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 |
|---|---|---|---|---|---|---|---|---|---|---|
trellominer/api/trello.py | xnoder/trellominer | 0 | 6900 | <reponame>xnoder/trellominer
import os
import requests
from trellominer.config import yaml
class HTTP(object):
def __init__(self):
self.config = yaml.read(os.getenv("TRELLO_CONFIG", default=os.path.join(os.path.expanduser('~'), ".trellominer.yaml")))
self.api_url = os.getenv("TRELLO_URL", defau... | import os
import requests
from trellominer.config import yaml
class HTTP(object):
def __init__(self):
self.config = yaml.read(os.getenv("TRELLO_CONFIG", default=os.path.join(os.path.expanduser('~'), ".trellominer.yaml")))
self.api_url = os.getenv("TRELLO_URL", default=self.config['api']['url'])... | none | 1 | 2.334571 | 2 | |
alexnet_guided_bp_vanilla.py | wezteoh/face_perception_thru_backprop | 0 | 6901 | import numpy as np
import tensorflow as tf
import os
from scipy.io import savemat
from scipy.io import loadmat
from scipy.misc import imread
from scipy.misc import imsave
from alexnet_face_classifier import *
import matplotlib.pyplot as plt
plt.switch_backend('agg')
class backprop_graph:
def __init__(self, num_... | import numpy as np
import tensorflow as tf
import os
from scipy.io import savemat
from scipy.io import loadmat
from scipy.misc import imread
from scipy.misc import imsave
from alexnet_face_classifier import *
import matplotlib.pyplot as plt
plt.switch_backend('agg')
class backprop_graph:
def __init__(self, num_... | none | 1 | 2.419791 | 2 | |
tests/test_sqlalchemy_registry.py | AferriDaniel/coaster | 48 | 6902 | <filename>tests/test_sqlalchemy_registry.py
"""Registry and RegistryMixin tests."""
from types import SimpleNamespace
import pytest
from coaster.db import db
from coaster.sqlalchemy import BaseMixin
from coaster.sqlalchemy.registry import Registry
# --- Fixtures -----------------------------------------------------... | <filename>tests/test_sqlalchemy_registry.py
"""Registry and RegistryMixin tests."""
from types import SimpleNamespace
import pytest
from coaster.db import db
from coaster.sqlalchemy import BaseMixin
from coaster.sqlalchemy.registry import Registry
# --- Fixtures -----------------------------------------------------... | en | 0.790282 | Registry and RegistryMixin tests. # --- Fixtures ------------------------------------------------------------------------- # noqa: N802 Callable registry with a positional parameter. # noqa: N802 Registry with property and a positional parameter. # noqa: N802 Registry with cached property and a positional parameter. # ... | 2.35712 | 2 |
home/migrations/0010_auto_20180206_1625.py | RomanMahar/personalsite | 0 | 6903 | <reponame>RomanMahar/personalsite
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-02-06 16:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0028_merge... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-02-06 16:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0028_merge'),
('home', '0009_remove_... | en | 0.696838 | # -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-02-06 16:25 | 1.70491 | 2 |
nesta/packages/misc_utils/tests/test_guess_sql_type.py | anniyanvr/nesta | 13 | 6904 | import pytest
from nesta.packages.misc_utils.guess_sql_type import guess_sql_type
@pytest.fixture
def int_data():
return [1,2,4,False]
@pytest.fixture
def text_data():
return ['a', True, 2,
('A very long sentence A very long sentence A '
'very long sentence A very long sentence'), 'd... | import pytest
from nesta.packages.misc_utils.guess_sql_type import guess_sql_type
@pytest.fixture
def int_data():
return [1,2,4,False]
@pytest.fixture
def text_data():
return ['a', True, 2,
('A very long sentence A very long sentence A '
'very long sentence A very long sentence'), 'd... | none | 1 | 2.426642 | 2 | |
api/controller/activity.py | DXCChina/pms | 27 | 6905 | # -*- coding: utf-8 -*-
'''活动管理接口'''
from flask import request
from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User
from model.role import identity
from flask_jwt_extended import (fresh_jwt_required)
def demand_activity_add(activity_id, data):
'''添加活动需求'''
for d... | # -*- coding: utf-8 -*-
'''活动管理接口'''
from flask import request
from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User
from model.role import identity
from flask_jwt_extended import (fresh_jwt_required)
def demand_activity_add(activity_id, data):
'''添加活动需求'''
for d... | zh | 0.359621 | # -*- coding: utf-8 -*- 活动管理接口 添加活动需求 # Demand.update(activityId=activity_id).where(Demand.id == demand_id).execute() 删除活动需求 # Demand.update(activityId=activity_id).where(Demand.id == demand_id).execute() 更新活动需求 # Demand.update(activityId=activity_id).where(Demand.id == demand_id).execute() 创建项目活动 更新项目活动 查询活动详情 ... | 2.434388 | 2 |
math/9. Palindrome number.py | Rage-ops/Leetcode-Solutions | 1 | 6906 | <filename>math/9. Palindrome number.py<gh_stars>1-10
# Easy
# https://leetcode.com/problems/palindrome-number/
# Time Complexity: O(log(x) to base 10)
# Space Complexity: O(1)
class Solution:
def isPalindrome(self, x: int) -> bool:
temp = x
rev = 0
while temp > 0:
rev = rev * 10 ... | <filename>math/9. Palindrome number.py<gh_stars>1-10
# Easy
# https://leetcode.com/problems/palindrome-number/
# Time Complexity: O(log(x) to base 10)
# Space Complexity: O(1)
class Solution:
def isPalindrome(self, x: int) -> bool:
temp = x
rev = 0
while temp > 0:
rev = rev * 10 ... | en | 0.753835 | # Easy # https://leetcode.com/problems/palindrome-number/ # Time Complexity: O(log(x) to base 10) # Space Complexity: O(1) | 3.656048 | 4 |
panoramisk/__init__.py | Eyepea/panoramisk | 0 | 6907 | from .manager import Manager # NOQA
from .call_manager import CallManager # NOQA
from . import fast_agi # NOQA
| from .manager import Manager # NOQA
from .call_manager import CallManager # NOQA
from . import fast_agi # NOQA
| ur | 0.230178 | # NOQA # NOQA # NOQA | 1.085414 | 1 |
prtg/client.py | kevinschoon/prtg-py | 0 | 6908 | <filename>prtg/client.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Python library for Paessler's PRTG (http://www.paessler.com/)
"""
import logging
import xml.etree.ElementTree as Et
from urllib import request
from prtg.cache import Cache
from prtg.models import Sensor, Device, Status, PrtgObject
from prtg.exceptions im... | <filename>prtg/client.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Python library for Paessler's PRTG (http://www.paessler.com/)
"""
import logging
import xml.etree.ElementTree as Et
from urllib import request
from prtg.cache import Cache
from prtg.models import Sensor, Device, Status, PrtgObject
from prtg.exceptions im... | en | 0.407505 | # -*- coding: utf-8 -*- Python library for Paessler's PRTG (http://www.paessler.com/) PRTG Connection Object Process the response from the server. # Catch KeyError and return finished Build the HTTP request. Make a single HTTP request # Recursively request until PRTG indicates "listend" def refresh(self, query): ... | 2.660876 | 3 |
template/misc.py | da-h/tf-boilerplate | 0 | 6909 | import tensorflow as tf
from tensorflow.python.training.session_run_hook import SessionRunArgs
# Define data loaders #####################################
# See https://gist.github.com/peterroelants/9956ec93a07ca4e9ba5bc415b014bcca
class IteratorInitializerHook(tf.train.SessionRunHook):
"""Hook to initialise data... | import tensorflow as tf
from tensorflow.python.training.session_run_hook import SessionRunArgs
# Define data loaders #####################################
# See https://gist.github.com/peterroelants/9956ec93a07ca4e9ba5bc415b014bcca
class IteratorInitializerHook(tf.train.SessionRunHook):
"""Hook to initialise data... | en | 0.603727 | # Define data loaders ##################################### # See https://gist.github.com/peterroelants/9956ec93a07ca4e9ba5bc415b014bcca Hook to initialise data iterator after Session is created. Initialise the iterator after the session has been created. # redefine summarysaverhook (for more accurate saving) Saves sum... | 2.708552 | 3 |
pyunitwizard/_private_tools/parsers.py | uibcdf/pyunitwizard | 0 | 6910 | <filename>pyunitwizard/_private_tools/parsers.py
parsers = ['openmm.unit', 'pint', 'unyt']
def digest_parser(parser: str) -> str:
""" Check if parser is correct."""
if parser is not None:
if parser.lower() in parsers:
return parser.lower()
else:
raise ValueError
else... | <filename>pyunitwizard/_private_tools/parsers.py
parsers = ['openmm.unit', 'pint', 'unyt']
def digest_parser(parser: str) -> str:
""" Check if parser is correct."""
if parser is not None:
if parser.lower() in parsers:
return parser.lower()
else:
raise ValueError
else... | en | 0.658327 | Check if parser is correct. | 2.707165 | 3 |
metric_wsd/utils/data_utils.py | bartonlin/MWSD | 4 | 6911 | '''
Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
Code taken from: https://github.com/facebookresearch/wsd-biencoders/blob/master/wsd_models/util.py
'''
import os
import re
impo... | '''
Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
Code taken from: https://github.com/facebookresearch/wsd-biencoders/blob/master/wsd_models/util.py
'''
import os
import re
impo... | en | 0.796671 | Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. Code taken from: https://github.com/facebookresearch/wsd-biencoders/blob/master/wsd_models/util.py #bert base #bert base #get set of... | 1.659143 | 2 |
examples/dehydrogenation/3-property-mappings/mappings_from_ontology/run_w_onto.py | TorgeirUstad/dlite | 0 | 6912 | #!/usr/bin/env python3
from typing import Dict, AnyStr
from pathlib import Path
from ontopy import get_ontology
import dlite
from dlite.mappings import make_instance
# Setup dlite paths
thisdir = Path(__file__).parent.absolute()
rootdir = thisdir.parent.parent
workflow1dir = rootdir / '1-simple-workflow'
entitiesdir... | #!/usr/bin/env python3
from typing import Dict, AnyStr
from pathlib import Path
from ontopy import get_ontology
import dlite
from dlite.mappings import make_instance
# Setup dlite paths
thisdir = Path(__file__).parent.absolute()
rootdir = thisdir.parent.parent
workflow1dir = rootdir / '1-simple-workflow'
entitiesdir... | en | 0.825421 | #!/usr/bin/env python3 # Setup dlite paths # Define the calculation Calculates reaction energies with data from Substance entity data is harvested from collection and mapped to Substance according to mappings. Args: reaction: dict with names of reactants and products ase keys and ... | 2.635552 | 3 |
forms.py | lendoo73/my_idea_boxes | 0 | 6913 | <filename>forms.py<gh_stars>0
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileRequired
from wtforms import StringField, PasswordField, BooleanField, TextAreaField, SubmitField, RadioField, HiddenField
from wtforms.fields.html5 import DateField, IntegerField
from wtforms.validators... | <filename>forms.py<gh_stars>0
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileRequired
from wtforms import StringField, PasswordField, BooleanField, TextAreaField, SubmitField, RadioField, HiddenField
from wtforms.fields.html5 import DateField, IntegerField
from wtforms.validators... | none | 1 | 2.658336 | 3 | |
5.analysis/scikit-multilearn-master/skmultilearn/adapt/brknn.py | fullmooncj/textmining_edu | 0 | 6914 | <reponame>fullmooncj/textmining_edu<filename>5.analysis/scikit-multilearn-master/skmultilearn/adapt/brknn.py
from builtins import range
from ..base import MLClassifierBase
from ..utils import get_matrix_in_format
from sklearn.neighbors import NearestNeighbors
import scipy.sparse as sparse
import numpy as np
class Bina... | from builtins import range
from ..base import MLClassifierBase
from ..utils import get_matrix_in_format
from sklearn.neighbors import NearestNeighbors
import scipy.sparse as sparse
import numpy as np
class BinaryRelevanceKNN(MLClassifierBase):
"""Binary Relevance adapted kNN Multi-Label Classifier."""
def __i... | en | 0.783498 | Binary Relevance adapted kNN Multi-Label Classifier. # Number of neighbours Fit classifier with training data Internally this method uses a sparse CSC representation for y (:py:class:`scipy.sparse.csc_matrix`). :param X: input features :type X: dense or sparse matrix (n_samples, n_feat... | 3.191593 | 3 |
groclient/constants.py | eric-gro/api-client | 18 | 6915 | """Constants about the Gro ontology that can be imported and re-used anywhere."""
REGION_LEVELS = {
'world': 1,
'continent': 2,
'country': 3,
'province': 4, # Equivalent to state in the United States
'district': 5, # Equivalent to county in the United States
'city': 6,
'market': 7,
'o... | """Constants about the Gro ontology that can be imported and re-used anywhere."""
REGION_LEVELS = {
'world': 1,
'continent': 2,
'country': 3,
'province': 4, # Equivalent to state in the United States
'district': 5, # Equivalent to county in the United States
'city': 6,
'market': 7,
'o... | en | 0.915338 | Constants about the Gro ontology that can be imported and re-used anywhere. # Equivalent to state in the United States # Equivalent to county in the United States | 1.670935 | 2 |
asv_bench/benchmarks/tslibs/period.py | CitizenB/pandas | 6 | 6916 | """
Period benchmarks that rely only on tslibs. See benchmarks.period for
Period benchmarks that rely on other parts fo pandas.
"""
from pandas import Period
from pandas.tseries.frequencies import to_offset
class PeriodProperties:
params = (
["M", "min"],
[
"year",
"mont... | """
Period benchmarks that rely only on tslibs. See benchmarks.period for
Period benchmarks that rely on other parts fo pandas.
"""
from pandas import Period
from pandas.tseries.frequencies import to_offset
class PeriodProperties:
params = (
["M", "min"],
[
"year",
"mont... | en | 0.777882 | Period benchmarks that rely only on tslibs. See benchmarks.period for Period benchmarks that rely on other parts fo pandas. | 2.672826 | 3 |
Bugscan_exploits-master/exp_list/exp-1788.py | csadsl/poc_exp | 11 | 6917 | <reponame>csadsl/poc_exp
#/usr/bin/python
#-*- coding: utf-8 -*-
#Refer http://www.wooyun.org/bugs/wooyun-2015-0137140
#__Author__ = 上善若水
#_PlugName_ = whezeip Plugin
#_FileName_ = whezeip.py
def assign(service, arg):
if service == "whezeip":
return True, arg
def audit(arg):
raw = '''
... | #/usr/bin/python
#-*- coding: utf-8 -*-
#Refer http://www.wooyun.org/bugs/wooyun-2015-0137140
#__Author__ = 上善若水
#_PlugName_ = whezeip Plugin
#_FileName_ = whezeip.py
def assign(service, arg):
if service == "whezeip":
return True, arg
def audit(arg):
raw = '''
POST /defaultroot/custom... | en | 0.326892 | #/usr/bin/python #-*- coding: utf-8 -*- #Refer http://www.wooyun.org/bugs/wooyun-2015-0137140 #__Author__ = 上善若水 #_PlugName_ = whezeip Plugin #_FileName_ = whezeip.py POST /defaultroot/customize/formClassUpload.jsp?flag=1&returnField=null HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42... | 1.940013 | 2 |
3-working-with-lists/zip_tuples.py | thecodingsim/learn-python | 0 | 6918 | <reponame>thecodingsim/learn-python
# Use zip() to create a new variable called names_and_dogs_names that combines owners and dogs_names lists into a zip object.
# Then, create a new variable named list_of_names_and_dogs_names by calling the list() function on names_and_dogs_names.
# Print list_of_names_and_dogs_name... | # Use zip() to create a new variable called names_and_dogs_names that combines owners and dogs_names lists into a zip object.
# Then, create a new variable named list_of_names_and_dogs_names by calling the list() function on names_and_dogs_names.
# Print list_of_names_and_dogs_names.
owners = ["Jenny", "Alexus", "Sa... | en | 0.879218 | # Use zip() to create a new variable called names_and_dogs_names that combines owners and dogs_names lists into a zip object. # Then, create a new variable named list_of_names_and_dogs_names by calling the list() function on names_and_dogs_names. # Print list_of_names_and_dogs_names. | 4.37907 | 4 |
setup.py | abhiomkar/couchdbkit | 1 | 6919 | # -*- coding: utf-8 -
#
# This file is part of couchdbkit released under the MIT license.
# See the NOTICE for more information.
import os
import sys
if not hasattr(sys, 'version_info') or sys.version_info < (2, 5, 0, 'final'):
raise SystemExit("couchdbkit requires Python 2.5 or later.")
from setuptools import ... | # -*- coding: utf-8 -
#
# This file is part of couchdbkit released under the MIT license.
# See the NOTICE for more information.
import os
import sys
if not hasattr(sys, 'version_info') or sys.version_info < (2, 5, 0, 'final'):
raise SystemExit("couchdbkit requires Python 2.5 or later.")
from setuptools import ... | en | 0.442778 | # -*- coding: utf-8 - # # This file is part of couchdbkit released under the MIT license. # See the NOTICE for more information. [couchdbkit.consumers] sync=couchdbkit.consumer.sync:SyncConsumer eventlet=couchdbkit.consumer.ceventlet:EventletConsumer gevent=couchdbkit.consumer.cgevent:GeventConsumer | 1.439568 | 1 |
tests/integration/test_infrastructure_persistence.py | othercodes/sample-todo-list-hexagonal-achitecture | 0 | 6920 | <reponame>othercodes/sample-todo-list-hexagonal-achitecture<gh_stars>0
from typing import Optional
from complexheart.domain.criteria import Criteria
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker
from to_do_list.tasks.domain.models import Task
from to... | from typing import Optional
from complexheart.domain.criteria import Criteria
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker
from to_do_list.tasks.domain.models import Task
from to_do_list.tasks.infrastructure.persistence.relational import RelationalT... | none | 1 | 2.133212 | 2 | |
wagtail_jinja2/extensions.py | minervaproject/wagtail-jinja2-extensions | 6 | 6921 | <filename>wagtail_jinja2/extensions.py
from jinja2.ext import Extension
from jinja2 import nodes
from jinja2 import Markup
from wagtail.wagtailadmin.templatetags.wagtailuserbar import wagtailuserbar as original_wagtailuserbar
from wagtail.wagtailimages.models import Filter, SourceImageIOError
class WagtailUserBarExt... | <filename>wagtail_jinja2/extensions.py
from jinja2.ext import Extension
from jinja2 import nodes
from jinja2 import Markup
from wagtail.wagtailadmin.templatetags.wagtailuserbar import wagtailuserbar as original_wagtailuserbar
from wagtail.wagtailimages.models import Filter, SourceImageIOError
class WagtailUserBarExt... | en | 0.824443 | # It's fairly routine for people to pull down remote databases to their # local dev versions without retrieving the corresponding image files. # In such a case, we would get a SourceImageIOError at the point where we try to # create the resized version of a non-existent image. Since this is a # bit catastrophic for a m... | 2.130375 | 2 |
rta/provision/__init__.py | XiaoguTech/rta-sandbox | 0 | 6922 | from rta.provision.utils import *
from rta.provision.passwd import *
from rta.provision.influxdb import *
from rta.provision.grafana import *
from rta.provision.kapacitor import *
| from rta.provision.utils import *
from rta.provision.passwd import *
from rta.provision.influxdb import *
from rta.provision.grafana import *
from rta.provision.kapacitor import *
| none | 1 | 1.064753 | 1 | |
nn_dataflow/tests/unit_test/test_network.py | Pingziwalk/nn_dataflow | 170 | 6923 | """ $lic$
Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of
Stanford University
This program is free software: you can redistribute it and/or modify it under
the terms of the Modified BSD-3 License as published by the Open Source
Initiative.
This program is distributed in the hope that it wi... | """ $lic$
Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of
Stanford University
This program is free software: you can redistribute it and/or modify it under
the terms of the Modified BSD-3 License as published by the Open Source
Initiative.
This program is distributed in the hope that it wi... | en | 0.618201 | $lic$ Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of Stanford University This program is free software: you can redistribute it and/or modify it under the terms of the Modified BSD-3 License as published by the Open Source Initiative. This program is distributed in the hope that it will b... | 2.502663 | 3 |
apps/division/urls.py | Jingil-Integrated-Management/JIM_backend | 0 | 6924 | from django.urls import path
from .views import DivisionListCreateAPIView, DivisionRetrieveUpdateDestroyAPIView, MainDivisionListAPIView
urlpatterns = [
path('division/', DivisionListCreateAPIView.as_view()),
path('division/<division_pk>', DivisionRetrieveUpdateDestroyAPIView.as_view()),
path('division/m... | from django.urls import path
from .views import DivisionListCreateAPIView, DivisionRetrieveUpdateDestroyAPIView, MainDivisionListAPIView
urlpatterns = [
path('division/', DivisionListCreateAPIView.as_view()),
path('division/<division_pk>', DivisionRetrieveUpdateDestroyAPIView.as_view()),
path('division/m... | none | 1 | 1.597855 | 2 | |
sympy/solvers/tests/test_pde.py | nashalex/sympy | 8,323 | 6925 | <gh_stars>1000+
from sympy import (Derivative as D, Eq, exp, sin,
Function, Symbol, symbols, cos, log)
from sympy.core import S
from sympy.solvers.pde import (pde_separate, pde_separate_add, pde_separate_mul,
pdsolve, classify_pde, checkpdesol)
from sympy.testing.pytest import raises
a, b, c, x, y = symbols('... | from sympy import (Derivative as D, Eq, exp, sin,
Function, Symbol, symbols, cos, log)
from sympy.core import S
from sympy.solvers.pde import (pde_separate, pde_separate_add, pde_separate_mul,
pdsolve, classify_pde, checkpdesol)
from sympy.testing.pytest import raises
a, b, c, x, y = symbols('a b c x y')
def... | en | 0.579629 | # Something simple :) # Duplicate arguments in functions # Wrong number of arguments # Wrong variables: [x, y] -> [x, z] # wave equation # Laplace equation in cylindrical coords # Separate z # Lets use the result to create a new equation... # ...and separate theta... # ...or r... # When more number of hints are added, ... | 2.576766 | 3 |
GCN/GCN.py | EasternJournalist/learn-deep-learning | 6 | 6926 | import torch
import torch.nn.functional as F
import pandas as pd
import numpy as np
from torch_geometric.data import Data
from torch_geometric.nn import GCNConv, PairNorm
from torch_geometric.utils.undirected import to_undirected
import random
import matplotlib.pyplot as plt
data_name = 'citeseer' # 'cora' or 'ci... | import torch
import torch.nn.functional as F
import pandas as pd
import numpy as np
from torch_geometric.data import Data
from torch_geometric.nn import GCNConv, PairNorm
from torch_geometric.utils.undirected import to_undirected
import random
import matplotlib.pyplot as plt
data_name = 'citeseer' # 'cora' or 'ci... | en | 0.514091 | # 'cora' or 'citeseer' # num layers # self loop # pair norm # drop edge # activation fn # undirected # Train # Test | 2.259117 | 2 |
esg_leipzig_homepage_2015/views.py | ESG-Leipzig/Homepage-2015 | 0 | 6927 | import datetime
import json
from django.conf import settings
from django.http import Http404
from django.utils import timezone
from django.views import generic
from .models import Event, FlatPage, News
class HomeView(generic.ListView):
"""
View for the first page called 'Home'.
"""
context_object_na... | import datetime
import json
from django.conf import settings
from django.http import Http404
from django.utils import timezone
from django.views import generic
from .models import Event, FlatPage, News
class HomeView(generic.ListView):
"""
View for the first page called 'Home'.
"""
context_object_na... | en | 0.73902 | View for the first page called 'Home'. Returns a queryset of all future events that should appear on home. Uses settings.EVENT_DELAY_IN_MINUTES to determine the range. Adds all news to the context. View for a calendar with all events. Returns the template context. Adds event data as JSON for use in Java... | 2.380449 | 2 |
train.py | ronniechong/tensorflow-trainer | 0 | 6928 | <filename>train.py
from dotenv import load_dotenv
load_dotenv()
from flask import Flask, flash, request, redirect, url_for
from flask_ngrok import run_with_ngrok
from flask_cors import CORS
from werkzeug.utils import secure_filename
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applicatio... | <filename>train.py
from dotenv import load_dotenv
load_dotenv()
from flask import Flask, flash, request, redirect, url_for
from flask_ngrok import run_with_ngrok
from flask_cors import CORS
from werkzeug.utils import secure_filename
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applicatio... | en | 0.366069 | # run_with_ngrok(app) # https://github.com/gstaff/flask-ngrok/issues/2 # Load via checkpoints # Load saved model # print(category_names[count] + ': ' + "{:.2f}".format(a)) # fh.close() # print(category_names[count] + ': ' + "{:.2f}".format(a)) | 2.227043 | 2 |
src/models/train_model.py | sandorfoldi/chess_positions_recognition | 0 | 6929 | import random
import matplotlib.pyplot as plt
import wandb
import hydra
import torch
import torch.utils.data as data_utils
from model import ChessPiecePredictor
from torch import nn, optim
from google.cloud import storage
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datas... | import random
import matplotlib.pyplot as plt
import wandb
import hydra
import torch
import torch.utils.data as data_utils
from model import ChessPiecePredictor
from torch import nn, optim
from google.cloud import storage
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datas... | en | 0.830413 | # in case we use cuda to train on gpu # accuracy # accuracy # plotting | 2.240149 | 2 |
fairseq/scoring/__init__.py | fairseq-FT/fairseq | 33 | 6930 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import importlib
import os
from abc import ABC, abstractmethod
from fairseq import registry
from omegaconf import DictConfig
class BaseSco... | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import importlib
import os
from abc import ABC, abstractmethod
from fairseq import registry
from omegaconf import DictConfig
class BaseSco... | en | 0.870177 | # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # automatically import any Python files in the current directory | 2.229563 | 2 |
dfn/tests/test_FractureNetworkThermal.py | richardhaslam/discrete-fracture-network | 1 | 6931 | import copy
import unittest
import networkx as nx
import numpy as np
from scipy.special import erf
from dfn import Fluid, FractureNetworkThermal
class TestFractureNetworkThermal(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestFractureNetworkThermal, self).__init__(*args, **kwargs)
... | import copy
import unittest
import networkx as nx
import numpy as np
from scipy.special import erf
from dfn import Fluid, FractureNetworkThermal
class TestFractureNetworkThermal(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestFractureNetworkThermal, self).__init__(*args, **kwargs)
... | en | 0.732333 | # fluid properties # reservoir properties # first network # second network Return a copy of the fracture networks. Return networks with the mass flow calculated. Reverse the node order for given segments. Test if TypeError is raised for networks without flow calculated. Test if valueError is raised for networks with ne... | 2.392211 | 2 |
dataapi/AWS/getawsdata.py | gusamarante/Quantequim | 296 | 6932 | """
Author: <NAME>
"""
import numpy as np
import pandas as pd
from datetime import datetime
class TrackerFeeder(object):
"""
Feeder for the trackers of the FinanceHub database.
"""
def __init__(self, db_connect):
"""
Feeder construction
:param db_connect: sql connection engin... | """
Author: <NAME>
"""
import numpy as np
import pandas as pd
from datetime import datetime
class TrackerFeeder(object):
"""
Feeder for the trackers of the FinanceHub database.
"""
def __init__(self, db_connect):
"""
Feeder construction
:param db_connect: sql connection engin... | en | 0.718995 | Author: <NAME> Feeder for the trackers of the FinanceHub database. Feeder construction :param db_connect: sql connection engine from sqlalchemy grabs trackers from the FH database :param fh_ticker: str or list with the tickers from the database trackers :return: pandas DataFrame with tickers on ... | 3.138746 | 3 |
assets/utils/config.py | mklew/quickstart-data-lake-qubole | 0 | 6933 | <reponame>mklew/quickstart-data-lake-qubole<filename>assets/utils/config.py
from configparser import ConfigParser
CONFIG_INT_KEYS = {
'hadoop_max_nodes_count',
'hadoop_ebs_volumes_count',
'hadoop_ebs_volume_size',
'spark_max_nodes_count',
'spark_ebs_volumes_count',
'spark_ebs_volume_size'
}
d... | from configparser import ConfigParser
CONFIG_INT_KEYS = {
'hadoop_max_nodes_count',
'hadoop_ebs_volumes_count',
'hadoop_ebs_volume_size',
'spark_max_nodes_count',
'spark_ebs_volumes_count',
'spark_ebs_volume_size'
}
def read_config(config_path):
parser = ConfigParser()
parser.read(con... | none | 1 | 2.968939 | 3 | |
app/blueprints/admin_api/__init__.py | lvyaoo/api-demo | 0 | 6934 | <gh_stars>0
from flask import Blueprint
from .hooks import admin_auth
from ...api_utils import *
bp_admin_api = Blueprint('bp_admin_api', __name__)
bp_admin_api.register_error_handler(APIError, handle_api_error)
bp_admin_api.register_error_handler(500, handle_500_error)
bp_admin_api.register_error_handler(400, handl... | from flask import Blueprint
from .hooks import admin_auth
from ...api_utils import *
bp_admin_api = Blueprint('bp_admin_api', __name__)
bp_admin_api.register_error_handler(APIError, handle_api_error)
bp_admin_api.register_error_handler(500, handle_500_error)
bp_admin_api.register_error_handler(400, handle_400_error)... | none | 1 | 1.926918 | 2 | |
project/starter_code/student_utils.py | nihaagarwalla/nd320-c1-emr-data-starter | 0 | 6935 | <reponame>nihaagarwalla/nd320-c1-emr-data-starter<filename>project/starter_code/student_utils.py
import pandas as pd
import numpy as np
import os
import tensorflow as tf
import functools
####### STUDENTS FILL THIS OUT ######
#Question 3
def reduce_dimension_ndc(df, ndc_df):
'''
df: pandas dataframe, input data... | import pandas as pd
import numpy as np
import os
import tensorflow as tf
import functools
####### STUDENTS FILL THIS OUT ######
#Question 3
def reduce_dimension_ndc(df, ndc_df):
'''
df: pandas dataframe, input dataset
ndc_df: pandas dataframe, drug code dataset used for mapping in generic names
return:... | en | 0.507182 | ####### STUDENTS FILL THIS OUT ###### #Question 3 df: pandas dataframe, input dataset ndc_df: pandas dataframe, drug code dataset used for mapping in generic names return: df: pandas dataframe, output dataframe with joined generic drug name # ndc_df["Dosage Form"]= ndc_df["Dosage Form"].str.replace(... | 3.14848 | 3 |
core_tools/utility/plotting/plot_1D.py | peendebak/core_tools | 0 | 6936 | <gh_stars>0
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import copy
from core_tools.utility.plotting.plot_settings import plot_layout, graph_settings_1D, _1D_raw_plot_data
from core_tools.utility.plotting.plot_general import _data_plotter
class plotter_1D(_data_plotter):
def __init__(... | import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import copy
from core_tools.utility.plotting.plot_settings import plot_layout, graph_settings_1D, _1D_raw_plot_data
from core_tools.utility.plotting.plot_general import _data_plotter
class plotter_1D(_data_plotter):
def __init__(self, plt_la... | en | 0.221148 | #default settings # ax.errorbar(a, c, yerr = b/10,ecolor='g',linewidth=1.2,elinewidth=0.7) # TODO add log scale support !!! # global settings # a.plot() # a.plot() # a.plot() | 2.374681 | 2 |
v0.3/achat.py | Forec/lan-ichat | 63 | 6937 | <gh_stars>10-100
# last edit date: 2016/11/2
# author: Forec
# LICENSE
# Copyright (c) 2015-2017, Forec <<EMAIL>>
# Permission to use, copy, modify, and/or distribute this code for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all c... | # last edit date: 2016/11/2
# author: Forec
# LICENSE
# Copyright (c) 2015-2017, Forec <<EMAIL>>
# Permission to use, copy, modify, and/or distribute this code for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
# THE SOF... | en | 0.60546 | # last edit date: 2016/11/2 # author: Forec # LICENSE # Copyright (c) 2015-2017, Forec <<EMAIL>> # Permission to use, copy, modify, and/or distribute this code for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # THE SOFTW... | 2.423162 | 2 |
gdb/util.py | dennereed/paleocore | 1 | 6938 | <filename>gdb/util.py
from gdb.models import *
| <filename>gdb/util.py
from gdb.models import *
| none | 1 | 1.004457 | 1 | |
iwg_blog/blog/views/__init__.py | razortheory/who-iwg-webapp | 0 | 6939 | <gh_stars>0
from .base import ArticleView, ArticlePreviewView, ArticleListView, SearchView, LandingView, \
CategoryView, TagView, SubscribeForUpdates, UnsubscribeFromUpdates
from .ajax import GetArticleSlugAjax, TagsAutocompleteAjax
from .errors import page_not_found, server_error
| from .base import ArticleView, ArticlePreviewView, ArticleListView, SearchView, LandingView, \
CategoryView, TagView, SubscribeForUpdates, UnsubscribeFromUpdates
from .ajax import GetArticleSlugAjax, TagsAutocompleteAjax
from .errors import page_not_found, server_error | none | 1 | 1.072664 | 1 | |
io_import_rbsp/rbsp/rpak_materials.py | snake-biscuits/io_import_rbsp | 7 | 6940 | <reponame>snake-biscuits/io_import_rbsp
# by MrSteyk & Dogecore
# TODO: extraction instructions & testing
import json
import os.path
from typing import List
import bpy
loaded_materials = {}
MATERIAL_LOAD_PATH = "" # put your path here
# normal has special logic
MATERIAL_INPUT_LINKING = {
"color": "Base Color"... | # by MrSteyk & Dogecore
# TODO: extraction instructions & testing
import json
import os.path
from typing import List
import bpy
loaded_materials = {}
MATERIAL_LOAD_PATH = "" # put your path here
# normal has special logic
MATERIAL_INPUT_LINKING = {
"color": "Base Color",
"rough": "Roughness",
"spec": ... | en | 0.683416 | # by MrSteyk & Dogecore # TODO: extraction instructions & testing # put your path here # normal has special logic # raise ValueError(f"Material data for material {material_name} does not exist!") # print(material_name, mat_data) # data link # normal link | 2.433336 | 2 |
initcmds/models.py | alldevic/mtauksync | 0 | 6941 | <filename>initcmds/models.py
from django.db import models
TASK_STATUS = (
("c", "created"),
("p", "progress"),
("s", "success"),
("f", "failed")
)
class TaskModel(models.Model):
lastrunned = models.DateTimeField(
"lastrunned", auto_now=False, auto_now_add=False)
taskname = models.Ch... | <filename>initcmds/models.py
from django.db import models
TASK_STATUS = (
("c", "created"),
("p", "progress"),
("s", "success"),
("f", "failed")
)
class TaskModel(models.Model):
lastrunned = models.DateTimeField(
"lastrunned", auto_now=False, auto_now_add=False)
taskname = models.Ch... | none | 1 | 2.481318 | 2 | |
aardvark/conf/reaper_conf.py | ttsiouts/aardvark | 0 | 6942 | # Copyright (c) 2018 European Organization for Nuclear Research.
# 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/LIC... | # Copyright (c) 2018 European Organization for Nuclear Research.
# 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/LIC... | en | 0.876332 | # Copyright (c) 2018 European Organization for Nuclear Research. # 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/LIC... | 2.240803 | 2 |
src/Data.py | jhlee93/WNet-cGAN-Keras | 7 | 6943 | <filename>src/Data.py
import glob
import numpy as np
class Data:
def __init__(self, path, random=False):
"""
input:
path: path to the folder with subfolders: DSM, PAN, LABEL
max_num: int, num of samples
random: bool, to load samples randomly or fro... | <filename>src/Data.py
import glob
import numpy as np
class Data:
def __init__(self, path, random=False):
"""
input:
path: path to the folder with subfolders: DSM, PAN, LABEL
max_num: int, num of samples
random: bool, to load samples randomly or fro... | en | 0.801272 | input:
path: path to the folder with subfolders: DSM, PAN, LABEL
max_num: int, num of samples
random: bool, to load samples randomly or from 0 to num_max function: load max_num of XY into lists
output: list of numpy arrays, X (images) and Y (labels) | 3.079846 | 3 |
count_files.py | xuannianc/keras-retinanet | 0 | 6944 | <filename>count_files.py
import csv
vat_filenames = set()
train_csv_filename = 'train_annotations.csv'
val_csv_filename = 'val_annotations.csv'
for csv_filename in [train_csv_filename, val_csv_filename]:
for line in csv.reader(open(csv_filename)):
vat_filename = line[0].split('/')[-1]
vat_filenames... | <filename>count_files.py
import csv
vat_filenames = set()
train_csv_filename = 'train_annotations.csv'
val_csv_filename = 'val_annotations.csv'
for csv_filename in [train_csv_filename, val_csv_filename]:
for line in csv.reader(open(csv_filename)):
vat_filename = line[0].split('/')[-1]
vat_filenames... | none | 1 | 2.691944 | 3 | |
liberaforms/views/admin.py | ngi-nix/liberaforms | 3 | 6945 | """
This file is part of LiberaForms.
# SPDX-FileCopyrightText: 2020 LiberaForms.org
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
import os, json
from flask import g, request, render_template, redirect
from flask import session, flash, Blueprint
from flask import send_file, after_this_request
from flask_babel imp... | """
This file is part of LiberaForms.
# SPDX-FileCopyrightText: 2020 LiberaForms.org
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
import os, json
from flask import g, request, render_template, redirect
from flask import session, flash, Blueprint
from flask import send_file, after_this_request
from flask_babel imp... | en | 0.647233 | This file is part of LiberaForms. # SPDX-FileCopyrightText: 2020 LiberaForms.org # SPDX-License-Identifier: AGPL-3.0-or-later User management # current_user cannot disable themself # current_user cannot remove their own admin permission Form management Invitations #pprint(token) # i18n: Invitation to <EMAIL> deleted O... | 2.278552 | 2 |
python/zephyr/datasets/score_dataset.py | r-pad/zephyr | 18 | 6946 | <filename>python/zephyr/datasets/score_dataset.py
import os, copy
import cv2
from functools import partial
import numpy as np
import torch
import torchvision
from torch.utils.data import Dataset
from zephyr.data_util import to_np, vectorize, img2uint8
from zephyr.utils import torch_norm_fast
from zephyr.ut... | <filename>python/zephyr/datasets/score_dataset.py
import os, copy
import cv2
from functools import partial
import numpy as np
import torch
import torchvision
from torch.utils.data import Dataset
from zephyr.data_util import to_np, vectorize, img2uint8
from zephyr.utils import torch_norm_fast
from zephyr.ut... | en | 0.564564 | # About timing # Use PointNet dataset For aggregated features Data For PointNet Data # indices of point_x channels that define coordinates # indices of point_x channels that are specific to the object model Mask channel # valid_proj.unsqueeze(-1).float(), # valid_depth.unsqueeze(-1).float(), XYZ channel Data channel Tr... | 2.127939 | 2 |
em Python/Roteiro7/Roteiro7__testes_dijkstra.py | GuilhermeEsdras/Grafos | 0 | 6947 | from Roteiro7.Roteiro7__funcoes import GrafoComPesos
# .:: Arquivo de Testes do Algoritmo de Dijkstra ::. #
# --------------------------------------------------------------------------- #
grafo_aula = GrafoComPesos(
['E', 'A', 'B', 'C', 'D'],
{
'E-A': 1,
'E-C': 10,
'A-B': 2,
'B... | from Roteiro7.Roteiro7__funcoes import GrafoComPesos
# .:: Arquivo de Testes do Algoritmo de Dijkstra ::. #
# --------------------------------------------------------------------------- #
grafo_aula = GrafoComPesos(
['E', 'A', 'B', 'C', 'D'],
{
'E-A': 1,
'E-C': 10,
'A-B': 2,
'B... | pt | 0.182132 | # .:: Arquivo de Testes do Algoritmo de Dijkstra ::. # # --------------------------------------------------------------------------- # | 3.183696 | 3 |
QScreenCast/spyder/api.py | awinia-github/QScreenCast | 0 | 6948 | <filename>QScreenCast/spyder/api.py
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © <NAME>
# Licensed under the terms of the MIT License
# ----------------------------------------------------------------------------
"""
Python QtScreenCaster Spyder A... | <filename>QScreenCast/spyder/api.py
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © <NAME>
# Licensed under the terms of the MIT License
# ----------------------------------------------------------------------------
"""
Python QtScreenCaster Spyder A... | en | 0.37437 | # -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright © <NAME> # Licensed under the terms of the MIT License # ---------------------------------------------------------------------------- Python QtScreenCaster Spyder API. | 1.24221 | 1 |
setup.py | aaron19950321/ICOM | 5 | 6949 | <filename>setup.py<gh_stars>1-10
import os, os.path
import subprocess
from distutils.core import setup
from py2exe.build_exe import py2exe
PROGRAM_NAME = 'icom_app'
PROGRAM_DESC = 'simple icom app'
NSIS_SCRIPT_TEMPLATE = r"""
!define py2exeOutputDirectory '{output_dir}\'
!define exe '{program_name}.exe'
... | <filename>setup.py<gh_stars>1-10
import os, os.path
import subprocess
from distutils.core import setup
from py2exe.build_exe import py2exe
PROGRAM_NAME = 'icom_app'
PROGRAM_DESC = 'simple icom app'
NSIS_SCRIPT_TEMPLATE = r"""
!define py2exeOutputDirectory '{output_dir}\'
!define exe '{program_name}.exe'
... | en | 0.690809 | !define py2exeOutputDirectory '{output_dir}\'
!define exe '{program_name}.exe'
; Uses solid LZMA compression. Can be slow, use discretion.
SetCompressor /SOLID lzma
; Sets the title bar text (although NSIS seems to append "Installer")
Caption "{program_desc}"
Name '{program_name}'
OutFile ${{exe}}
Icon '{... | 1.949931 | 2 |
src/lingcomp/farm/features.py | CharlottePouw/interpreting-complexity | 2 | 6950 | <gh_stars>1-10
import torch
from farm.data_handler.samples import Sample
from farm.modeling.prediction_head import RegressionHead
class FeaturesEmbeddingSample(Sample):
def __init__(self, id, clear_text, tokenized=None, features=None, feat_embeds=None):
super().__init__(id, clear_text, tokenized, features... | import torch
from farm.data_handler.samples import Sample
from farm.modeling.prediction_head import RegressionHead
class FeaturesEmbeddingSample(Sample):
def __init__(self, id, clear_text, tokenized=None, features=None, feat_embeds=None):
super().__init__(id, clear_text, tokenized, features)
self.... | en | 0.904812 | A regression head mixing [CLS] representation and explicit features for prediction | 2.529802 | 3 |
manager/tests/api_view_test_classes.py | UN-ICC/icc-digital-id-manager | 3 | 6951 | import pytest
from rest_framework import status
from rest_framework.test import APIClient
class TestBase:
__test__ = False
path = None
get_data = {}
put_data = {}
post_data = {}
delete_data = {}
requires_auth = True
implements_retrieve = False
implements_create = False
implemen... | import pytest
from rest_framework import status
from rest_framework.test import APIClient
class TestBase:
__test__ = False
path = None
get_data = {}
put_data = {}
post_data = {}
delete_data = {}
requires_auth = True
implements_retrieve = False
implements_create = False
implemen... | none | 1 | 2.244336 | 2 | |
dashboard/dashboard.py | TrustyJAID/Toxic-Cogs | 0 | 6952 | <reponame>TrustyJAID/Toxic-Cogs
from collections import defaultdict
import discord
from redbot.core import Config, checks, commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import box, humanize_list, inline
from abc import ABC
# ABC Mixins
from dashboard.abc.abc import MixinMeta... | from collections import defaultdict
import discord
from redbot.core import Config, checks, commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import box, humanize_list, inline
from abc import ABC
# ABC Mixins
from dashboard.abc.abc import MixinMeta
from dashboard.abc.mixin impor... | en | 0.904764 | # ABC Mixins # Command Mixins # RPC Mixins This allows the metaclass used for proper type detection to coexist with discord.py's
metaclass. # Thanks to Flare for showing how to use group commands across multiple files. If this breaks, its his fault | 2.040998 | 2 |
algorithms/162.Find-Peak-Element/Python/solution_2.py | hopeness/leetcode | 0 | 6953 | <gh_stars>0
"""
https://leetcode.com/problems/find-peak-element/submissions/
"""
from typing import List
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
l, r = 0, len(nums)-1
while l < r:
lmid = (l + r) // 2
rmid = lmid + 1
if nums[lmid] < num... | """
https://leetcode.com/problems/find-peak-element/submissions/
"""
from typing import List
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
l, r = 0, len(nums)-1
while l < r:
lmid = (l + r) // 2
rmid = lmid + 1
if nums[lmid] < nums[rmid]:
... | en | 0.554907 | https://leetcode.com/problems/find-peak-element/submissions/ | 3.229828 | 3 |
data_loader.py | vinbigdata-medical/MIDL2021-Xray-Classification | 4 | 6954 | from torchvision.datasets import ImageFolder
from torchvision import transforms
import random
import os
import torch
from torch.utils.data.dataloader import DataLoader
from utils import constants, get_default_device
from image_folder_with_path import ImageFolderWithPaths
def to_device(data, device):
"""Move tensor... | from torchvision.datasets import ImageFolder
from torchvision import transforms
import random
import os
import torch
from torch.utils.data.dataloader import DataLoader
from utils import constants, get_default_device
from image_folder_with_path import ImageFolderWithPaths
def to_device(data, device):
"""Move tensor... | en | 0.484924 | Move tensor(s) to chosen device wrap a Dataloader to move data to a device yield a batch of data after moving it to device return number of batch size # testing_dataset = ImageFolder(constants.DATA_PATH + constants.TEST_PATH, transform=test_transforms) # training_dataset = ImageFolderWithPaths(constants.DATA_PATH + con... | 2.728693 | 3 |
calliope/test/test_analysis.py | sjpfenninger/calliope | 1 | 6955 | # import matplotlib
# matplotlib.use('Qt5Agg') # Prevents `Invalid DISPLAY variable` errors
import pytest
import tempfile
from calliope import Model
from calliope.utils import AttrDict
from calliope import analysis
from . import common
from .common import assert_almost_equal, solver, solver_io
import matplotlib.p... | # import matplotlib
# matplotlib.use('Qt5Agg') # Prevents `Invalid DISPLAY variable` errors
import pytest
import tempfile
from calliope import Model
from calliope.utils import AttrDict
from calliope import analysis
from . import common
from .common import assert_almost_equal, solver, solver_io
import matplotlib.p... | en | 0.794737 | # import matplotlib # matplotlib.use('Qt5Agg') # Prevents `Invalid DISPLAY variable` errors # Prevents `Invalid DISPLAY variable` errors locations: 1: techs: ['ccgt', 'demand_power'] override: ccgt: constraints:... | 2.032199 | 2 |
mol/data/reader.py | TzuTingWei/mol | 0 | 6956 | <reponame>TzuTingWei/mol
import os
from mol.util import read_xyz
dirname = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(dirname, 'look_and_say.dat')
with open(filename, 'r') as handle:
look_and_say = handle.read()
def get_molecule(filename):
return read_xyz(os.path.join(dirname, filename + ".... | import os
from mol.util import read_xyz
dirname = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(dirname, 'look_and_say.dat')
with open(filename, 'r') as handle:
look_and_say = handle.read()
def get_molecule(filename):
return read_xyz(os.path.join(dirname, filename + ".xyz")) | none | 1 | 2.831244 | 3 | |
cinder/tests/unit/targets/test_spdknvmf.py | lightsey/cinder | 3 | 6957 | # 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
# d... | # 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
# d... | en | 0.859654 | # 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 # d... | 1.524099 | 2 |
server/algos/euler/transformer.py | yizhang7210/Acre | 2 | 6958 | """ This is algos.euler.transformer module.
This module is responsible for transforming raw candle data into training
samples usable to the Euler algorithm.
"""
import datetime
import decimal
from algos.euler.models import training_samples as ts
from core.models import instruments
from datasource.models import... | """ This is algos.euler.transformer module.
This module is responsible for transforming raw candle data into training
samples usable to the Euler algorithm.
"""
import datetime
import decimal
from algos.euler.models import training_samples as ts
from core.models import instruments
from datasource.models import... | en | 0.834446 | This is algos.euler.transformer module. This module is responsible for transforming raw candle data into training samples usable to the Euler algorithm. Extract the features for the learning algorithm from a daily candle. The Features are: high_bid, low_bid, close_bid, open_ask, high_ask, lo... | 3.163546 | 3 |
diagrams/outscale/__init__.py | analyticsftw/diagrams | 17,037 | 6959 | <reponame>analyticsftw/diagrams<filename>diagrams/outscale/__init__.py
from diagrams import Node
class _Outscale(Node):
_provider = "outscale"
_icon_dir = "resources/outscale"
fontcolor = "#ffffff"
| from diagrams import Node
class _Outscale(Node):
_provider = "outscale"
_icon_dir = "resources/outscale"
fontcolor = "#ffffff" | none | 1 | 1.624862 | 2 | |
misc/python/mango/application/main_driver/logstream.py | pymango/pymango | 3 | 6960 | __doc__ = \
"""
=======================================================================================
Main-driver :obj:`LogStream` variables (:mod:`mango.application.main_driver.logstream`)
=======================================================================================
.. currentmodule:: mango.application.ma... | __doc__ = \
"""
=======================================================================================
Main-driver :obj:`LogStream` variables (:mod:`mango.application.main_driver.logstream`)
=======================================================================================
.. currentmodule:: mango.application.ma... | en | 0.500882 | ======================================================================================= Main-driver :obj:`LogStream` variables (:mod:`mango.application.main_driver.logstream`) ======================================================================================= .. currentmodule:: mango.application.main_driver.logstr... | 1.865111 | 2 |
ucdev/cy7c65211/header.py | luftek/python-ucdev | 11 | 6961 | # -*- coding: utf-8-unix -*-
import platform
######################################################################
# Platform specific headers
######################################################################
if platform.system() == 'Linux':
src = """
typedef bool BOOL;
"""
#############################... | # -*- coding: utf-8-unix -*-
import platform
######################################################################
# Platform specific headers
######################################################################
if platform.system() == 'Linux':
src = """
typedef bool BOOL;
"""
#############################... | en | 0.34902 | # -*- coding: utf-8-unix -*- ###################################################################### # Platform specific headers ###################################################################### typedef bool BOOL; ###################################################################### # Common headers ##############... | 1.486734 | 1 |
deep_qa/layers/wrappers/output_mask.py | richarajpal/deep_qa | 459 | 6962 | <reponame>richarajpal/deep_qa
from overrides import overrides
from ..masked_layer import MaskedLayer
class OutputMask(MaskedLayer):
"""
This Layer is purely for debugging. You can wrap this on a layer's output to get the mask
output by that layer as a model output, for easier visualization of what the m... | from overrides import overrides
from ..masked_layer import MaskedLayer
class OutputMask(MaskedLayer):
"""
This Layer is purely for debugging. You can wrap this on a layer's output to get the mask
output by that layer as a model output, for easier visualization of what the model is actually
doing.
... | en | 0.879635 | This Layer is purely for debugging. You can wrap this on a layer's output to get the mask output by that layer as a model output, for easier visualization of what the model is actually doing. Don't try to use this in an actual model. # pylint: disable=unused-argument | 3.30379 | 3 |
ljmc/energy.py | karnesh/Monte-Carlo-LJ | 0 | 6963 | """
energy.py
function that computes the inter particle energy
It uses truncated 12-6 Lennard Jones potential
All the variables are in reduced units.
"""
def distance(atom1, atom2):
"""
Computes the square of inter particle distance
Minimum image convention is applied for distance calculatio... | """
energy.py
function that computes the inter particle energy
It uses truncated 12-6 Lennard Jones potential
All the variables are in reduced units.
"""
def distance(atom1, atom2):
"""
Computes the square of inter particle distance
Minimum image convention is applied for distance calculatio... | en | 0.853473 | energy.py function that computes the inter particle energy It uses truncated 12-6 Lennard Jones potential All the variables are in reduced units. Computes the square of inter particle distance Minimum image convention is applied for distance calculation for periodic boundary conditions calculates the energy of... | 3.43966 | 3 |
CEST/Evaluation/lorenzian.py | ludgerradke/bMRI | 0 | 6964 | import numpy as np
import math
from scipy.optimize import curve_fit
def calc_lorentzian(CestCurveS, x_calcentires, mask, config):
(rows, colums, z_slices, entires) = CestCurveS.shape
lorenzian = {key: np.zeros((rows, colums, z_slices), dtype=float) for key in config.lorenzian_keys}
for k in range(z_slice... | import numpy as np
import math
from scipy.optimize import curve_fit
def calc_lorentzian(CestCurveS, x_calcentires, mask, config):
(rows, colums, z_slices, entires) = CestCurveS.shape
lorenzian = {key: np.zeros((rows, colums, z_slices), dtype=float) for key in config.lorenzian_keys}
for k in range(z_slice... | de | 0.366202 | # wassr_offset, da die Z-Spektren vorher korrigiert wurden # X_f = frequenz of X #ret = (a + ak) - (a * ((b ** 2) / 4) / (((b ** 2) / 4) + (x - wassr_offset) ** 2)) | 2.144338 | 2 |
components/network_models_LSTU.py | neuralchen/CooGAN | 12 | 6965 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#############################################################
# File: network_models_LSTU.py
# Created Date: Tuesday February 25th 2020
# Author: <NAME>
# Email: <EMAIL>
# Last Modified: Tuesday, 25th February 2020 9:57:06 pm
# Modified By: <NAME>
# Copyright (c) 2020 Shan... | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#############################################################
# File: network_models_LSTU.py
# Created Date: Tuesday February 25th 2020
# Author: <NAME>
# Email: <EMAIL>
# Last Modified: Tuesday, 25th February 2020 9:57:06 pm
# Modified By: <NAME>
# Copyright (c) 2020 Shan... | en | 0.422412 | #!/usr/bin/env python3 # -*- coding:utf-8 -*- ############################################################# # File: network_models_LSTU.py # Created Date: Tuesday February 25th 2020 # Author: <NAME> # Email: <EMAIL> # Last Modified: Tuesday, 25th February 2020 9:57:06 pm # Modified By: <NAME> # Copyright (c) 2020 Shan... | 2.116126 | 2 |
slender/tests/list/test_keep_if.py | torokmark/slender | 1 | 6966 | <reponame>torokmark/slender
from unittest import TestCase
from expects import expect, equal, raise_error
from slender import List
class TestKeepIf(TestCase):
def test_keep_if_if_func_is_none(self):
e = List([1, 2, 3, 4, 5])
expect(e.keep_if(None).to_list()).to(equal([1, 2, 3, 4, 5]))
def t... | from unittest import TestCase
from expects import expect, equal, raise_error
from slender import List
class TestKeepIf(TestCase):
def test_keep_if_if_func_is_none(self):
e = List([1, 2, 3, 4, 5])
expect(e.keep_if(None).to_list()).to(equal([1, 2, 3, 4, 5]))
def test_keep_if_if_func_is_valid(... | none | 1 | 2.765321 | 3 | |
test/functional/bchn-txbroadcastinterval.py | 1Crazymoney/bitcoin-cash-node | 1 | 6967 | <filename>test/functional/bchn-txbroadcastinterval.py
#!/usr/bin/env python3
# Copyright (c) 2020 The Bitcoin Cash Node developers
# Author matricz
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Test that inv messages are sent... | <filename>test/functional/bchn-txbroadcastinterval.py
#!/usr/bin/env python3
# Copyright (c) 2020 The Bitcoin Cash Node developers
# Author matricz
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Test that inv messages are sent... | en | 0.869392 | #!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Cash Node developers # Author matricz # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. Test that inv messages are sent according to an exponential distribution with scale -txbr... | 2.30454 | 2 |
tests/compute/test_sampler.py | buaaqt/dgl | 1 | 6968 | import backend as F
import numpy as np
import scipy as sp
import dgl
from dgl import utils
import unittest
from numpy.testing import assert_array_equal
np.random.seed(42)
def generate_rand_graph(n):
arr = (sp.sparse.random(n, n, density=0.1, format='coo') != 0).astype(np.int64)
return dgl.DGLGraph(arr, readon... | import backend as F
import numpy as np
import scipy as sp
import dgl
from dgl import utils
import unittest
from numpy.testing import assert_array_equal
np.random.seed(42)
def generate_rand_graph(n):
arr = (sp.sparse.random(n, n, density=0.1, format='coo') != 0).astype(np.int64)
return dgl.DGLGraph(arr, readon... | en | 0.876136 | # In this case, NeighborSampling simply gets the neighborhood of a single vertex. # We don't allow duplicate elements in the neighbor list. # The neighbor list also needs to be sorted. # a neighbor in the subgraph must also exist in parent graph. # In this case, NeighborSampling simply gets the neighborhood of a single... | 2.365546 | 2 |
plugins/voila/voila/__init__.py | srinivasreddych/aws-orbit-workbench | 94 | 6969 | # Copyright Amazon.com, Inc. or its affiliates. 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
#
# Unl... | # Copyright Amazon.com, Inc. or its affiliates. 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
#
# Unl... | en | 0.85975 | # Copyright Amazon.com, Inc. or its affiliates. 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 # # Unl... | 1.659516 | 2 |
tools/generate_driver_list.py | aarunsai81/netapp | 11 | 6970 | #! /usr/bin/env python
#
# 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... | #! /usr/bin/env python
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | en | 0.88356 | #! /usr/bin/env python # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in... | 2.291795 | 2 |
Disp_pythonScript.py | maniegley/python | 1 | 6971 | <gh_stars>1-10
import sys
f = open("/home/vader/Desktop/test.py", "r")
#read all file
python_script = f.read()
print(python_script)
| import sys
f = open("/home/vader/Desktop/test.py", "r")
#read all file
python_script = f.read()
print(python_script) | en | 0.922075 | #read all file | 2.131076 | 2 |
email_file.py | grussr/email-file-attachment | 0 | 6972 | import smtplib
import argparse
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
import configparser
import json
def send_mail(send_from, send_to, subject, te... | import smtplib
import argparse
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
import configparser
import json
def send_mail(send_from, send_to, subject, te... | en | 0.99894 | # After the file is closed | 2.887788 | 3 |
logs/constants.py | gonzatorte/sw-utils | 0 | 6973 | <gh_stars>0
import logging
TRACE_LVL = int( (logging.DEBUG + logging.INFO) / 2 )
| import logging
TRACE_LVL = int( (logging.DEBUG + logging.INFO) / 2 ) | none | 1 | 1.385667 | 1 | |
examples/simple_lakehouse/simple_lakehouse/repo.py | dbatten5/dagster | 2 | 6974 | <gh_stars>1-10
from dagster import repository
from simple_lakehouse.pipelines import simple_lakehouse_pipeline
@repository
def simple_lakehouse():
return [simple_lakehouse_pipeline]
| from dagster import repository
from simple_lakehouse.pipelines import simple_lakehouse_pipeline
@repository
def simple_lakehouse():
return [simple_lakehouse_pipeline] | none | 1 | 1.413011 | 1 | |
demos/odyssey/dodyssey.py | steingabelgaard/reportlab | 55 | 6975 | <filename>demos/odyssey/dodyssey.py<gh_stars>10-100
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.3.0'
__doc__=''
#REPORTLAB_TEST_SCRIPT
import sys, copy, os
from reportlab.platypus import *
_NEW_PARA=os.environ.get('NEW_PARA','0')[0] in ('y','Y','1')
_REDCAP=int(os.env... | <filename>demos/odyssey/dodyssey.py<gh_stars>10-100
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.3.0'
__doc__=''
#REPORTLAB_TEST_SCRIPT
import sys, copy, os
from reportlab.platypus import *
_NEW_PARA=os.environ.get('NEW_PARA','0')[0] in ('y','Y','1')
_REDCAP=int(os.env... | en | 0.558585 | #Copyright ReportLab Europe Ltd. 2000-2017 #see license.txt for license details #REPORTLAB_TEST_SCRIPT # attach our callback to the canvas #normal frame as for SimpleFlowDocument #Two Columns | 2.202297 | 2 |
tests/test_fred_fred_view.py | Traceabl3/GamestonkTerminal | 0 | 6976 | """ econ/fred_view.py tests """
import unittest
from unittest import mock
from io import StringIO
import pandas as pd
# pylint: disable=unused-import
from gamestonk_terminal.econ.fred_view import get_fred_data # noqa: F401
fred_data_mock = """
,GDP
2019-01-01,21115.309
2019-04-01,21329.877
2019-07-01,21540.325
2019-... | """ econ/fred_view.py tests """
import unittest
from unittest import mock
from io import StringIO
import pandas as pd
# pylint: disable=unused-import
from gamestonk_terminal.econ.fred_view import get_fred_data # noqa: F401
fred_data_mock = """
,GDP
2019-01-01,21115.309
2019-04-01,21329.877
2019-07-01,21540.325
2019-... | en | 0.41956 | econ/fred_view.py tests # pylint: disable=unused-import # noqa: F401 ,GDP 2019-01-01,21115.309 2019-04-01,21329.877 2019-07-01,21540.325 2019-10-01,21747.394 2020-01-01,21561.139 2020-04-01,19520.114 2020-07-01,21170.252 2020-10-01,21494.731 | 2.706955 | 3 |
python27/1.0/lib/linux/gevent/pool.py | jt6562/XX-Net | 2 | 6977 | # Copyright (c) 2009-2010 <NAME>. See LICENSE for details.
"""Managing greenlets in a group.
The :class:`Group` class in this module abstracts a group of running greenlets.
When a greenlet dies, it's automatically removed from the group.
The :class:`Pool` which a subclass of :class:`Group` provides a way to limit
con... | # Copyright (c) 2009-2010 <NAME>. See LICENSE for details.
"""Managing greenlets in a group.
The :class:`Group` class in this module abstracts a group of running greenlets.
When a greenlet dies, it's automatically removed from the group.
The :class:`Pool` which a subclass of :class:`Group` provides a way to limit
con... | en | 0.858957 | # Copyright (c) 2009-2010 <NAME>. See LICENSE for details. Managing greenlets in a group. The :class:`Group` class in this module abstracts a group of running greenlets. When a greenlet dies, it's automatically removed from the group. The :class:`Pool` which a subclass of :class:`Group` provides a way to limit concur... | 2.948487 | 3 |
lecarb/estimator/lw/lw_tree.py | anshumandutt/AreCELearnedYet | 34 | 6978 | <gh_stars>10-100
import time
import logging
from typing import Dict, Any, Tuple
import pickle
import numpy as np
import xgboost as xgb
from .common import load_lw_dataset, encode_query, decode_label
from ..postgres import Postgres
from ..estimator import Estimator
from ..utils import evaluate, run_test
from ...datase... | import time
import logging
from typing import Dict, Any, Tuple
import pickle
import numpy as np
import xgboost as xgb
from .common import load_lw_dataset, encode_query, decode_label
from ..postgres import Postgres
from ..estimator import Estimator
from ..utils import evaluate, run_test
from ...dataset.dataset import ... | en | 0.598873 | # overwrite parameters from user # convert parameter dict of lw(nn) # Train model # 'model_size': model_size, # load model params: model: model file name use_cache: load processed vectors directly instead of build from queries # uniform thread number # load corresonding version of table # load model # ... | 2.19303 | 2 |
fsim/utils.py | yamasampo/fsim | 0 | 6979 |
import os
import configparser
from warnings import warn
def read_control_file(control_file):
# Initialize ConfigParser object
config = configparser.ConfigParser(
strict=True,
comment_prefixes=('/*', ';', '#'),
inline_comment_prefixes=('/*', ';', '#')
)
# Parse control file
... |
import os
import configparser
from warnings import warn
def read_control_file(control_file):
# Initialize ConfigParser object
config = configparser.ConfigParser(
strict=True,
comment_prefixes=('/*', ';', '#'),
inline_comment_prefixes=('/*', ';', '#')
)
# Parse control file
... | en | 0.515139 | # Initialize ConfigParser object # Parse control file # Check number of read control files. # Check sections. Only 'REQUIRED' and 'OPTIONAL' sections will be used. Write arguments or keyword arguments to a file. Values will be separated by a given separator. | 2.687299 | 3 |
src/pymortests/function.py | mahgadalla/pymor | 1 | 6980 | # This file is part of the pyMOR project (http://www.pymor.org).
# Copyright 2013-2017 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
import numpy as np
import pytest
from pymor.core.pickle import dumps, loads
from pymor.functions.... | # This file is part of the pyMOR project (http://www.pymor.org).
# Copyright 2013-2017 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
import numpy as np
import pytest
from pymor.core.pickle import dumps, loads
from pymor.functions.... | en | 0.722459 | # This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2017 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) # monkey np.testing.assert_allclose to behave the same as np.allclose # for some reason, the defaul... | 2.247319 | 2 |
Code/userIDCrawler.py | CarberZ/social-media-mining | 2 | 6981 | <reponame>CarberZ/social-media-mining
'''
step 1
get the userID and their locations
put them all into a database
'''
from bs4 import BeautifulSoup
import urllib
import sqlite3
from selenium import webdriver
import time
import re
from urllib import request
import random
import pickle
import os
import ... | '''
step 1
get the userID and their locations
put them all into a database
'''
from bs4 import BeautifulSoup
import urllib
import sqlite3
from selenium import webdriver
import time
import re
from urllib import request
import random
import pickle
import os
import pytesseract
url_dog = "https:... | en | 0.557361 | step 1
get the userID and their locations
put them all into a database cat = 1 ~ 336770
dog = 1 ~ 156240 #iniate the start point # if getInfo.type == 'dog': # getInfo.cursor.execute("drop table if exists DogPeople") # getInfo.cursor.execute("create table DogPeople(id varchar(48), location varchar(48))") # el... | 2.974574 | 3 |
src/stoat/core/structure/__init__.py | saarkatz/guppy-struct | 1 | 6982 | <gh_stars>1-10
from .structure import Structure
| from .structure import Structure | none | 1 | 1.054344 | 1 | |
tbase/network/polices_test.py | iminders/TradeBaselines | 16 | 6983 | <reponame>iminders/TradeBaselines<filename>tbase/network/polices_test.py
import unittest
import numpy as np
from tbase.common.cmd_util import set_global_seeds
from tbase.network.polices import RandomPolicy
class TestPolices(unittest.TestCase):
@classmethod
def setUpClass(self):
set_global_seeds(0)
... | import unittest
import numpy as np
from tbase.common.cmd_util import set_global_seeds
from tbase.network.polices import RandomPolicy
class TestPolices(unittest.TestCase):
@classmethod
def setUpClass(self):
set_global_seeds(0)
def test_random_policy(self):
policy = RandomPolicy(2)
... | en | 0.278372 | # action 1 # action 2 | 2.614157 | 3 |
keystone/tests/unit/core.py | knikolla/keystone | 0 | 6984 | # Copyright 2012 OpenStack Foundation
#
# 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... | # Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | en | 0.845024 | # Copyright 2012 OpenStack Foundation # # 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... | 1.385054 | 1 |
PyISY/Nodes/__init__.py | sneelco/PyISY | 0 | 6985 | <filename>PyISY/Nodes/__init__.py
from .group import Group
from .node import (Node, parse_xml_properties, ATTR_ID)
from time import sleep
from xml.dom import minidom
class Nodes(object):
"""
This class handles the ISY nodes. This class can be used as a dictionary to
navigate through the controller's str... | <filename>PyISY/Nodes/__init__.py
from .group import Group
from .node import (Node, parse_xml_properties, ATTR_ID)
from time import sleep
from xml.dom import minidom
class Nodes(object):
"""
This class handles the ISY nodes. This class can be used as a dictionary to
navigate through the controller's str... | en | 0.770969 | This class handles the ISY nodes. This class can be used as a dictionary to navigate through the controller's structure to objects of type :class:`~PyISY.Nodes.Node` and :class:`~PyISY.Nodes.Group` that represent objects on the controller. | parent: ISY class | root: [optional] String representin... | 2.675945 | 3 |
easyCore/Utils/Logging.py | easyScience/easyCore | 2 | 6986 | <gh_stars>1-10
# SPDX-FileCopyrightText: 2021 easyCore contributors <<EMAIL>>
# SPDX-License-Identifier: BSD-3-Clause
# © 2021 Contributors to the easyCore project <https://github.com/easyScience/easyCore>
__author__ = 'github.com/wardsimon'
__version__ = '0.1.0'
import logging
class Logger:
def __init__(se... | # SPDX-FileCopyrightText: 2021 easyCore contributors <<EMAIL>>
# SPDX-License-Identifier: BSD-3-Clause
# © 2021 Contributors to the easyCore project <https://github.com/easyScience/easyCore>
__author__ = 'github.com/wardsimon'
__version__ = '0.1.0'
import logging
class Logger:
def __init__(self, log_level: ... | en | 0.469081 | # SPDX-FileCopyrightText: 2021 easyCore contributors <<EMAIL>> # SPDX-License-Identifier: BSD-3-Clause # © 2021 Contributors to the easyCore project <https://github.com/easyScience/easyCore> Create a logger :param color: :param logger_name: logger name. Usually __name__ on creation :param de... | 2.306467 | 2 |
iqoptionapi/http/billing.py | mustx1/MYIQ | 3 | 6987 | """Module for IQ option billing resource."""
from iqoptionapi.http.resource import Resource
class Billing(Resource):
"""Class for IQ option billing resource."""
# pylint: disable=too-few-public-methods
url = "billing"
| """Module for IQ option billing resource."""
from iqoptionapi.http.resource import Resource
class Billing(Resource):
"""Class for IQ option billing resource."""
# pylint: disable=too-few-public-methods
url = "billing"
| en | 0.648508 | Module for IQ option billing resource. Class for IQ option billing resource. # pylint: disable=too-few-public-methods | 1.631367 | 2 |
defaultsob/core.py | honewatson/defaults | 0 | 6988 | # -*- coding: utf-8 -*-
def ordered_set(iter):
"""Creates an ordered set
@param iter: list or tuple
@return: list with unique values
"""
final = []
for i in iter:
if i not in final:
final.append(i)
return final
def class_slots(ob):
"""Get object attributes from... | # -*- coding: utf-8 -*-
def ordered_set(iter):
"""Creates an ordered set
@param iter: list or tuple
@return: list with unique values
"""
final = []
for i in iter:
if i not in final:
final.append(i)
return final
def class_slots(ob):
"""Get object attributes from... | en | 0.505912 | # -*- coding: utf-8 -*- Creates an ordered set @param iter: list or tuple @return: list with unique values Get object attributes from child class attributes @param ob: Defaults object @type ob: Defaults @return: Tuple of slots Try and get a value from kwargs for original_attr. If there is... | 3.473845 | 3 |
tests/bot_test.py | item4/yui | 36 | 6989 | import asyncio
from collections import defaultdict
from datetime import timedelta
import pytest
from yui.api import SlackAPI
from yui.bot import Bot
from yui.box import Box
from yui.types.slack.response import APIResponse
from yui.utils import json
from .util import FakeImportLib
def test_bot_init(event_loop, monk... | import asyncio
from collections import defaultdict
from datetime import timedelta
import pytest
from yui.api import SlackAPI
from yui.bot import Bot
from yui.box import Box
from yui.types.slack.response import APIResponse
from yui.utils import json
from .util import FakeImportLib
def test_bot_init(event_loop, monk... | none | 1 | 1.945003 | 2 | |
scripts/marker_filter.py | CesMak/aruco_detector_ocv | 12 | 6990 | <reponame>CesMak/aruco_detector_ocv
#!/usr/bin/env python
import numpy as np
import rospy
import geometry_msgs.msg
import tf2_ros
from tf.transformations import quaternion_slerp
def translation_to_numpy(t):
return np.array([t.x, t.y, t.z])
def quaternion_to_numpy(q):
return np.array([q.x, q.y, q.z, q.w])
... | #!/usr/bin/env python
import numpy as np
import rospy
import geometry_msgs.msg
import tf2_ros
from tf.transformations import quaternion_slerp
def translation_to_numpy(t):
return np.array([t.x, t.y, t.z])
def quaternion_to_numpy(q):
return np.array([q.x, q.y, q.z, q.w])
if __name__ == '__main__':
rosp... | en | 0.777941 | #!/usr/bin/env python # Lookup the transform # Apply running average filter to translation and rotation # Update pose of the marker # Create new transform and broadcast it | 2.231758 | 2 |
src/backbone/utils.py | hankyul2/FaceDA | 20 | 6991 | <filename>src/backbone/utils.py
import os
import subprocess
from pathlib import Path
from torch.hub import load_state_dict_from_url
import numpy as np
model_urls = {
# ResNet
'resnet18': 'https://download.pytorch.org/models/resnet18-f37072fd.pth',
'resnet34': 'https://download.pytorch.org/models/resnet3... | <filename>src/backbone/utils.py
import os
import subprocess
from pathlib import Path
from torch.hub import load_state_dict_from_url
import numpy as np
model_urls = {
# ResNet
'resnet18': 'https://download.pytorch.org/models/resnet18-f37072fd.pth',
'resnet34': 'https://download.pytorch.org/models/resnet3... | en | 0.536263 | # ResNet # MobileNetV2 # Se ResNet # ViT # Hybrid (resnet50 + ViT) | 2.224355 | 2 |
crawler1.py | pjha1994/Scrape_reddit | 0 | 6992 | import requests
from bs4 import BeautifulSoup
def recursiveUrl(url, link, depth):
if depth == 5:
return url
else:
print(link['href'])
page = requests.get(url + link['href'])
soup = BeautifulSoup(page.text, 'html.parser')
newlink = soup.find('a')
if len(newlink) =... | import requests
from bs4 import BeautifulSoup
def recursiveUrl(url, link, depth):
if depth == 5:
return url
else:
print(link['href'])
page = requests.get(url + link['href'])
soup = BeautifulSoup(page.text, 'html.parser')
newlink = soup.find('a')
if len(newlink) =... | none | 1 | 3.185773 | 3 | |
chime2/tests/normal/models/seir_test.py | BrianThomasRoss/CHIME-2 | 0 | 6993 | """Tests for SEIR model in this repo
* Compares conserved quantities
* Compares model against SEIR wo social policies in limit to SIR
"""
from pandas import Series
from pandas.testing import assert_frame_equal, assert_series_equal
from bayes_chime.normal.models import SEIRModel, SIRModel
from pytest import fixture
fro... | """Tests for SEIR model in this repo
* Compares conserved quantities
* Compares model against SEIR wo social policies in limit to SIR
"""
from pandas import Series
from pandas.testing import assert_frame_equal, assert_series_equal
from bayes_chime.normal.models import SEIRModel, SIRModel
from pytest import fixture
fro... | en | 0.825346 | Tests for SEIR model in this repo * Compares conserved quantities * Compares model against SEIR wo social policies in limit to SIR # pylint: disable=W0611 # Does not compare census as this repo uses the exponential distribution Returns data for the SIHR model Checks if S + E + I + R is conserved for SEIR Checks if SEIR... | 2.188934 | 2 |
Libraries/mattsLibraries/mathOperations.py | mrware91/PhilTransA-TRXS-Limits | 0 | 6994 | import numpy as np
from scipy.interpolate import interp1d
from pyTools import *
################################################################################
#~~~~~~~~~Log ops
################################################################################
def logPolyVal(p,x):
ord = p.order()
logs = []
... | import numpy as np
from scipy.interpolate import interp1d
from pyTools import *
################################################################################
#~~~~~~~~~Log ops
################################################################################
def logPolyVal(p,x):
ord = p.order()
logs = []
... | de | 0.798224 | ################################################################################ #~~~~~~~~~Log ops ################################################################################ ################################################################################ #~~~~~~~~~Symmeterize data ################################... | 2.50513 | 3 |
setup.py | avryhof/ambient_api | 20 | 6995 | from setuptools import setup
setup(
name="ambient_api",
version="1.5.6",
packages=["ambient_api"],
url="https://github.com/avryhof/ambient_api",
license="MIT",
author="<NAME>",
author_email="<EMAIL>",
description="A Python class for accessing the Ambient Weather API.",
classifiers=[... | from setuptools import setup
setup(
name="ambient_api",
version="1.5.6",
packages=["ambient_api"],
url="https://github.com/avryhof/ambient_api",
license="MIT",
author="<NAME>",
author_email="<EMAIL>",
description="A Python class for accessing the Ambient Weather API.",
classifiers=[... | none | 1 | 1.395278 | 1 | |
tests/llvm/static/test_main_is_found/test_main_is_found.py | ganeshutah/FPChecker | 19 | 6996 | <reponame>ganeshutah/FPChecker
#!/usr/bin/env python
import subprocess
import os
def setup_module(module):
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(THIS_DIR)
def teardown_module(module):
cmd = ["make clean"]
cmdOutput = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shel... | #!/usr/bin/env python
import subprocess
import os
def setup_module(module):
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(THIS_DIR)
def teardown_module(module):
cmd = ["make clean"]
cmdOutput = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
def test_1():
cmd... | ru | 0.26433 | #!/usr/bin/env python | 2.592497 | 3 |
regipy/exceptions.py | kamnon/regipy | 190 | 6997 | class RegipyException(Exception):
"""
This is the parent exception for all regipy exceptions
"""
pass
class RegipyGeneralException(RegipyException):
"""
General exception
"""
pass
class RegistryValueNotFoundException(RegipyException):
pass
class NoRegistrySubkeysException(Regipy... | class RegipyException(Exception):
"""
This is the parent exception for all regipy exceptions
"""
pass
class RegipyGeneralException(RegipyException):
"""
General exception
"""
pass
class RegistryValueNotFoundException(RegipyException):
pass
class NoRegistrySubkeysException(Regipy... | en | 0.800845 | This is the parent exception for all regipy exceptions General exception Raised when there is a parsing error, most probably a corrupted hive Raised when the binary Windows NT SID representation can not be decoded | 2.135129 | 2 |
Dynamic_Programming/1259.Integer Replacement/Solution_BFS.py | Zhenye-Na/LxxxCode | 12 | 6998 | from collections import deque
class Solution:
"""
@param n: a positive integer
@return: the minimum number of replacements
"""
def integerReplacement(self, n):
# Write your code here
steps = 0
if n == 1:
return steps
queue = deque([n])
while q... | from collections import deque
class Solution:
"""
@param n: a positive integer
@return: the minimum number of replacements
"""
def integerReplacement(self, n):
# Write your code here
steps = 0
if n == 1:
return steps
queue = deque([n])
while q... | en | 0.558833 | @param n: a positive integer @return: the minimum number of replacements # Write your code here | 3.806978 | 4 |
src/routes/web.py | enflo/weather-flask | 0 | 6999 | <gh_stars>0
from flask import Blueprint, render_template
from gateways.models import getWeatherData
web = Blueprint("web", __name__, template_folder='templates')
@web.route("/", methods=['GET'])
def home():
items = getWeatherData.get_last_item()
cityName = items["city"]
return render_template("index.html... | from flask import Blueprint, render_template
from gateways.models import getWeatherData
web = Blueprint("web", __name__, template_folder='templates')
@web.route("/", methods=['GET'])
def home():
items = getWeatherData.get_last_item()
cityName = items["city"]
return render_template("index.html",
... | en | 0.245175 | #@web.route("/profile", methods=['GET']) #def profile(): # items = getWeatherData.get_last_item() # return render_template("profile.html", # celcius=items["temperature"], # humidity=items["humidity"], # pressure=items["pressure"]) #@... | 2.675837 | 3 |