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 |
|---|---|---|---|---|---|---|---|---|---|---|
test/test_cursor_binding.py | rhlahuja/snowflake-connector-python | 0 | 4200 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2018 Snowflake Computing Inc. All right reserved.
#
import pytest
from snowflake.connector.errors import (ProgrammingError)
def test_binding_security(conn_cnx, db_parameters):
"""
SQL Injection Tests
"""
try:
wit... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2018 Snowflake Computing Inc. All right reserved.
#
import pytest
from snowflake.connector.errors import (ProgrammingError)
def test_binding_security(conn_cnx, db_parameters):
"""
SQL Injection Tests
"""
try:
with conn_cnx()... | en | 0.519738 | #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2012-2018 Snowflake Computing Inc. All right reserved. # SQL Injection Tests # SQL injection safe test # Good Example # Bad Example in application. DON'T DO THIS SQL binding list type for IN SELECT * FROM {name} WHERE aa IN (%s) ORDER BY 1 DESC SELECT * FR... | 2.852462 | 3 |
taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/model/__init__.py | hectormartinez/rougexstem | 0 | 4201 | # Natural Language Toolkit: Language Models
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: <NAME> <<EMAIL>>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
class ModelI(object):
"""
A processing interface for assigning a probability to the next word.
"""
def __... | # Natural Language Toolkit: Language Models
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: <NAME> <<EMAIL>>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
class ModelI(object):
"""
A processing interface for assigning a probability to the next word.
"""
def __... | en | 0.767931 | # Natural Language Toolkit: Language Models # # Copyright (C) 2001-2008 University of Pennsylvania # Author: <NAME> <<EMAIL>> # URL: <http://nltk.sf.net> # For license information, see LICENSE.TXT A processing interface for assigning a probability to the next word. Create a new language model. Train the model on the te... | 3.147325 | 3 |
flask-graphene-sqlalchemy/models.py | JovaniPink/flask-apps | 0 | 4202 | import os
from graphene_sqlalchemy import SQLAlchemyObjectType
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
POSTGRES_CONNECTION_STRING = (
os.environ.get("POSTGRES_CONNECTION_STRING")
... | import os
from graphene_sqlalchemy import SQLAlchemyObjectType
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
POSTGRES_CONNECTION_STRING = (
os.environ.get("POSTGRES_CONNECTION_STRING")
... | none | 1 | 2.532111 | 3 | |
curlypiv/synthetics/microsig.py | sean-mackenzie/curlypiv | 0 | 4203 | # microsig
"""
Author: <NAME>
More detail about the MicroSIG can be found at:
Website:
https://gitlab.com/defocustracking/microsig-python
Publication:
Rossi M, Synthetic image generator for defocusing and astigmatic PIV/PTV, Meas. Sci. Technol., 31, 017003 (2020)
DOI:10.1088/1361-6501/ab42bb.
"""
import n... | # microsig
"""
Author: <NAME>
More detail about the MicroSIG can be found at:
Website:
https://gitlab.com/defocustracking/microsig-python
Publication:
Rossi M, Synthetic image generator for defocusing and astigmatic PIV/PTV, Meas. Sci. Technol., 31, 017003 (2020)
DOI:10.1088/1361-6501/ab42bb.
"""
import n... | en | 0.777823 | # microsig Author: <NAME> More detail about the MicroSIG can be found at: Website: https://gitlab.com/defocustracking/microsig-python Publication: Rossi M, Synthetic image generator for defocusing and astigmatic PIV/PTV, Meas. Sci. Technol., 31, 017003 (2020) DOI:10.1088/1361-6501/ab42bb. # import time as t... | 2.324845 | 2 |
planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/scripts/trajectory_visualizer.py | kmiya/AutowareArchitectureProposal.iv | 0 | 4204 | <gh_stars>0
# Copyright 2020 Tier IV, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | # Copyright 2020 Tier IV, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | en | 0.41814 | # Copyright 2020 Tier IV, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing... | 2.39117 | 2 |
main/forms.py | agokhale11/test2 | 0 | 4205 | from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
# If you don't do this you cannot use Bootstrap CSS
class LoginFor... | from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
# If you don't do this you cannot use Bootstrap CSS
class LoginFor... | en | 0.866377 | # If you don't do this you cannot use Bootstrap CSS | 2.537129 | 3 |
pandas 9 - Statistics Information on data sets.py | PythonProgramming/Pandas-Basics-with-2.7 | 10 | 4206 | import pandas as pd
from pandas import DataFrame
df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True)
df['H-L'] = df.High - df.Low
# Giving us count (rows), mean (avg), std (standard deviation for the entire
# set), minimum for the set, maximum for the set, and some %s in that range.
print( df.des... | import pandas as pd
from pandas import DataFrame
df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True)
df['H-L'] = df.High - df.Low
# Giving us count (rows), mean (avg), std (standard deviation for the entire
# set), minimum for the set, maximum for the set, and some %s in that range.
print( df.des... | en | 0.935464 | # Giving us count (rows), mean (avg), std (standard deviation for the entire # set), minimum for the set, maximum for the set, and some %s in that range. # gives us correlation data. Remember the 3d chart we plotted? # now you can see if correlation of H-L and Volume also is correlated # with price swings. Correlations... | 4.113152 | 4 |
working/tkinter_widget/test.py | songdaegeun/school-zone-enforcement-system | 0 | 4207 | import cv2
import numpy as np
import threading
def test():
while 1:
img1=cv2.imread('captured car1.jpg')
print("{}".format(img1.shape))
print("{}".format(img1))
cv2.imshow('asd',img1)
cv2.waitKey(1)
t1 = threading.Thread(target=test)
t1.start()
| import cv2
import numpy as np
import threading
def test():
while 1:
img1=cv2.imread('captured car1.jpg')
print("{}".format(img1.shape))
print("{}".format(img1))
cv2.imshow('asd',img1)
cv2.waitKey(1)
t1 = threading.Thread(target=test)
t1.start()
| none | 1 | 3.014746 | 3 | |
ceilometer/compute/virt/hyperv/utilsv2.py | aristanetworks/ceilometer | 2 | 4208 | # Copyright 2013 Cloudbase Solutions Srl
#
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# 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/LICENS... | # Copyright 2013 Cloudbase Solutions Srl
#
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# 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/LICENS... | en | 0.799425 | # Copyright 2013 Cloudbase Solutions Srl # # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # 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/LICENS... | 1.656817 | 2 |
src/cli.py | cajones314/avocd2019 | 0 | 4209 | # system
from io import IOBase, StringIO
import os
# 3rd party
import click
# internal
from days import DayFactory
# import logging
# logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)
# ch = logging.StreamHandler()
# logger.addHandler(ch)
@click.group(invoke_without_command=True)
@click.option... | # system
from io import IOBase, StringIO
import os
# 3rd party
import click
# internal
from days import DayFactory
# import logging
# logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)
# ch = logging.StreamHandler()
# logger.addHandler(ch)
@click.group(invoke_without_command=True)
@click.option... | en | 0.497491 | # system # 3rd party # internal # import logging # logger = logging.getLogger(__name__) # logger.setLevel(logging.DEBUG) # ch = logging.StreamHandler() # logger.addHandler(ch) # pylint: disable=no-value-for-parameter | 2.614673 | 3 |
option_c.py | wrosecrans/colormap | 231 | 4210 |
from matplotlib.colors import LinearSegmentedColormap
from numpy import nan, inf
# Used to reconstruct the colormap in viscm
parameters = {'xp': [-5.4895292543686764, 14.790571669586654, 82.5546687431056, 29.15531114139253, -4.1316769886951761, -13.002076438907238],
'yp': [-35.948168839230306, -42.27337... |
from matplotlib.colors import LinearSegmentedColormap
from numpy import nan, inf
# Used to reconstruct the colormap in viscm
parameters = {'xp': [-5.4895292543686764, 14.790571669586654, 82.5546687431056, 29.15531114139253, -4.1316769886951761, -13.002076438907238],
'yp': [-35.948168839230306, -42.27337... | en | 0.818514 | # Used to reconstruct the colormap in viscm | 1.878623 | 2 |
RPI/yolov5/algorithm/planner/algorithms/hybrid_astar/draw/draw.py | Aditya239233/MDP | 4 | 4211 | <reponame>Aditya239233/MDP
import matplotlib.pyplot as plt
import numpy as np
import math
from algorithm.planner.utils.car_utils import Car_C
PI = np.pi
class Arrow:
def __init__(self, x, y, theta, L, c):
angle = np.deg2rad(30)
d = 0.3 * L
w = 2
x_start = x
y_start = y
... | import matplotlib.pyplot as plt
import numpy as np
import math
from algorithm.planner.utils.car_utils import Car_C
PI = np.pi
class Arrow:
def __init__(self, x, y, theta, L, c):
angle = np.deg2rad(30)
d = 0.3 * L
w = 2
x_start = x
y_start = y
x_end = x + L * np.co... | en | 0.271775 | # Bottom-Left vertex # Bottom-Right vertex # Front-Left vertex # Front-Right vertex | 2.641745 | 3 |
models/database_models/comment_model.py | RuiCoreSci/Flask-Restful | 7 | 4212 | from sqlalchemy import Integer, Text, DateTime, func, Boolean, text
from models.database_models import Base, Column
class Comment(Base):
__tablename__ = "comment"
id = Column(Integer, primary_key=True, )
user_id = Column(Integer, nullable=False, comment="评论用户的 ID")
post_id = Column(Integer, nullable... | from sqlalchemy import Integer, Text, DateTime, func, Boolean, text
from models.database_models import Base, Column
class Comment(Base):
__tablename__ = "comment"
id = Column(Integer, primary_key=True, )
user_id = Column(Integer, nullable=False, comment="评论用户的 ID")
post_id = Column(Integer, nullable... | none | 1 | 2.74601 | 3 | |
aws_deploy/ecs/helper.py | jmsantorum/aws-deploy | 0 | 4213 | <reponame>jmsantorum/aws-deploy
import json
import re
from datetime import datetime
from json.decoder import JSONDecodeError
import click
from boto3.session import Session
from boto3_type_annotations.ecs import Client
from botocore.exceptions import ClientError, NoCredentialsError
from dateutil.tz.tz import tzlocal
fr... | import json
import re
from datetime import datetime
from json.decoder import JSONDecodeError
import click
from boto3.session import Session
from boto3_type_annotations.ecs import Client
from botocore.exceptions import ClientError, NoCredentialsError
from dateutil.tz.tz import tzlocal
from dictdiffer import diff
JSON_... | en | 0.732871 | # the compatibilities parameter is returned from the ECS API, when # describing a task, but may not be included, when registering a new # task definition. Just storing it for now. # check if tag changes | 2.071688 | 2 |
sbm.py | emmaling27/networks-research | 0 | 4214 | <reponame>emmaling27/networks-research
import networkx as nx
from scipy.special import comb
import attr
@attr.s
class Count(object):
"""Count class with monochromatic and bichromatic counts"""
n = attr.ib()
monochromatic = attr.ib(default=0)
bichromatic = attr.ib(default=0)
def count_edge(self, u... | import networkx as nx
from scipy.special import comb
import attr
@attr.s
class Count(object):
"""Count class with monochromatic and bichromatic counts"""
n = attr.ib()
monochromatic = attr.ib(default=0)
bichromatic = attr.ib(default=0)
def count_edge(self, u, v):
if (u < self.n / 2) != (v... | en | 0.803811 | Count class with monochromatic and bichromatic counts SBM class with predicted numbers of wedges and local bridges and actual counts | 2.627794 | 3 |
src/data/graph/ops/anagram_transform_op.py | PhilHarnish/forge | 2 | 4215 | from typing import Callable, Collection, Iterable, List, Union
from data.anagram import anagram_iter
from data.graph import _op_mixin, bloom_mask, bloom_node, bloom_node_reducer
Transformer = Callable[['bloom_node.BloomNode'], 'bloom_node.BloomNode']
_SPACE_MASK = bloom_mask.for_alpha(' ')
def merge_fn(
host: 'b... | from typing import Callable, Collection, Iterable, List, Union
from data.anagram import anagram_iter
from data.graph import _op_mixin, bloom_mask, bloom_node, bloom_node_reducer
Transformer = Callable[['bloom_node.BloomNode'], 'bloom_node.BloomNode']
_SPACE_MASK = bloom_mask.for_alpha(' ')
def merge_fn(
host: 'b... | en | 0.841135 | # TODO: Need a cleaner way to inject and rerun these nodes. # HACK: This duplicates BloomNode._expand, essentially. Singleton object used during anagram traversal. # Compute requirements from exits. # Distance and provide masks should be correct. Reset required values. # Any route to any of the spaces is now okay but 1... | 2.160255 | 2 |
gogapi/api.py | tikki/pygogapi | 23 | 4216 | <gh_stars>10-100
import json
import re
import logging
import html.parser
import zlib
import requests
from gogapi import urls
from gogapi.base import NotAuthorizedError, logger
from gogapi.product import Product, Series
from gogapi.search import SearchResult
DEBUG_JSON = False
GOGDATA_RE = re.compile(r"gogData\.?(.*?... | import json
import re
import logging
import html.parser
import zlib
import requests
from gogapi import urls
from gogapi.base import NotAuthorizedError, logger
from gogapi.product import Product, Series
from gogapi.search import SearchResult
DEBUG_JSON = False
GOGDATA_RE = re.compile(r"gogData\.?(.*?) = (.+);")
CLIEN... | en | 0.610713 | # Just for their statistics # TODO: replace tuple # Helpers Wrapper around requests.request that also handles authorization, retries and logging # Retries Wrapper around requests.get Wrapper around requests.post Wrapper around GogApi.request that automatically parses the JSON response. Also does zlib de... | 2.196639 | 2 |
setup.py | gibsonMatt/stacks-pairwise | 0 | 4217 | import pathlib
import os
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# specify requirements of your package here
REQUIREMENTS = ['biopython', 'numpy', 'pandas']
setup(name='stacksPairwi... | import pathlib
import os
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# specify requirements of your package here
REQUIREMENTS = ['biopython', 'numpy', 'pandas']
setup(name='stacksPairwi... | en | 0.663323 | # The directory containing this file # The text of the README file # specify requirements of your package here | 1.499323 | 1 |
csv_experiment.py | komax/spanningtree-crossingnumber | 2 | 4218 | <gh_stars>1-10
#! /usr/bin/env python
import os
import sys
args = sys.argv[1:]
os.system('python -O -m spanningtree.csv_experiment_statistics ' +
' '.join(args))
| #! /usr/bin/env python
import os
import sys
args = sys.argv[1:]
os.system('python -O -m spanningtree.csv_experiment_statistics ' +
' '.join(args)) | ru | 0.148623 | #! /usr/bin/env python | 1.665696 | 2 |
projects/tutorials/object_nav_ithor_dagger_then_ppo_one_object.py | klemenkotar/dcrl | 18 | 4219 | <reponame>klemenkotar/dcrl<filename>projects/tutorials/object_nav_ithor_dagger_then_ppo_one_object.py<gh_stars>10-100
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from allenact.algorithms.onpolicy_sync.losses import PPO
from allenact.algorithms.onpolicy_sync.losses.imitation i... | import torch
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from allenact.algorithms.onpolicy_sync.losses import PPO
from allenact.algorithms.onpolicy_sync.losses.imitation import Imitation
from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig
from allenact.utils.experiment_util... | en | 0.811218 | A simple object navigation experiment in THOR. Training with DAgger and then PPO. # Log every 10 max length tasks # We add an imitation loss. | 2.034276 | 2 |
BioCAT/src/Calculating_scores.py | DanilKrivonos/BioCAT-nrp-BIOsynthesis-Caluster-Analyzing-Tool | 4 | 4220 | from numpy import array
from pickle import load
from pandas import read_csv
import os
from BioCAT.src.Combinatorics import multi_thread_shuffling, multi_thread_calculating_scores, make_combine, get_score, get_max_aminochain, skipper
# Importing random forest model
modelpath = os.path.dirname(os.path.abspath(__file__)... | from numpy import array
from pickle import load
from pandas import read_csv
import os
from BioCAT.src.Combinatorics import multi_thread_shuffling, multi_thread_calculating_scores, make_combine, get_score, get_max_aminochain, skipper
# Importing random forest model
modelpath = os.path.dirname(os.path.abspath(__file__)... | en | 0.642921 | # Importing random forest model # The function generate list of shuflled matrix The functuion generate massive of shuffled matrix. Parameters ---------- matrix : pandas DataFrame PSSM profile. cpu : int Number of tred used. iterat : int Number of iterations of shuffling. ... | 2.749442 | 3 |
deal/linter/_extractors/returns.py | m4ta1l/deal | 1 | 4221 | <reponame>m4ta1l/deal
# built-in
from typing import Optional
# app
from .common import TOKENS, Extractor, Token, traverse
from .value import UNKNOWN, get_value
get_returns = Extractor()
inner_extractor = Extractor()
def has_returns(body: list) -> bool:
for expr in traverse(body=body):
if isinstance(exp... | # built-in
from typing import Optional
# app
from .common import TOKENS, Extractor, Token, traverse
from .value import UNKNOWN, get_value
get_returns = Extractor()
inner_extractor = Extractor()
def has_returns(body: list) -> bool:
for expr in traverse(body=body):
if isinstance(expr, TOKENS.RETURN + TOK... | en | 0.949221 | # built-in # app | 2.400561 | 2 |
qubiter/device_specific/chip_couplings_ibm.py | yourball/qubiter | 3 | 4222 | <reponame>yourball/qubiter
def aaa():
# trick sphinx to build link in doc
pass
# retired
ibmqx2_c_to_tars =\
{
0: [1, 2],
1: [2],
2: [],
3: [2, 4],
4: [2]
} # 6 edges
# retired
ibmqx4_c_to_tars =\
{
0: [],
1: [0],
2: [0, 1, 4],
3: [2, 4],
4: []
} # 6 edges
# retired
... | def aaa():
# trick sphinx to build link in doc
pass
# retired
ibmqx2_c_to_tars =\
{
0: [1, 2],
1: [2],
2: [],
3: [2, 4],
4: [2]
} # 6 edges
# retired
ibmqx4_c_to_tars =\
{
0: [],
1: [0],
2: [0, 1, 4],
3: [2, 4],
4: []
} # 6 edges
# retired
ibmq16Rus_c_to_tars = \
{
... | en | 0.770195 | # trick sphinx to build link in doc # retired # 6 edges # retired # 6 edges # retired # 22 edges # 86 edges # 12 edges # 36 edges | 1.584742 | 2 |
Template.py | rainshen49/citadel-trading-comp | 2 | 4223 | import signal
import requests
import time
from math import floor
shutdown = False
MAIN_TAKER = 0.0065
MAIN_MAKER = 0.002
ALT_TAKER = 0.005
ALT_MAKER = 0.0035
TAKER = (MAIN_TAKER + ALT_TAKER)*2
MAKER = MAIN_MAKER + ALT_MAKER
TAKEMAIN = MAIN_TAKER - ALT_MAKER
TAKEALT = ALT_TAKER - MAIN_MAKER
BUFFER = 0.0... | import signal
import requests
import time
from math import floor
shutdown = False
MAIN_TAKER = 0.0065
MAIN_MAKER = 0.002
ALT_TAKER = 0.005
ALT_MAKER = 0.0035
TAKER = (MAIN_TAKER + ALT_TAKER)*2
MAKER = MAIN_MAKER + ALT_MAKER
TAKEMAIN = MAIN_TAKER - ALT_MAKER
TAKEALT = ALT_TAKER - MAIN_MAKER
BUFFER = 0.0... | en | 0.798098 | # could be cached # this timer is unnecessary, network latency should be enough # only care about recent news # price does change in every tick # check position # plain arbitradge # index arbitrage # shock handling # wave riding # pairTickers = [('WMT-M', 'WMT-A'), ('CAT-M', 'CAT-A'), ('MMM-M', 'MMM-A')] # trader = ses... | 2.70772 | 3 |
examples/basic/wire_feedthrough.py | souviksaha97/spydrnet-physical | 0 | 4224 | """
==========================================
Genrating feedthrough from single instance
==========================================
This example demostrates how to generate a feedthrough wire connection for
a given scalar or vector wires.
**Initial Design**
.. hdl-diagram:: ../../../examples/basic/_initial_design.v... | """
==========================================
Genrating feedthrough from single instance
==========================================
This example demostrates how to generate a feedthrough wire connection for
a given scalar or vector wires.
**Initial Design**
.. hdl-diagram:: ../../../examples/basic/_initial_design.v... | en | 0.42709 | ========================================== Genrating feedthrough from single instance ========================================== This example demostrates how to generate a feedthrough wire connection for a given scalar or vector wires. **Initial Design** .. hdl-diagram:: ../../../examples/basic/_initial_design.v ... | 2.520812 | 3 |
workflows/workflow.py | sunnyfloyd/panderyx | 0 | 4225 | from __future__ import annotations
from typing import Optional, Union
from tools import tools
from exceptions import workflow_exceptions
class Workflow:
"""A class to represent a workflow.
Workflow class provides set of methods to manage state of the workflow.
It allows for tool insertions, removals and... | from __future__ import annotations
from typing import Optional, Union
from tools import tools
from exceptions import workflow_exceptions
class Workflow:
"""A class to represent a workflow.
Workflow class provides set of methods to manage state of the workflow.
It allows for tool insertions, removals and... | en | 0.793103 | A class to represent a workflow. Workflow class provides set of methods to manage state of the workflow. It allows for tool insertions, removals and modifications. When workflow is run data flow is built and each tool linked to the workflow instance is executed in determined order. Tool outputs are th... | 3.060595 | 3 |
team_fundraising/text.py | namtel-hp/fundraising-website | 5 | 4226 |
class Donation_text:
# Shown as a message across the top of the page on return from a donation
# used in views.py:new_donation()
thank_you = (
"Thank you for your donation. "
"You may need to refresh this page to see the donation."
)
confirmation_email_subject = (
'Thank y... |
class Donation_text:
# Shown as a message across the top of the page on return from a donation
# used in views.py:new_donation()
thank_you = (
"Thank you for your donation. "
"You may need to refresh this page to see the donation."
)
confirmation_email_subject = (
'Thank y... | en | 0.782886 | # Shown as a message across the top of the page on return from a donation # used in views.py:new_donation() # Start of the email sent confirming the paypal payment has gone through # used in paypal.py:process_paypal() # Closing of the email sent confirming the paypal payment has gone through # used in paypal.py:process... | 2.748812 | 3 |
tests/wagtail_live/test_apps.py | wagtail/wagtail-live | 22 | 4227 | from django.apps import apps
from django.test import override_settings
from wagtail_live.signals import live_page_update
def test_live_page_update_signal_receivers():
assert len(live_page_update.receivers) == 0
@override_settings(
WAGTAIL_LIVE_PUBLISHER="tests.testapp.publishers.DummyWebsocketPublisher"
)
... | from django.apps import apps
from django.test import override_settings
from wagtail_live.signals import live_page_update
def test_live_page_update_signal_receivers():
assert len(live_page_update.receivers) == 0
@override_settings(
WAGTAIL_LIVE_PUBLISHER="tests.testapp.publishers.DummyWebsocketPublisher"
)
... | en | 0.84614 | # Receiver should be connected, no IndexError | 1.706289 | 2 |
PLM/options.py | vtta2008/pipelineTool | 7 | 4228 | # -*- coding: utf-8 -*-
"""
Script Name:
Author: <NAME>/Jimmy - 3D artist.
Description:
"""
# -------------------------------------------------------------------------------------------------------------
""" Import """
import os
from PySide2.QtWidgets import (QFrame, QStyle, QAbstractItemView, QSizePolicy, ... | # -*- coding: utf-8 -*-
"""
Script Name:
Author: <NAME>/Jimmy - 3D artist.
Description:
"""
# -------------------------------------------------------------------------------------------------------------
""" Import """
import os
from PySide2.QtWidgets import (QFrame, QStyle, QAbstractItemView, QSizePolicy, ... | en | 0.254059 | # -*- coding: utf-8 -*- Script Name: Author: <NAME>/Jimmy - 3D artist. Description: # ------------------------------------------------------------------------------------------------------------- Import # Basic color # Dark Palette color # Nice color # Size policy # Alignment # Docking area # datestamp # ------------... | 1.637015 | 2 |
Crawling/ssafyCrawling.py | Nyapy/FMTG | 0 | 4229 | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import sys
import time
import urllib.request
import os
sys.stdin = open('idpwd.txt')
site = input()
id = input()
pwd = input()
# selenium에서 사용할 웹 드라이버 절대 경로 정보
chromedriver = 'C:\Webdriver\chromedriver.exe'
# selenum의 webdriver에 앞서 설치... | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import sys
import time
import urllib.request
import os
sys.stdin = open('idpwd.txt')
site = input()
id = input()
pwd = input()
# selenium에서 사용할 웹 드라이버 절대 경로 정보
chromedriver = 'C:\Webdriver\chromedriver.exe'
# selenum의 webdriver에 앞서 설치... | ko | 0.2547 | # selenium에서 사용할 웹 드라이버 절대 경로 정보 # selenum의 webdriver에 앞서 설치한 chromedirver를 연동한다. # driver로 특정 페이지를 크롤링한다. # driver.find_element_by_id('searchContNm').send_keys('aps') # # driver.find_element_by_xpath("//button[@onclick='fnSearch();']").click() # driver.find_elements_by_xpath("//button[@title='마지막 페이지']")[0].click() # ... | 3.167903 | 3 |
100days/day95/StringIO_demo.py | chainren/python-learn | 0 | 4230 | <reponame>chainren/python-learn<gh_stars>0
from io import StringIO
# 定义一个 StringIO 对象,写入并读取其在内存中的内容
f = StringIO()
f.write('Python-100')
str = f.getvalue() # 读取写入的内容
print('写入内存中的字符串为:%s' %str)
f.write('\n') # 追加内容
f.write('坚持100天')
f.close() # 关闭
f1 = StringIO('Python-100' + '\n' + '坚持100天')
# 读取内容
print(f1.re... | from io import StringIO
# 定义一个 StringIO 对象,写入并读取其在内存中的内容
f = StringIO()
f.write('Python-100')
str = f.getvalue() # 读取写入的内容
print('写入内存中的字符串为:%s' %str)
f.write('\n') # 追加内容
f.write('坚持100天')
f.close() # 关闭
f1 = StringIO('Python-100' + '\n' + '坚持100天')
# 读取内容
print(f1.read())
f1.close()
# 假设的爬虫数据输出函数 outputDat... | zh | 0.948226 | # 定义一个 StringIO 对象,写入并读取其在内存中的内容 # 读取写入的内容 # 追加内容 # 关闭 # 读取内容 # 假设的爬虫数据输出函数 outputData() # dataStr 为爬虫数据字符串 # 1. 将 outputData() 函数返回的内容写入内存中 # 假设的爬虫数据输出函数 outputData() # dataStr 为爬虫数据字符串 # 1. 将 outputData() 函数返回的内容写入内存中 # 1.1 输出 StringIO 在内存中写入的数据 # 1.2 按行输出写入的数据方式一 # 去掉每行数据末尾的换行符 # 1.2 按行输出写入的数据方式一 # 去掉每行数据末尾的换行符 # 1.... | 3.30827 | 3 |
tests/test_cli.py | Nate1729/FinPack | 1 | 4231 | """Contains tests for finpack/core/cli.py
"""
__copyright__ = "Copyright (C) 2021 <NAME>"
import os
import unittest
from importlib import metadata
from docopt import docopt
from finpack.core import cli
class TestCli(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.DATA_DIR = "temp"
... | """Contains tests for finpack/core/cli.py
"""
__copyright__ = "Copyright (C) 2021 <NAME>"
import os
import unittest
from importlib import metadata
from docopt import docopt
from finpack.core import cli
class TestCli(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.DATA_DIR = "temp"
... | en | 0.673651 | Contains tests for finpack/core/cli.py | 2.416289 | 2 |
python/Patterns/inheritance/main.py | zinderud/ysa | 0 | 4232 | class Yaratik(object):
def move_left(self):
print('Moving left...')
def move_right(self):
print('Moving left...')
class Ejderha(Yaratik):
def Ates_puskurtme(self):
print('ates puskurtum!')
class Zombie(Yaratik):
def Isirmak(self):
print('Isirdim simdi!')
enemy =... | class Yaratik(object):
def move_left(self):
print('Moving left...')
def move_right(self):
print('Moving left...')
class Ejderha(Yaratik):
def Ates_puskurtme(self):
print('ates puskurtum!')
class Zombie(Yaratik):
def Isirmak(self):
print('Isirdim simdi!')
enemy =... | en | 0.912196 | # ejderha also includes all functions from parent class (yaratik) # Zombie is called the (child class), inherits from Yaratik (parent class) | 3.543972 | 4 |
clustering/graph_utils.py | perathambkk/ml-techniques | 0 | 4233 | """
Author: <NAME>
"""
import numpy as np
import pandas as pd
from sklearn.neighbors import NearestNeighbors
def affinity_graph(X):
'''
This function returns a numpy array.
'''
ni, nd = X.shape
A = np.zeros((ni, ni))
for i in range(ni):
for j in range(i+1, ni):
dist = ((X[i] - X[j])**2).sum() # compute ... | """
Author: <NAME>
"""
import numpy as np
import pandas as pd
from sklearn.neighbors import NearestNeighbors
def affinity_graph(X):
'''
This function returns a numpy array.
'''
ni, nd = X.shape
A = np.zeros((ni, ni))
for i in range(ni):
for j in range(i+1, ni):
dist = ((X[i] - X[j])**2).sum() # compute ... | en | 0.651194 | Author: <NAME> This function returns a numpy array. # compute L2 distance # by symmetry This function returns a numpy array. # by symmetry TODO: This function returns a numpy sparse matrix. # compute L2 distance # by symmetry The unnormalized graph Laplacian, L = D − W. | 3.376109 | 3 |
recipe_engine/internal/commands/__init__.py | Acidburn0zzz/luci | 1 | 4234 | <gh_stars>1-10
# Copyright 2019 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""This package houses all subcommands for the recipe engine.
See implementation_details.md for the expectations of the modules in... | # Copyright 2019 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""This package houses all subcommands for the recipe engine.
See implementation_details.md for the expectations of the modules in this
directory... | en | 0.866571 | # Copyright 2019 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. This package houses all subcommands for the recipe engine. See implementation_details.md for the expectations of the modules in this directory. # ... | 1.907633 | 2 |
openfl/pipelines/stc_pipeline.py | sarthakpati/openfl | 0 | 4235 | <filename>openfl/pipelines/stc_pipeline.py
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""STCPipelinemodule."""
import numpy as np
import gzip as gz
from .pipeline import TransformationPipeline, Transformer
class SparsityTransformer(Transformer):
"""A transformer class to ... | <filename>openfl/pipelines/stc_pipeline.py
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""STCPipelinemodule."""
import numpy as np
import gzip as gz
from .pipeline import TransformationPipeline, Transformer
class SparsityTransformer(Transformer):
"""A transformer class to ... | en | 0.523502 | # Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 STCPipelinemodule. A transformer class to sparsify input data. Initialize. Args: p (float): sparsity ratio (Default=0.01) Sparsify data and pass over only non-sparsified elements by reducing the array size. A... | 2.313707 | 2 |
tests/component/test_grid_mixin.py | csdms/pymt | 38 | 4236 | import numpy as np
import pytest
from pytest import approx
from pymt.component.grid import GridMixIn
class Port:
def __init__(self, name, uses=None, provides=None):
self._name = name
self._uses = uses or []
self._provides = provides or []
def get_component_name(self):
return ... | import numpy as np
import pytest
from pytest import approx
from pymt.component.grid import GridMixIn
class Port:
def __init__(self, name, uses=None, provides=None):
self._name = name
self._uses = uses or []
self._provides = provides or []
def get_component_name(self):
return ... | none | 1 | 2.132884 | 2 | |
scripts/compare.py | SnoozeTime/nes | 1 | 4237 | import sys
def load_log_sp(filename):
data = []
with open(filename) as f:
for line in f.readlines():
tokens = line.split(" ")
spidx = line.find("SP:")
endidx = line.find(' ', spidx)
data.append((line[0:4], line[spidx+3:endidx]))
return data
if __nam... | import sys
def load_log_sp(filename):
data = []
with open(filename) as f:
for line in f.readlines():
tokens = line.split(" ")
spidx = line.find("SP:")
endidx = line.find(' ', spidx)
data.append((line[0:4], line[spidx+3:endidx]))
return data
if __nam... | none | 1 | 2.800943 | 3 | |
tercer_modelo.py | nahuelalmeira/deepLearning | 0 | 4238 | """Exercise 1
Usage:
$ CUDA_VISIBLE_DEVICES=2 python practico_1_train_petfinder.py --dataset_dir ../ --epochs 30 --dropout 0.1 0.1 --hidden_layer_sizes 200 100
To know which GPU to use, you can check it with the command
$ nvidia-smi
"""
import argparse
import os
import mlflow
import pickle
import numpy as np
impo... | """Exercise 1
Usage:
$ CUDA_VISIBLE_DEVICES=2 python practico_1_train_petfinder.py --dataset_dir ../ --epochs 30 --dropout 0.1 0.1 --hidden_layer_sizes 200 100
To know which GPU to use, you can check it with the command
$ nvidia-smi
"""
import argparse
import os
import mlflow
import pickle
import numpy as np
impo... | de | 0.7285 | Exercise 1 Usage: $ CUDA_VISIBLE_DEVICES=2 python practico_1_train_petfinder.py --dataset_dir ../ --epochs 30 --dropout 0.1 0.1 --hidden_layer_sizes 200 100 To know which GPU to use, you can check it with the command $ nvidia-smi # Here you have some examples of classifier parameters. You can add # more arguments o... | 2.833052 | 3 |
catpy/applications/export.py | catmaid/catpy | 5 | 4239 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from pkg_resources import parse_version
from warnings import warn
from copy import deepcopy
import networkx as nx
from networkx.readwrite import json_graph
from catpy.applications.base import CatmaidClientApplication
NX_VERSION_INFO = parse_version(nx.... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from pkg_resources import parse_version
from warnings import warn
from copy import deepcopy
import networkx as nx
from networkx.readwrite import json_graph
from catpy.applications.base import CatmaidClientApplication
NX_VERSION_INFO = parse_version(nx.... | en | 0.59392 | # -*- coding: utf-8 -*- #26 [1]. " NetworkX serialises graphs differently in v1.x and v2.x. This converts v1-style data (as emitted by CATMAID) to v2-style data. See issue #26 https://github.com/catmaid/catpy/issues/26 Parameters ---------- jso : dict Returns ------- dict Get a singl... | 2.240587 | 2 |
packages/watchmen-data-kernel/src/watchmen_data_kernel/meta/external_writer_service.py | Indexical-Metrics-Measure-Advisory/watchmen | 0 | 4240 | from typing import Optional
from watchmen_auth import PrincipalService
from watchmen_data_kernel.cache import CacheService
from watchmen_data_kernel.common import DataKernelException
from watchmen_data_kernel.external_writer import find_external_writer_create, register_external_writer_creator
from watchmen_meta.common... | from typing import Optional
from watchmen_auth import PrincipalService
from watchmen_data_kernel.cache import CacheService
from watchmen_data_kernel.common import DataKernelException
from watchmen_data_kernel.external_writer import find_external_writer_create, register_external_writer_creator
from watchmen_meta.common... | en | 0.214864 | # noinspection PyTypeChecker | 1.876367 | 2 |
udemy-python/mediaponderada.py | AlbertoAlfredo/exercicios-cursos | 1 | 4241 | <reponame>AlbertoAlfredo/exercicios-cursos
nota1 = float(input('Digite a nota da primeira nota '))
peso1 = float(input('Digite o peso da primeira nota '))
nota2 = float(input('Digite a nota da seugundo nota '))
peso2 = float(input('Digite o peso da segundo nota '))
media = (nota1/peso1+nota2/peso2)/2
print('A média ... | nota1 = float(input('Digite a nota da primeira nota '))
peso1 = float(input('Digite o peso da primeira nota '))
nota2 = float(input('Digite a nota da seugundo nota '))
peso2 = float(input('Digite o peso da segundo nota '))
media = (nota1/peso1+nota2/peso2)/2
print('A média das duas notas é:', media) | none | 1 | 3.886665 | 4 | |
scrywarden/module.py | chasebrewsky/scrywarden | 1 | 4242 | <reponame>chasebrewsky/scrywarden
from importlib import import_module
from typing import Any
def import_string(path: str) -> Any:
"""Imports a dotted path name and returns the class/attribute.
Parameters
----------
path: str
Dotted module path to retrieve.
Returns
-------
Class/a... | from importlib import import_module
from typing import Any
def import_string(path: str) -> Any:
"""Imports a dotted path name and returns the class/attribute.
Parameters
----------
path: str
Dotted module path to retrieve.
Returns
-------
Class/attribute at the given import path.... | en | 0.425515 | Imports a dotted path name and returns the class/attribute. Parameters ---------- path: str Dotted module path to retrieve. Returns ------- Class/attribute at the given import path. Raises ------ ImportError If the path does not exist. | 3.244117 | 3 |
release/scripts/modules/bl_i18n_utils/utils_spell_check.py | dvgd/blender | 0 | 4243 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | en | 0.783594 | # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib... | 2.160232 | 2 |
naslib/predictors/mlp.py | gmeyerlee/NASLib | 0 | 4244 | <gh_stars>0
import numpy as np
import os
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from naslib.utils.utils import AverageMeterGroup
from naslib.predictors.utils.encodings import encode
from naslib.pr... | import numpy as np
import os
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from naslib.utils.utils import AverageMeterGroup
from naslib.predictors.utils.encodings import encode
from naslib.predictors imp... | en | 0.67723 | # NOTE: faster on CPU # make the init similar to the tf.keras version # add L1 regularization | 2.583968 | 3 |
pythonforandroid/recipes/libx264/__init__.py | Joreshic/python-for-android | 1 | 4245 | from pythonforandroid.toolchain import Recipe, shprint, current_directory, ArchARM
from os.path import exists, join, realpath
from os import uname
import glob
import sh
class LibX264Recipe(Recipe):
version = 'x264-snapshot-20170608-2245-stable' # using mirror url since can't use ftp
url = 'http://mirror.yand... | from pythonforandroid.toolchain import Recipe, shprint, current_directory, ArchARM
from os.path import exists, join, realpath
from os import uname
import glob
import sh
class LibX264Recipe(Recipe):
version = 'x264-snapshot-20170608-2245-stable' # using mirror url since can't use ftp
url = 'http://mirror.yand... | en | 0.955601 | # using mirror url since can't use ftp | 1.979717 | 2 |
Win/reg.py | QGB/QPSU | 6 | 4246 | #coding=utf-8
try:
if __name__.startswith('qgb.Win'):
from .. import py
else:
import py
except Exception as ei:
raise ei
raise EnvironmentError(__name__)
if py.is2():
import _winreg as winreg
from _winreg import *
else:
import winreg
from winreg import *
def get(skey,name,root=HKEY_CURRENT_USER,returnTyp... | #coding=utf-8
try:
if __name__.startswith('qgb.Win'):
from .. import py
else:
import py
except Exception as ei:
raise ei
raise EnvironmentError(__name__)
if py.is2():
import _winreg as winreg
from _winreg import *
else:
import winreg
from winreg import *
def get(skey,name,root=HKEY_CURRENT_USER,returnTyp... | en | 0.500952 | #coding=utf-8 from qgb.Win import reg reg.get(r'Software\Microsoft\Windows\CurrentVersion\Internet Settings','ProxyEnable') reg.get(r'HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters\Size' ) There are seven predefined root keys, traditionally named according to their constant handles defined in the W... | 2.206599 | 2 |
tests/test_handler.py | CJSoldier/webssh | 13 | 4247 | <filename>tests/test_handler.py
import unittest
import paramiko
from tornado.httputil import HTTPServerRequest
from tests.utils import read_file, make_tests_data_path
from webssh.handler import MixinHandler, IndexHandler, InvalidValueError
class TestMixinHandler(unittest.TestCase):
def test_get_real_client_addr... | <filename>tests/test_handler.py
import unittest
import paramiko
from tornado.httputil import HTTPServerRequest
from tests.utils import read_file, make_tests_data_path
from webssh.handler import MixinHandler, IndexHandler, InvalidValueError
class TestMixinHandler(unittest.TestCase):
def test_get_real_client_addr... | none | 1 | 2.347794 | 2 | |
apps/notifications/tests/test_views.py | SCiO-systems/qcat | 0 | 4248 | <gh_stars>0
import logging
from unittest import mock
from unittest.mock import call
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.signing import Signer
from django.urls import reverse
from django.http import Http404
from django.test import RequestFactory
from braces.... | import logging
from unittest import mock
from unittest.mock import call
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.signing import Signer
from django.urls import reverse
from django.http import Http404
from django.test import RequestFactory
from braces.views import... | en | 0.76712 | # for faster tests, mock all the elements. elements are created here # as this makes the tests more readable. # logs are ordered by creation date - 42 is the newer one #def test_add_user_aware_data_is_todo(self): # data = self._test_add_user_aware_data() # self.assertTrue(data[1]['is_todo']) | 2.176538 | 2 |
examples/resources.py | willvousden/clint | 1,230 | 4249 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
from clint import resources
resources.init('kennethreitz', 'clint')
lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
from clint import resources
resources.init('kennethreitz', 'clint')
lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt... | en | 0.352855 | #!/usr/bin/env python # -*- coding: utf-8 -*- | 2.215885 | 2 |
photos/urls.py | charlesmugambi/Instagram | 0 | 4250 | from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^image/$', views.add_image, name='upload_image'),
url(r'^profile/$', views.profile_info, name='profile'),
url(r'... | from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^image/$', views.add_image, name='upload_image'),
url(r'^profile/$', views.profile_info, name='profile'),
url(r'... | none | 1 | 1.907633 | 2 | |
bread.py | vgfang/breadbot | 0 | 4251 | <reponame>vgfang/breadbot
import random
import math
from fractions import Fraction
from datetime import datetime
from jinja2 import Template
# empty class for passing to template engine
class Recipe:
def __init__(self):
return
# returns flour percent using flour type
def get_special_flour_percent(flourType: str, ... | import random
import math
from fractions import Fraction
from datetime import datetime
from jinja2 import Template
# empty class for passing to template engine
class Recipe:
def __init__(self):
return
# returns flour percent using flour type
def get_special_flour_percent(flourType: str, breadFlourPercent:int) -> ... | en | 0.745964 | # empty class for passing to template engine # returns flour percent using flour type # returns multiplied spoon units from teaspoon fraction input, 3 tsp = 1 tbsp # use tablespoons # returns amount given the type of flavoring(spices) # floors to the 500g/scale for clean fractional multiplication # flavors in category ... | 3.237284 | 3 |
posthog/api/test/test_organization_domain.py | msnitish/posthog | 0 | 4252 | import datetime
from unittest.mock import patch
import dns.resolver
import dns.rrset
import pytest
import pytz
from django.utils import timezone
from freezegun import freeze_time
from rest_framework import status
from posthog.models import Organization, OrganizationDomain, OrganizationMembership, Team
from posthog.te... | import datetime
from unittest.mock import patch
import dns.resolver
import dns.rrset
import pytest
import pytz
from django.utils import timezone
from freezegun import freeze_time
from rest_framework import status
from posthog.models import Organization, OrganizationDomain, OrganizationMembership, Team
from posthog.te... | en | 0.563697 | Tests the task that re-verifies domains to ensure ownership is maintained. # type: ignore # type: ignore # type: ignore # List & retrieve domains # Create domains # ignore me # ignore me # ignore me # ignore me # ignore me # ignore me # ignore me # ignore me # Update domains # SSO Enforcement # JIT Provisioning # Delet... | 2.273185 | 2 |
tutorial/test input.py | nataliapryakhina/FA_group3 | 0 | 4253 | import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
from os import listdir
from tensorflow.keras.callbacks import ModelCheckpoint
dataDir = "./data/trainSmallFA/"
files = listdir(dataDir)
files.sort()
totalLength = len(files)
inputs = np.empty((len(files), 3, 64, 64)... | import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
from os import listdir
from tensorflow.keras.callbacks import ModelCheckpoint
dataDir = "./data/trainSmallFA/"
files = listdir(dataDir)
files.sort()
totalLength = len(files)
inputs = np.empty((len(files), 3, 64, 64)... | en | 0.324437 | # inx, iny, mask # p, velx, vely # print("inputs shape = ", inputs.shape) # predicted data # vmin=-100,vmax=100, cmap='jet') | 2.325281 | 2 |
pepper/responder/brain.py | cltl/pepper | 29 | 4254 | <filename>pepper/responder/brain.py<gh_stars>10-100
from pepper.framework import *
from pepper import logger
from pepper.language import Utterance
from pepper.language.generation.thoughts_phrasing import phrase_thoughts
from pepper.language.generation.reply import reply_to_question
from .responder import Responder, R... | <filename>pepper/responder/brain.py<gh_stars>10-100
from pepper.framework import *
from pepper import logger
from pepper.language import Utterance
from pepper.language.generation.thoughts_phrasing import phrase_thoughts
from pepper.language.generation.reply import reply_to_question
from .responder import Responder, R... | en | 0.739287 | # type: (Utterance, Union[TextToSpeechComponent, BrainComponent]) -> Optional[Tuple[float, Callable]] # Searches for types in dbpedia # Return Score and Response # Make sure to not execute the response here, but just to return the response function # Thank Human for the Data! # Apologize to human for not knowing | 2.500875 | 3 |
fedora_college/modules/content/views.py | fedora-infra/fedora-college | 2 | 4255 | <filename>fedora_college/modules/content/views.py
# -*- coding: utf-8 -*-
import re
from unicodedata import normalize
from flask import Blueprint, render_template, current_app
from flask import redirect, url_for, g, abort
from sqlalchemy import desc
from fedora_college.core.database import db
from fedora_college.module... | <filename>fedora_college/modules/content/views.py
# -*- coding: utf-8 -*-
import re
from unicodedata import normalize
from flask import Blueprint, render_template, current_app
from flask import redirect, url_for, g, abort
from sqlalchemy import desc
from fedora_college.core.database import db
from fedora_college.module... | en | 0.719539 | # -*- coding: utf-8 -*- # noqa # noqa # noqa # Verify if user is authenticated # generate url slug Generates an slightly worse ASCII-only slug. # attach tags to a content entry # delete content delete mapped tags delete comments with foriegn keys # add / edit more content Publish the message Publish the message # Dupli... | 2.058295 | 2 |
tests/components/airthings/test_config_flow.py | MrDelik/core | 30,023 | 4256 | <reponame>MrDelik/core<filename>tests/components/airthings/test_config_flow.py
"""Test the Airthings config flow."""
from unittest.mock import patch
import airthings
from homeassistant import config_entries
from homeassistant.components.airthings.const import CONF_ID, CONF_SECRET, DOMAIN
from homeassistant.core impor... | """Test the Airthings config flow."""
from unittest.mock import patch
import airthings
from homeassistant import config_entries
from homeassistant.components.airthings.const import CONF_ID, CONF_SECRET, DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import RESULT_TYPE_CREATE_EN... | en | 0.754076 | Test the Airthings config flow. Test we get the form. Test we handle invalid auth. Test we handle cannot connect error. Test we handle unknown error. Test user input for config_entry that already exists. | 2.387663 | 2 |
utils/utils.py | scomup/StereoNet-ActiveStereoNet | 0 | 4257 | <reponame>scomup/StereoNet-ActiveStereoNet
# ------------------------------------------------------------------------------
# Copyright (c) NKU
# Licensed under the MIT License.
# Written by <NAME> (<EMAIL>)
# ------------------------------------------------------------------------------
import os
import torch
import t... | # ------------------------------------------------------------------------------
# Copyright (c) NKU
# Licensed under the MIT License.
# Written by <NAME> (<EMAIL>)
# ------------------------------------------------------------------------------
import os
import torch
import torch.nn.functional as F
#import cv2 as cv
i... | en | 0.258975 | # ------------------------------------------------------------------------------ # Copyright (c) NKU # Licensed under the MIT License. # Written by <NAME> (<EMAIL>) # ------------------------------------------------------------------------------ #import cv2 as cv # mask = (GT < args.maxdisp) & (GT >= 0) # print(mask.si... | 2.196782 | 2 |
worker/main.py | Devalent/facial-recognition-service | 0 | 4258 | <reponame>Devalent/facial-recognition-service
from aiohttp import web
import base64
import io
import face_recognition
async def encode(request):
request_data = await request.json()
# Read base64 encoded image
url = request_data['image'].split(',')[1]
image = io.BytesIO(base64.b64decode(url))
# Lo... | from aiohttp import web
import base64
import io
import face_recognition
async def encode(request):
request_data = await request.json()
# Read base64 encoded image
url = request_data['image'].split(',')[1]
image = io.BytesIO(base64.b64decode(url))
# Load image data
np_array = face_recognition.... | en | 0.662832 | # Read base64 encoded image # Load image data # Find face locations # Create face encodings | 2.826443 | 3 |
rblod/setup.py | TiKeil/Two-scale-RBLOD | 0 | 4259 | # ~~~
# This file is part of the paper:
#
# " An Online Efficient Two-Scale Reduced Basis Approach
# for the Localized Orthogonal Decomposition "
#
# https://github.com/TiKeil/Two-scale-RBLOD.git
#
# Copyright 2019-2021 all developers. All rights reserved.
# License: Licensed as BSD 2-Clause ... | # ~~~
# This file is part of the paper:
#
# " An Online Efficient Two-Scale Reduced Basis Approach
# for the Localized Orthogonal Decomposition "
#
# https://github.com/TiKeil/Two-scale-RBLOD.git
#
# Copyright 2019-2021 all developers. All rights reserved.
# License: Licensed as BSD 2-Clause ... | en | 0.809519 | # ~~~ # This file is part of the paper: # # " An Online Efficient Two-Scale Reduced Basis Approach # for the Localized Orthogonal Decomposition " # # https://github.com/TiKeil/Two-scale-RBLOD.git # # Copyright 2019-2021 all developers. All rights reserved. # License: Licensed as BSD 2-Clause ... | 1.381793 | 1 |
bin/euclid_fine_plot_job_array.py | ndeporzio/cosmicfish | 0 | 4260 | import os
import shutil
import numpy as np
import pandas as pd ... | import os
import shutil
import numpy as np
import pandas as pd ... | en | 0.617972 | # Instruct pyplot to use seaborn # Set project, data, CLASS directories # Generate output paths # Specify resolution of numerical integrals # How much to vary parameter to calculate numerical derivative # For calculating numerical integral wrt mu between -1 and 1 # Linda Fiducial Cosmology # Units [K] # Units [T_cmb]. ... | 2.290705 | 2 |
project4/test/test_arm.py | XDZhelheim/CS205_C_CPP_Lab | 3 | 4261 | <reponame>XDZhelheim/CS205_C_CPP_Lab
import os
if __name__ == "__main__":
dims = ["32", "64", "128", "256", "512", "1024", "2048"]
for dim in dims:
os.system(
f"perf stat -e r11 -x, -r 10 ../matmul.out ../data/mat-A-{dim}.txt ../data/mat-B-{dim}.txt ./out/out-{dim}.txt 2>>res_arm.csv"
... | import os
if __name__ == "__main__":
dims = ["32", "64", "128", "256", "512", "1024", "2048"]
for dim in dims:
os.system(
f"perf stat -e r11 -x, -r 10 ../matmul.out ../data/mat-A-{dim}.txt ../data/mat-B-{dim}.txt ./out/out-{dim}.txt 2>>res_arm.csv"
)
print(f"Finished {dim}... | none | 1 | 2.229106 | 2 | |
src/oci/apm_traces/models/query_result_row_type_summary.py | Manny27nyc/oci-python-sdk | 249 | 4262 | <reponame>Manny27nyc/oci-python-sdk<filename>src/oci/apm_traces/models/query_result_row_type_summary.py
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.... | # coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | en | 0.648036 | # coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | 2.137006 | 2 |
jaxformer/hf/sample.py | salesforce/CodeGen | 105 | 4263 | <gh_stars>100-1000
# Copyright (c) 2022, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
import os
import re
import time
import random
import argparse
import torch
from t... | # Copyright (c) 2022, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
import os
import re
import time
import random
import argparse
import torch
from transformers import ... | de | 0.473912 | # Copyright (c) 2022, salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause ######################################################################## # util # torch.use_determinist... | 1.93372 | 2 |
tests/services/test_rover_runner_service.py | dev-11/mars-rover-challenge | 0 | 4264 | <reponame>dev-11/mars-rover-challenge
import unittest
from services import RoverRunnerService
from tests.test_environment.marses import small_mars_with_one_rover_empty_commands
from tests.test_environment import mocks as m
from data_objects import Rover
class TestRoverRunnerService(unittest.TestCase):
def test_r... | import unittest
from services import RoverRunnerService
from tests.test_environment.marses import small_mars_with_one_rover_empty_commands
from tests.test_environment import mocks as m
from data_objects import Rover
class TestRoverRunnerService(unittest.TestCase):
def test_rover_runner_moves_rover_forward(self):... | none | 1 | 2.753706 | 3 | |
retrain_with_rotnet.py | ericdaat/self-label | 440 | 4265 | import argparse
import warnings
warnings.simplefilter("ignore", UserWarning)
import files
from tensorboardX import SummaryWriter
import os
import numpy as np
import time
import torch
import torch.optim
import torch.nn as nn
import torch.utils.data
import torchvision
import torchvision.transforms as tfs
from data impo... | import argparse
import warnings
warnings.simplefilter("ignore", UserWarning)
import files
from tensorboardX import SummaryWriter
import os
import numpy as np
import time
import torch
import torch.optim
import torch.nn as nn
import torch.utils.data
import torchvision
import torchvision.transforms as tfs
from data impo... | de | 0.410305 | # house keeping # len(loader) #################### train CNN ########################################### # every few iter logging # end of epoch logging Perform full optimization. ##################################################################################### # Perform optmization ################################... | 2.109258 | 2 |
tests/vie.py | Jinwithyoo/han | 0 | 4266 | # -*- coding: utf-8 -*-
from tests import HangulizeTestCase
from hangulize.langs.vie import Vietnamese
class VietnameseTestCase(HangulizeTestCase):
""" http://korean.go.kr/09_new/dic/rule/rule_foreign_0218.jsp """
lang = Vietnamese()
def test_1st(self):
"""제1항
nh는 이어지는 모음과 합쳐서 한 음절로 적는다.... | # -*- coding: utf-8 -*-
from tests import HangulizeTestCase
from hangulize.langs.vie import Vietnamese
class VietnameseTestCase(HangulizeTestCase):
""" http://korean.go.kr/09_new/dic/rule/rule_foreign_0218.jsp """
lang = Vietnamese()
def test_1st(self):
"""제1항
nh는 이어지는 모음과 합쳐서 한 음절로 적는다.... | ko | 0.99912 | # -*- coding: utf-8 -*- http://korean.go.kr/09_new/dic/rule/rule_foreign_0218.jsp 제1항 nh는 이어지는 모음과 합쳐서 한 음절로 적는다. 어말이나 자음 앞에서는 받침 ‘ㄴ' 으로 적되, 그 앞의 모음이 a인 경우에는 a와 합쳐 ‘아인'으로 적는다. # u'Nha Trang': u'냐짱', # u'<NAME>': u'호찌민', # u'Thanh Hoa': u'타인호아', # u'Đông Khanh': u'동카인', 제2항 qu... | 2.595398 | 3 |
tests/test_functions/test_trig.py | jackromo/mathLibPy | 1 | 4267 | from mathlibpy.functions import *
import unittest
class SinTester(unittest.TestCase):
def setUp(self):
self.sin = Sin()
def test_call(self):
self.assertEqual(self.sin(0), 0)
def test_eq(self):
self.assertEqual(self.sin, Sin())
def test_get_derivative_call(self):
sel... | from mathlibpy.functions import *
import unittest
class SinTester(unittest.TestCase):
def setUp(self):
self.sin = Sin()
def test_call(self):
self.assertEqual(self.sin(0), 0)
def test_eq(self):
self.assertEqual(self.sin, Sin())
def test_get_derivative_call(self):
sel... | none | 1 | 3.409808 | 3 | |
src/smallestLetter/target.py | rajitbanerjee/leetcode | 0 | 4268 | class Solution:
def nextGreatestLetter(self, letters: list, target: str) -> str:
if target < letters[0] or target >= letters[-1]:
return letters[0]
left, right = 0, len(letters) - 1
while left < right:
mid = left + (right - left) // 2
if letters[mid] > tar... | class Solution:
def nextGreatestLetter(self, letters: list, target: str) -> str:
if target < letters[0] or target >= letters[-1]:
return letters[0]
left, right = 0, len(letters) - 1
while left < right:
mid = left + (right - left) // 2
if letters[mid] > tar... | none | 1 | 3.548063 | 4 | |
anti_cpdaily/command.py | hyx0329/nonebot_plugin_anti_cpdaily | 2 | 4269 | <reponame>hyx0329/nonebot_plugin_anti_cpdaily
import nonebot
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.log import logger
from .config import global_config
from .schedule import anti_cpdaily_check_routine
cpdai... | import nonebot
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.log import logger
from .config import global_config
from .schedule import anti_cpdaily_check_routine
cpdaily = on_command('cpdaily')
scheduler = nonebot... | en | 0.468084 | Manually activate the routine in 1 min # await anti_cpdaily_check_routine() | 2.071621 | 2 |
matplotlib/gallery_python/pyplots/dollar_ticks.py | gottaegbert/penter | 13 | 4270 | <reponame>gottaegbert/penter
"""
============
Dollar Ticks
============
Use a `~.ticker.FormatStrFormatter` to prepend dollar signs on y axis labels.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = ... | """
============
Dollar Ticks
============
Use a `~.ticker.FormatStrFormatter` to prepend dollar signs on y axis labels.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.plot(100*np... | en | 0.355245 | ============ Dollar Ticks ============ Use a `~.ticker.FormatStrFormatter` to prepend dollar signs on y axis labels. # Fixing random state for reproducibility ############################################################################# # # ------------ # # References # """""""""" # # The use of the following function... | 3.126232 | 3 |
Chibrary/utils.py | chiro2001/chibrary | 0 | 4271 | <reponame>chiro2001/chibrary
import json
import re
from flask import request, abort, jsonify
from Chibrary import config
from Chibrary.config import logger
from Chibrary.exceptions import *
from functools import wraps
from urllib import parse
from Chibrary.server import db
def parse_url_query(url: str) -> dict:
i... | import json
import re
from flask import request, abort, jsonify
from Chibrary import config
from Chibrary.config import logger
from Chibrary.exceptions import *
from functools import wraps
from urllib import parse
from Chibrary.server import db
def parse_url_query(url: str) -> dict:
if not url.lower().startswith(... | zh | 0.210638 | # 注意这里的类型转化处理 # if not url.lower().startswith('http://') \ # and not url.lower().startswith('https://'): # logger.warning('Provided wrong url %s !' % url) # return url # if len(data) == 0: # return url # query = '?' # for key in data: # # 特事特办(?) # if type(data[key]) is str and '/' in data[k... | 2.45079 | 2 |
tests/inputs/loops/51-arrays-in-loop.py | helq/pytropos | 4 | 4272 | import numpy as np
from something import Top
i = 0
while i < 10:
a = np.ndarray((10,4))
b = np.ones((10, Top))
i += 1
del Top
# show_store()
| import numpy as np
from something import Top
i = 0
while i < 10:
a = np.ndarray((10,4))
b = np.ones((10, Top))
i += 1
del Top
# show_store()
| it | 0.453416 | # show_store() | 2.711477 | 3 |
tests/mappers/fields/test_float_field.py | Arfey/aiohttp_admin2 | 12 | 4273 | from aiohttp_admin2.mappers import Mapper
from aiohttp_admin2.mappers import fields
class FloatMapper(Mapper):
field = fields.FloatField()
def test_correct_float_type():
"""
In this test we check success convert to float type.
"""
mapper = FloatMapper({"field": 1})
mapper.is_valid()
ass... | from aiohttp_admin2.mappers import Mapper
from aiohttp_admin2.mappers import fields
class FloatMapper(Mapper):
field = fields.FloatField()
def test_correct_float_type():
"""
In this test we check success convert to float type.
"""
mapper = FloatMapper({"field": 1})
mapper.is_valid()
ass... | en | 0.761238 | In this test we check success convert to float type. In this test we check error when we received wrong float type. | 3.217755 | 3 |
autotest/t038_test.py | jdlarsen-UA/flopy | 2 | 4274 | <gh_stars>1-10
"""
Try to load all of the MODFLOW-USG examples in ../examples/data/mfusg_test.
These are the examples that are distributed with MODFLOW-USG.
"""
import os
import flopy
# make the working directory
tpth = os.path.join("temp", "t038")
if not os.path.isdir(tpth):
os.makedirs(tpth)
# build list of na... | """
Try to load all of the MODFLOW-USG examples in ../examples/data/mfusg_test.
These are the examples that are distributed with MODFLOW-USG.
"""
import os
import flopy
# make the working directory
tpth = os.path.join("temp", "t038")
if not os.path.isdir(tpth):
os.makedirs(tpth)
# build list of name files to try... | en | 0.851849 | Try to load all of the MODFLOW-USG examples in ../examples/data/mfusg_test. These are the examples that are distributed with MODFLOW-USG. # make the working directory # build list of name files to try and load # # function to load a MODFLOW-USG model and then write it back out | 2.333097 | 2 |
botlib/cli.py | relikd/botlib | 0 | 4275 | #!/usr/bin/env python3
import os
from argparse import ArgumentParser, ArgumentTypeError, FileType, Namespace
from typing import Any
def DirType(string: str) -> str:
if os.path.isdir(string):
return string
raise ArgumentTypeError(
'Directory does not exist: "{}"'.format(os.path.abspath(string))... | #!/usr/bin/env python3
import os
from argparse import ArgumentParser, ArgumentTypeError, FileType, Namespace
from typing import Any
def DirType(string: str) -> str:
if os.path.isdir(string):
return string
raise ArgumentTypeError(
'Directory does not exist: "{}"'.format(os.path.abspath(string))... | fr | 0.221828 | #!/usr/bin/env python3 | 3.029707 | 3 |
pyhanko_certvalidator/asn1_types.py | MatthiasValvekens/certvalidator | 4 | 4276 | <filename>pyhanko_certvalidator/asn1_types.py
from typing import Optional
from asn1crypto import core, x509, cms
__all__ = [
'Target', 'TargetCert', 'Targets', 'SequenceOfTargets',
'AttrSpec', 'AAControls'
]
class TargetCert(core.Sequence):
_fields = [
('target_certificate', cms.IssuerSerial),
... | <filename>pyhanko_certvalidator/asn1_types.py
from typing import Optional
from asn1crypto import core, x509, cms
__all__ = [
'Target', 'TargetCert', 'Targets', 'SequenceOfTargets',
'AttrSpec', 'AAControls'
]
class TargetCert(core.Sequence):
_fields = [
('target_certificate', cms.IssuerSerial),
... | en | 0.891003 | # Blame X.509... # handle AA controls (not natively supported by asn1crypto, so # not available as an attribute). # Deal with wbond/asn1crypto#218 # Deal with wbond/asn1crypto#220 # patch in attribute certificate extensions # Note: unlike in Certomancer, we don't do this one conditionally, since # we need the actual Py... | 2.105106 | 2 |
test/test_delete_group.py | ruslankl9/ironpython_training | 0 | 4277 | <filename>test/test_delete_group.py
from model.group import Group
import random
def test_delete_some_group(app):
if len(app.group.get_group_list()) <= 1:
app.group.add_new_group(Group(name='test'))
old_list = app.group.get_group_list()
index = random.randrange(len(old_list))
app.group.delete_g... | <filename>test/test_delete_group.py
from model.group import Group
import random
def test_delete_some_group(app):
if len(app.group.get_group_list()) <= 1:
app.group.add_new_group(Group(name='test'))
old_list = app.group.get_group_list()
index = random.randrange(len(old_list))
app.group.delete_g... | none | 1 | 2.738082 | 3 | |
Evaluation/batch_detection.py | gurkirt/actNet-inAct | 27 | 4278 | <filename>Evaluation/batch_detection.py
'''
Autor: <NAME>
Start data: 15th May 2016
purpose: of this file is read frame level predictions and process them to produce a label per video
'''
from sklearn.svm import LinearSVC
from sklearn.ensemble import RandomForestClassifier
import numpy as np
import pickle
import os
im... | <filename>Evaluation/batch_detection.py
'''
Autor: <NAME>
Start data: 15th May 2016
purpose: of this file is read frame level predictions and process them to produce a label per video
'''
from sklearn.svm import LinearSVC
from sklearn.ensemble import RandomForestClassifier
import numpy as np
import pickle
import os
im... | en | 0.61567 | Autor: <NAME> Start data: 15th May 2016 purpose: of this file is read frame level predictions and process them to produce a label per video #######baseDir = "/mnt/sun-alpha/actnet/"; #baseDir = "/mnt/solar-machines/actnet/"; ########imgDir = "/mnt/sun-alpha/actnet/rgb-images/"; ######## imgDir = "/mnt/DATADISK2/ss-work... | 2.373774 | 2 |
python/csv/csv_dict_writer.py | y2ghost/study | 0 | 4279 | <filename>python/csv/csv_dict_writer.py
import csv
def csv_dict_writer(path, headers, data):
with open(path, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, delimiter=',',
fieldnames=headers)
writer.writeheader()
for record in data:
... | <filename>python/csv/csv_dict_writer.py
import csv
def csv_dict_writer(path, headers, data):
with open(path, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, delimiter=',',
fieldnames=headers)
writer.writeheader()
for record in data:
... | en | 0.471699 | book_title,author,publisher,pub_date,isbn Python 101,<NAME>, <NAME>,2020,123456789 wxPython Recipes,<NAME>,Apress,2018,978-1-4842-3237-8 Python Interviews,<NAME>,Packt Publishing,2018,9781788399081 | 3.886508 | 4 |
src/decisionengine/framework/modules/tests/test_module_decorators.py | moibenko/decisionengine | 9 | 4280 | <gh_stars>1-10
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import pytest
from decisionengine.framework.modules import Publisher, Source
from decisionengine.framework.modules.Module import verify_products
from decisionengine.framework.modules.Source import Paramete... | # SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import pytest
from decisionengine.framework.modules import Publisher, Source
from decisionengine.framework.modules.Module import verify_products
from decisionengine.framework.modules.Source import Parameter
def test_mu... | en | 0.320026 | # SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC # SPDX-License-Identifier: Apache-2.0 | 2.118434 | 2 |
models/cnn_layer.py | RobinRojowiec/intent-recognition-in-doctor-patient-interviews | 0 | 4281 | import torch
import torch.nn as nn
from torch.nn.functional import max_pool1d
from utility.model_parameter import Configuration, ModelParameter
class CNNLayer(nn.Module):
def __init__(self, config: Configuration, vocab_size=30000, use_embeddings=True, embed_dim=-1, **kwargs):
super(CNNLayer, self).__init... | import torch
import torch.nn as nn
from torch.nn.functional import max_pool1d
from utility.model_parameter import Configuration, ModelParameter
class CNNLayer(nn.Module):
def __init__(self, config: Configuration, vocab_size=30000, use_embeddings=True, embed_dim=-1, **kwargs):
super(CNNLayer, self).__init... | en | 0.114613 | # set parameters # create and initialize layers | 2.687333 | 3 |
musicscore/musicxml/types/complextypes/backup.py | alexgorji/music_score | 2 | 4282 | '''
<xs:complexType name="backup">
<xs:annotation>
<xs:documentation></xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:group ref="duration"/>
<xs:group ref="editorial"/>
</xs:sequence>
</xs:complexType>
'''
from musicscore.dtd.dtd import Sequence, GroupReference, Element
from musicscore.musicxml... | '''
<xs:complexType name="backup">
<xs:annotation>
<xs:documentation></xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:group ref="duration"/>
<xs:group ref="editorial"/>
</xs:sequence>
</xs:complexType>
'''
from musicscore.dtd.dtd import Sequence, GroupReference, Element
from musicscore.musicxml... | en | 0.795439 | <xs:complexType name="backup"> <xs:annotation> <xs:documentation></xs:documentation> </xs:annotation> <xs:sequence> <xs:group ref="duration"/> <xs:group ref="editorial"/> </xs:sequence> </xs:complexType> The backup and forward elements are required to coordinate multiple voices in one part, including ... | 2.072199 | 2 |
NLP programmes in Python/9.Text Clustering/kmeans.py | AlexandrosPlessias/NLP-Greek-Presentations | 0 | 4283 | <filename>NLP programmes in Python/9.Text Clustering/kmeans.py
import nltk
import re
import csv
import string
import collections
import numpy as np
from nltk.corpus import wordnet
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import WordPunctTokenizer
from sk... | <filename>NLP programmes in Python/9.Text Clustering/kmeans.py
import nltk
import re
import csv
import string
import collections
import numpy as np
from nltk.corpus import wordnet
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import WordPunctTokenizer
from sk... | en | 0.705207 | "Pre - Processing: tokenization, stopwords removal, remove words(with size 1), lower capitalization & lemmatization # text = text.decode("utf8") # remove punctuation # remove extra spaces # tokenize into words # remove number # remove stopwords # remove words less than three letters # lower capitalization # keep only ... | 3.583856 | 4 |
common/utils.py | paTRICK-swk/P-STMO | 8 | 4284 | import torch
import numpy as np
import hashlib
from torch.autograd import Variable
import os
def deterministic_random(min_value, max_value, data):
digest = hashlib.sha256(data.encode()).digest()
raw_value = int.from_bytes(digest[:4], byteorder='little', signed=False)
return int(raw_value / (2 ** 32 - 1... | import torch
import numpy as np
import hashlib
from torch.autograd import Variable
import os
def deterministic_random(min_value, max_value, data):
digest = hashlib.sha256(data.encode()).digest()
raw_value = int.from_bytes(digest[:4], byteorder='little', signed=False)
return int(raw_value / (2 ** 32 - 1... | en | 0.331425 | #1 mm", "p#2 mm")) # if os.path.exists(previous_name): # os.remove(previous_name) # if os.path.exists(previous_name): # os.remove(previous_name) # torch.save(model.state_dict(), # '%s/%s_%d_%d.pth' % (save_dir, model_name, epoch, data_threshold * 100)) | 2.12669 | 2 |
personal_ad/advice/converter.py | Sailer43/CSE5914Project | 0 | 4285 | <gh_stars>0
from ibm_watson import TextToSpeechV1, SpeechToTextV1, DetailedResponse
from os import system
from json import loads
class Converter:
k_s2t_api_key = "<KEY>"
k_t2s_api_key = "<KEY>"
k_s2t_url = "https://stream.watsonplatform.net/speech-to-text/api"
k_t2s_url = "https://gateway-wdc.watson... | from ibm_watson import TextToSpeechV1, SpeechToTextV1, DetailedResponse
from os import system
from json import loads
class Converter:
k_s2t_api_key = "<KEY>"
k_t2s_api_key = "<KEY>"
k_s2t_url = "https://stream.watsonplatform.net/speech-to-text/api"
k_t2s_url = "https://gateway-wdc.watsonplatform.net... | none | 1 | 3.112962 | 3 | |
warg_client/client/apis/controller/attack_controller.py | neel4os/warg-client | 0 | 4286 | <gh_stars>0
from subprocess import run
def perform_shutdown(body):
arg = ""
if body["reboot"]:
_is_reboot = arg + "-r"
else:
_is_reboot = arg + "-h"
time_to_shutdown = str(body['timeToShutdown'])
result = run(["/sbin/shutdown", _is_reboot, time_to_shutdown])
return body
| from subprocess import run
def perform_shutdown(body):
arg = ""
if body["reboot"]:
_is_reboot = arg + "-r"
else:
_is_reboot = arg + "-h"
time_to_shutdown = str(body['timeToShutdown'])
result = run(["/sbin/shutdown", _is_reboot, time_to_shutdown])
return body | none | 1 | 2.671659 | 3 | |
torrents/migrations/0011_auto_20190223_2345.py | 2600box/harvest | 9 | 4287 | <reponame>2600box/harvest<filename>torrents/migrations/0011_auto_20190223_2345.py
# Generated by Django 2.1.7 on 2019-02-23 23:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('torrents', '0010_auto_20190223_0326'),
]
operations = [
migrations... | # Generated by Django 2.1.7 on 2019-02-23 23:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('torrents', '0010_auto_20190223_0326'),
]
operations = [
migrations.AlterModelOptions(
name='realm',
options={'ordering': ('n... | en | 0.771902 | # Generated by Django 2.1.7 on 2019-02-23 23:45 | 1.3865 | 1 |
common/__init__.py | whyh/FavourDemo | 1 | 4288 | <filename>common/__init__.py
from . import (emoji as emj,
keyboards as kb,
telegram as tg,
phrases as phr,
finance as fin,
utils,
glossary,
bots,
gcp,
sed,
db)
| <filename>common/__init__.py
from . import (emoji as emj,
keyboards as kb,
telegram as tg,
phrases as phr,
finance as fin,
utils,
glossary,
bots,
gcp,
sed,
db)
| none | 1 | 1.230882 | 1 | |
questions/serializers.py | aneumeier/questions | 0 | 4289 | <filename>questions/serializers.py
#!/usr/bin/env python
# -*- coding: utf-8
"""
:mod:`question.serializers` -- serializers
"""
from rest_framework import serializers
from .models import Question, PossibleAnswer
from category.models import Category
class PossibleAnswerSerializer(serializers.ModelSerializer):
cl... | <filename>questions/serializers.py
#!/usr/bin/env python
# -*- coding: utf-8
"""
:mod:`question.serializers` -- serializers
"""
from rest_framework import serializers
from .models import Question, PossibleAnswer
from category.models import Category
class PossibleAnswerSerializer(serializers.ModelSerializer):
cl... | en | 0.223661 | #!/usr/bin/env python # -*- coding: utf-8 :mod:`question.serializers` -- serializers {{ category.question_set.count }} | 2.594499 | 3 |
widgets/ui_ShowResultDialog.py | JaySon-Huang/SecertPhotos | 0 | 4290 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'src/ui_ShowResultDialog.ui'
#
# Created: Sat May 16 17:05:43 2015
# by: PyQt5 UI code generator 5.4
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def s... | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'src/ui_ShowResultDialog.ui'
#
# Created: Sat May 16 17:05:43 2015
# by: PyQt5 UI code generator 5.4
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def s... | en | 0.797163 | # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'src/ui_ShowResultDialog.ui' # # Created: Sat May 16 17:05:43 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! | 1.665875 | 2 |
mixcoatl/admin/api_key.py | zomGreg/mixcoatl | 0 | 4291 | <gh_stars>0
"""
mixcoatl.admin.api_key
----------------------
Implements access to the DCM ApiKey API
"""
from mixcoatl.resource import Resource
from mixcoatl.decorators.lazy import lazy_property
from mixcoatl.decorators.validations import required_attrs
from mixcoatl.utils import uncamel, camelize, camel_keys, uncame... | """
mixcoatl.admin.api_key
----------------------
Implements access to the DCM ApiKey API
"""
from mixcoatl.resource import Resource
from mixcoatl.decorators.lazy import lazy_property
from mixcoatl.decorators.validations import required_attrs
from mixcoatl.utils import uncamel, camelize, camel_keys, uncamel_keys
impor... | en | 0.619605 | mixcoatl.admin.api_key ---------------------- Implements access to the DCM ApiKey API An API key is an access key and secret key that provide API access into DCM. The primary identifier of the `ApiKey`. Same as `DCM_ACCESS_KEY` `dict` - The account with which this API key is associated. `str` - The date and time when ... | 2.268317 | 2 |
Python tests/dictionaries.py | Johnny-QA/Python_training | 0 | 4292 | <reponame>Johnny-QA/Python_training<filename>Python tests/dictionaries.py
my_set = {1, 3, 5}
my_dict = {'name': 'Jose', 'age': 90}
another_dict = {1: 15, 2: 75, 3: 150}
lottery_players = [
{
'name': 'Rolf',
'numbers': (13, 45, 66, 23, 22)
},
{
'name': 'John',
'numbers': (14,... | tests/dictionaries.py
my_set = {1, 3, 5}
my_dict = {'name': 'Jose', 'age': 90}
another_dict = {1: 15, 2: 75, 3: 150}
lottery_players = [
{
'name': 'Rolf',
'numbers': (13, 45, 66, 23, 22)
},
{
'name': 'John',
'numbers': (14, 56, 80, 23, 22)
}
]
universities = [
{
... | none | 1 | 2.458917 | 2 | |
psdaq/psdaq/control_gui/QWTable.py | ZhenghengLi/lcls2 | 16 | 4293 | <reponame>ZhenghengLi/lcls2
"""Class :py:class:`QWTable` is a QTableView->QWidget for tree model
======================================================================
Usage ::
# Run test: python lcls2/psdaq/psdaq/control_gui/QWTable.py
from psdaq.control_gui.QWTable import QWTable
w = QWTable()
Create... | """Class :py:class:`QWTable` is a QTableView->QWidget for tree model
======================================================================
Usage ::
# Run test: python lcls2/psdaq/psdaq/control_gui/QWTable.py
from psdaq.control_gui.QWTable import QWTable
w = QWTable()
Created on 2019-03-28 by <NAME>
Re-... | en | 0.385414 | Class :py:class:`QWTable` is a QTableView->QWidget for tree model ====================================================================== Usage :: # Run test: python lcls2/psdaq/psdaq/control_gui/QWTable.py from psdaq.control_gui.QWTable import QWTable w = QWTable() Created on 2019-03-28 by <NAME> Re-des... | 2.263892 | 2 |
src/grailbase/mtloader.py | vadmium/grailbrowser | 9 | 4294 | """Extension loader for filetype handlers.
The extension objects provided by MIMEExtensionLoader objects have four
attributes: parse, embed, add_options, and update_options. The first two
are used as handlers for supporting the MIME type as primary and embeded
resources. The last two are (currently) only used for pr... | """Extension loader for filetype handlers.
The extension objects provided by MIMEExtensionLoader objects have four
attributes: parse, embed, add_options, and update_options. The first two
are used as handlers for supporting the MIME type as primary and embeded
resources. The last two are (currently) only used for pr... | en | 0.92939 | Extension loader for filetype handlers. The extension objects provided by MIMEExtensionLoader objects have four attributes: parse, embed, add_options, and update_options. The first two are used as handlers for supporting the MIME type as primary and embeded resources. The last two are (currently) only used for print... | 2.483741 | 2 |
eventstreams_sdk/adminrest_v1.py | IBM/eventstreams-python-sdk | 2 | 4295 | <gh_stars>1-10
# coding: utf-8
# (C) Copyright IBM Corp. 2021.
#
# 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 appl... | # coding: utf-8
# (C) Copyright IBM Corp. 2021.
#
# 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 a... | en | 0.612737 | # coding: utf-8 # (C) Copyright IBM Corp. 2021. # # 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 ag... | 1.765333 | 2 |
3-functions/pytest-exercises/test_functions.py | BaseCampCoding/python-fundamentals | 0 | 4296 | <filename>3-functions/pytest-exercises/test_functions.py
import functions
from pytest import approx
from bcca.test import should_print
def test_add_em_up():
assert functions.add_em_up(1, 2, 3) == 6
assert functions.add_em_up(4, 5, 6) == 15
def test_sub_sub_hubbub():
assert functions.sub_sub_hubbub(1, 2,... | <filename>3-functions/pytest-exercises/test_functions.py
import functions
from pytest import approx
from bcca.test import should_print
def test_add_em_up():
assert functions.add_em_up(1, 2, 3) == 6
assert functions.add_em_up(4, 5, 6) == 15
def test_sub_sub_hubbub():
assert functions.sub_sub_hubbub(1, 2,... | en | 0.624152 | Purchase Amount: 1 State Sales Tax: 0.04 County Sales Tax: 0.02 Total Sales Tax: 0.06 Total Cost: 1.06 Purchase Amount: 99.99 State Sales Tax: 3.9996 County Sales Tax: 1.9998 Total Sales Tax: 5.9994 Total Cost: 105.98939999999999 Purchase Amount: 5.95 State Sales Tax: 0.23800000000000002 County Sales Tax: 0.11900000000... | 3.44851 | 3 |
src/products/admin.py | apabaad/django_ecommerce | 0 | 4297 | <reponame>apabaad/django_ecommerce
from django.contrib import admin
from .models import Product
admin.site.register(Product) | from django.contrib import admin
from .models import Product
admin.site.register(Product) | none | 1 | 1.20634 | 1 | |
cio/plugins/txt.py | beshrkayali/content-io | 6 | 4298 | <reponame>beshrkayali/content-io
# coding=utf-8
from __future__ import unicode_literals
from .base import BasePlugin
class TextPlugin(BasePlugin):
ext = 'txt'
| # coding=utf-8
from __future__ import unicode_literals
from .base import BasePlugin
class TextPlugin(BasePlugin):
ext = 'txt' | en | 0.644078 | # coding=utf-8 | 1.356241 | 1 |
ml-scripts/dump-data-to-learn.py | thejoeejoee/SUI-MIT-VUT-2020-2021 | 0 | 4299 | #!/usr/bin/env python3
# Project: VUT FIT SUI Project - Dice Wars
# Authors:
# - <NAME> <<EMAIL>>
# - <NAME> <<EMAIL>>
# - <NAME> <<EMAIL>>
# - <NAME> <<EMAIL>>
# Year: 2020
# Description: Generates game configurations.
import random
import sys
from argparse import ArgumentParser
import time
from... | #!/usr/bin/env python3
# Project: VUT FIT SUI Project - Dice Wars
# Authors:
# - <NAME> <<EMAIL>>
# - <NAME> <<EMAIL>>
# - <NAME> <<EMAIL>>
# - <NAME> <<EMAIL>>
# Year: 2020
# Description: Generates game configurations.
import random
import sys
from argparse import ArgumentParser
import time
from... | en | 0.362661 | #!/usr/bin/env python3 # Project: VUT FIT SUI Project - Dice Wars # Authors: # - <NAME> <<EMAIL>> # - <NAME> <<EMAIL>> # - <NAME> <<EMAIL>> # - <NAME> <<EMAIL>> # Year: 2020 # Description: Generates game configurations. Handler for SIGCHLD signal that terminates server and clients. | 2.398588 | 2 |