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 |
|---|---|---|---|---|---|---|---|---|---|---|
third_party/logging.py | sweeneyb/iot-core-micropython | 50 | 9600 | # MIT License
#
# Copyright (c) 2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pub... | # MIT License
#
# Copyright (c) 2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pub... | en | 0.765671 | # MIT License # # Copyright (c) 2019 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publi... | 1.99221 | 2 |
assessments/migrations/0003_auto_20210212_1943.py | acounsel/django_msat | 0 | 9601 | # Generated by Django 3.1.6 on 2021-02-12 19:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assessments', '0002_auto_20210212_1904'),
]
operations = [
migrations.AlterField(
model_name='country',
name='region... | # Generated by Django 3.1.6 on 2021-02-12 19:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assessments', '0002_auto_20210212_1904'),
]
operations = [
migrations.AlterField(
model_name='country',
name='region... | en | 0.814238 | # Generated by Django 3.1.6 on 2021-02-12 19:43 | 1.632256 | 2 |
noxfile.py | sethmlarson/workplace-search-python | 5 | 9602 | <gh_stars>1-10
import nox
SOURCE_FILES = (
"setup.py",
"noxfile.py",
"elastic_workplace_search/",
"tests/",
)
@nox.session(python=["2.7", "3.4", "3.5", "3.6", "3.7", "3.8"])
def test(session):
session.install(".")
session.install("-r", "dev-requirements.txt")
session.run("pytest", "--re... | import nox
SOURCE_FILES = (
"setup.py",
"noxfile.py",
"elastic_workplace_search/",
"tests/",
)
@nox.session(python=["2.7", "3.4", "3.5", "3.6", "3.7", "3.8"])
def test(session):
session.install(".")
session.install("-r", "dev-requirements.txt")
session.run("pytest", "--record-mode=none"... | none | 1 | 1.737421 | 2 | |
komodo2_rl/src/environments/Spawner.py | osheraz/komodo | 5 | 9603 | <reponame>osheraz/komodo
# !/usr/bin/env python
import rospy
import numpy as np
from gazebo_msgs.srv import SpawnModel, SpawnModelRequest, SpawnModelResponse
from copy import deepcopy
from tf.transformations import quaternion_from_euler
sdf_cube = """<?xml version="1.0" ?>
<sdf version="1.4">
<model name="MODELNAM... | # !/usr/bin/env python
import rospy
import numpy as np
from gazebo_msgs.srv import SpawnModel, SpawnModelRequest, SpawnModelResponse
from copy import deepcopy
from tf.transformations import quaternion_from_euler
sdf_cube = """<?xml version="1.0" ?>
<sdf version="1.4">
<model name="MODELNAME">
<static>0</static... | en | 0.264585 | # !/usr/bin/env python <?xml version="1.0" ?> <sdf version="1.4"> <model name="MODELNAME"> <static>0</static> <link name="link"> <inertial> <mass>1.0</mass> <inertia> <ixx>0.01</ixx> <ixy>0.0</ixy> <ixz>0.0</ixz> <iyy>0.01</iyy> <iyz>0.0<... | 2.124403 | 2 |
output/models/ms_data/regex/re_l32_xsd/__init__.py | tefra/xsdata-w3c-tests | 1 | 9604 | <reponame>tefra/xsdata-w3c-tests<filename>output/models/ms_data/regex/re_l32_xsd/__init__.py<gh_stars>1-10
from output.models.ms_data.regex.re_l32_xsd.re_l32 import (
Regex,
Doc,
)
__all__ = [
"Regex",
"Doc",
]
| from output.models.ms_data.regex.re_l32_xsd.re_l32 import (
Regex,
Doc,
)
__all__ = [
"Regex",
"Doc",
] | none | 1 | 1.101199 | 1 | |
sdk/python/tests/dsl/metadata_tests.py | ConverJens/pipelines | 6 | 9605 | <reponame>ConverJens/pipelines
# Copyright 2018 Google LLC
#
# 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 applicabl... | # Copyright 2018 Google LLC
#
# 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.85377 | # Copyright 2018 Google LLC # # 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, ... | 1.867314 | 2 |
challenges/python-solutions/day-25.py | elifloresch/thirty-days-challenge | 0 | 9606 | <gh_stars>0
import math
def is_prime_number(number):
if number < 2:
return False
if number == 2 or number == 3:
return True
if number % 2 == 0 or number % 3 == 0:
return False
number_sqrt = math.sqrt(number)
int_number_sqrt = int(number_sqrt) + 1
for d in range(6, i... | import math
def is_prime_number(number):
if number < 2:
return False
if number == 2 or number == 3:
return True
if number % 2 == 0 or number % 3 == 0:
return False
number_sqrt = math.sqrt(number)
int_number_sqrt = int(number_sqrt) + 1
for d in range(6, int_number_sq... | none | 1 | 4.036832 | 4 | |
examples/path_config.py | rnixx/garden.cefpython | 13 | 9607 | <reponame>rnixx/garden.cefpython
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Minimal example of the CEFBrowser widget use. Here you don't have any controls
(back / forth / reload) or whatsoever. Just a kivy app displaying the
chromium-webview.
In this example we demonstrate how the cache path of CEF can be set.
... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Minimal example of the CEFBrowser widget use. Here you don't have any controls
(back / forth / reload) or whatsoever. Just a kivy app displaying the
chromium-webview.
In this example we demonstrate how the cache path of CEF can be set.
"""
import os
from kivy.app im... | en | 0.375754 | #!/usr/bin/env python # -*- coding: UTF-8 -*- Minimal example of the CEFBrowser widget use. Here you don't have any controls (back / forth / reload) or whatsoever. Just a kivy app displaying the chromium-webview. In this example we demonstrate how the cache path of CEF can be set. # Set runtime data paths # CEFBrowser.... | 2.650842 | 3 |
simple-systems/and_xor_shift.py | laserbat/random-projects | 3 | 9608 | #!/usr/bin/python3
# If F(a) is any function that can be defined as composition of bitwise XORs, ANDs and left shifts
# Then the dynac system x_(n+1) = F(x_n) is Turing complete
# Proof by simulation (rule110)
a = 1
while a:
print(bin(a))
a = a ^ (a << 1) ^ (a & (a << 1)) ^ (a & (a << 1) & (a << 2))
| #!/usr/bin/python3
# If F(a) is any function that can be defined as composition of bitwise XORs, ANDs and left shifts
# Then the dynac system x_(n+1) = F(x_n) is Turing complete
# Proof by simulation (rule110)
a = 1
while a:
print(bin(a))
a = a ^ (a << 1) ^ (a & (a << 1)) ^ (a & (a << 1) & (a << 2))
| en | 0.847879 | #!/usr/bin/python3 # If F(a) is any function that can be defined as composition of bitwise XORs, ANDs and left shifts # Then the dynac system x_(n+1) = F(x_n) is Turing complete # Proof by simulation (rule110) | 3.342913 | 3 |
trinity/protocol/common/peer_pool_event_bus.py | Gauddel/trinity | 0 | 9609 | from abc import (
abstractmethod,
)
from typing import (
Any,
Callable,
cast,
FrozenSet,
Generic,
Type,
TypeVar,
)
from cancel_token import (
CancelToken,
)
from p2p.exceptions import (
PeerConnectionLost,
)
from p2p.kademlia import Node
from p2p.peer import (
BasePeer,
... | from abc import (
abstractmethod,
)
from typing import (
Any,
Callable,
cast,
FrozenSet,
Generic,
Type,
TypeVar,
)
from cancel_token import (
CancelToken,
)
from p2p.exceptions import (
PeerConnectionLost,
)
from p2p.kademlia import Node
from p2p.peer import (
BasePeer,
... | en | 0.879236 | Base class to create a bridge between the ``PeerPool`` and the event bus so that peer messages become available to external processes (e.g. isolated plugins). In the opposite direction, other processes can also retrieve information or execute actions on the peer pool by sending specific events through the e... | 2.195026 | 2 |
tests/e2e/performance/csi_tests/test_pvc_creation_deletion_performance.py | annagitel/ocs-ci | 1 | 9610 | <gh_stars>1-10
"""
Test to verify performance of PVC creation and deletion
for RBD, CephFS and RBD-Thick interfaces
"""
import time
import logging
import datetime
import pytest
import ocs_ci.ocs.exceptions as ex
import threading
import statistics
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
... | """
Test to verify performance of PVC creation and deletion
for RBD, CephFS and RBD-Thick interfaces
"""
import time
import logging
import datetime
import pytest
import ocs_ci.ocs.exceptions as ex
import threading
import statistics
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
from ocs_ci.fr... | en | 0.884599 | Test to verify performance of PVC creation and deletion for RBD, CephFS and RBD-Thick interfaces This class generates results for all tests as one unit and saves them to an elastic search server on the cluster Initialize the object by reading some of the data from the CRD file and by connecting to the ES se... | 2.358282 | 2 |
templates/t/searchresult_withnone.py | MikeBirdsall/food-log | 0 | 9611 | <reponame>MikeBirdsall/food-log
#!/usr/bin/python3
from jinja2 import Environment, FileSystemLoader
def spacenone(value):
return "" if value is None else str(value)
results = [
dict(
description="Noodles and Company steak Stromboli",
comment="",
size="small",
cals=530,
... | #!/usr/bin/python3
from jinja2 import Environment, FileSystemLoader
def spacenone(value):
return "" if value is None else str(value)
results = [
dict(
description="Noodles and Company steak Stromboli",
comment="",
size="small",
cals=530,
carbs=50,
fat=25,
... | fr | 0.386793 | #!/usr/bin/python3 | 2.713311 | 3 |
payments/views.py | aman-roy/pune.pycon.org | 0 | 9612 | from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from payments.models import Invoice, RazorpayKeys
from payments.razorpay.razorpay_payments import RazorpayPayments
from payments.models import Payment, Order
import json
@csrf_exempt
def webhook(request):
if request.method ... | from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from payments.models import Invoice, RazorpayKeys
from payments.razorpay.razorpay_payments import RazorpayPayments
from payments.models import Payment, Order
import json
@csrf_exempt
def webhook(request):
if request.method ... | none | 1 | 2.02555 | 2 | |
src/convnet/image_classifier.py | danschef/gear-detector | 1 | 9613 | import configparser
import os
import sys
from time import localtime, strftime, mktime
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from net import Net
from geo_helper import store_image_bounds
from image_helper import CLASSES
from image_helper import save_image
f... | import configparser
import os
import sys
from time import localtime, strftime, mktime
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from net import Net
from geo_helper import store_image_bounds
from image_helper import CLASSES
from image_helper import save_image
f... | de | 0.46219 | ########################################### # Training Stage ########################################### ########################################### # Loss Function ########################################### # loop over the dataset multiple times # Wrap images and labels into Variables # Clear all accumulated gradient... | 2.214759 | 2 |
src/modules/AlphabetPlotter.py | aaanh/duplicated_accelcamp | 0 | 9614 | import tkinter as tk
from tkinter import filedialog
import csv
import matplotlib.pyplot as plt
root = tk.Tk(screenName=':0.0')
root.withdraw()
file_path = filedialog.askopenfilename()
lastIndex = len(file_path.split('/')) - 1
v0 = [0, 0, 0]
x0 = [0, 0, 0]
fToA = 1
error = 0.28
errorZ = 3
t = []
time... | import tkinter as tk
from tkinter import filedialog
import csv
import matplotlib.pyplot as plt
root = tk.Tk(screenName=':0.0')
root.withdraw()
file_path = filedialog.askopenfilename()
lastIndex = len(file_path.split('/')) - 1
v0 = [0, 0, 0]
x0 = [0, 0, 0]
fToA = 1
error = 0.28
errorZ = 3
t = []
time... | en | 0.388809 | # For when the data starts at (2,1) # For when the data starts at (0,0) # For when the data starts at (1,0) # Translates Data into Position axs[2].scatter(time, acceleration[2])
axs[2].set_xlabel('Time (s)')
axs[2].set_ylabel('AccelerationZ (m/s^2)')
axs[3].scatter(time, velocity[2])
axs[3].set_xlabel('Time (s)')
... | 3.236343 | 3 |
users/migrations/0008_profile_fields_optional.py | mitodl/mit-xpro | 10 | 9615 | # Generated by Django 2.2.3 on 2019-07-15 19:24
from django.db import migrations, models
def backpopulate_incomplete_profiles(apps, schema):
"""Backpopulate users who don't have a profile record"""
User = apps.get_model("users", "User")
Profile = apps.get_model("users", "Profile")
for user in User.o... | # Generated by Django 2.2.3 on 2019-07-15 19:24
from django.db import migrations, models
def backpopulate_incomplete_profiles(apps, schema):
"""Backpopulate users who don't have a profile record"""
User = apps.get_model("users", "User")
Profile = apps.get_model("users", "Profile")
for user in User.o... | en | 0.894545 | # Generated by Django 2.2.3 on 2019-07-15 19:24 Backpopulate users who don't have a profile record Delete records that will cause rollbacks on nullable/blankable fields to fail | 2.490112 | 2 |
test/unit_testing/grid/element_linear_dx_data/test_element_linearC/element/geom_element_AD.py | nwukie/ChiDG | 36 | 9616 | from __future__ import division
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import sys
import os
import time
#
# TORCH INSTALLATION: refer to https://pytorch.org/get-started/locally/
#
def update_progress(job_t... | from __future__ import division
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import sys
import os
import time
#
# TORCH INSTALLATION: refer to https://pytorch.org/get-started/locally/
#
def update_progress(job_t... | en | 0.49498 | # # TORCH INSTALLATION: refer to https://pytorch.org/get-started/locally/ # # modify this to change the length ################################################################################################################ # Initialize torch tensor for coordiantes # Define matrix of polynomial basis terms at support n... | 2.447817 | 2 |
osr_stat_generator/generator.py | brian-thomas/osr_stat_generator | 0 | 9617 |
"""
OSR (LOTFP) stat generator.
"""
import random
def d(num_sides):
"""
Represents rolling a die of size 'num_sides'.
Returns random number from that size die
"""
return random.randint(1, num_sides)
def xdy(num_dice, num_sides):
""" represents rolling num_dice of size num_sides.
Re... |
"""
OSR (LOTFP) stat generator.
"""
import random
def d(num_sides):
"""
Represents rolling a die of size 'num_sides'.
Returns random number from that size die
"""
return random.randint(1, num_sides)
def xdy(num_dice, num_sides):
""" represents rolling num_dice of size num_sides.
Re... | en | 0.776505 | OSR (LOTFP) stat generator. Represents rolling a die of size 'num_sides'. Returns random number from that size die represents rolling num_dice of size num_sides. Returns random number from that many dice being 'rolled'. # the default Define a package of OSR/DnD stats # get a summed value for all stats in this ... | 3.518759 | 4 |
cohesity_management_sdk/models/health_tile.py | nick6655/management-sdk-python | 18 | 9618 | # -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import cohesity_management_sdk.models.alert
class HealthTile(object):
"""Implementation of the 'HealthTile' model.
Health for Dashboard.
Attributes:
capacity_bytes (long|int): Raw Cluster Capacity in Bytes. This is not
usable ca... | # -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import cohesity_management_sdk.models.alert
class HealthTile(object):
"""Implementation of the 'HealthTile' model.
Health for Dashboard.
Attributes:
capacity_bytes (long|int): Raw Cluster Capacity in Bytes. This is not
usable ca... | en | 0.796961 | # -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. Implementation of the 'HealthTile' model. Health for Dashboard. Attributes: capacity_bytes (long|int): Raw Cluster Capacity in Bytes. This is not usable capacity and does not take replication factor into account. cl... | 2.294908 | 2 |
TextRank/textrank.py | nihanjali/PageRank | 0 | 9619 | <reponame>nihanjali/PageRank<gh_stars>0
import os
import sys
import copy
import collections
import nltk
import nltk.tokenize
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
import pagerank
'''
textrank.py
-----------
This module implements TextRank, an unsupervised keyword
significa... | import os
import sys
import copy
import collections
import nltk
import nltk.tokenize
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
import pagerank
'''
textrank.py
-----------
This module implements TextRank, an unsupervised keyword
significance scoring algorithm. TextRank builds a... | en | 0.737872 | textrank.py ----------- This module implements TextRank, an unsupervised keyword significance scoring algorithm. TextRank builds a weighted graph representation of a document using words as nodes and coocurrence frequencies between pairs of words as edge weights. It then applies PageRank to thi... | 3.085036 | 3 |
tests/test_exploration.py | lionelkusch/neurolib | 0 | 9620 | import logging
import os
import random
import string
import time
import unittest
import neurolib.utils.paths as paths
import neurolib.utils.pypetUtils as pu
import numpy as np
import pytest
import xarray as xr
from neurolib.models.aln import ALNModel
from neurolib.models.fhn import FHNModel
from neurolib.models.multim... | import logging
import os
import random
import string
import time
import unittest
import neurolib.utils.paths as paths
import neurolib.utils.pypetUtils as pu
import numpy as np
import pytest
import xarray as xr
from neurolib.models.aln import ALNModel
from neurolib.models.fhn import FHNModel
from neurolib.models.multim... | en | 0.693056 | Generate a random string of fixed length Basic tests. ALN single node exploration. FHN brain network simulation with BOLD simulation. # ms # firing rate xr # bold xr ALN brain network simulation with custom evaluation function. # def test_brain_network_postprocessing(self): # Resting state fits # multi stage evaluation... | 2.179502 | 2 |
irc3/tags.py | belst/irc3 | 0 | 9621 | <reponame>belst/irc3
# -*- coding: utf-8 -*-
'''
Module offering 2 functions, encode() and decode(), to transcode between
IRCv3.2 tags and python dictionaries.
'''
import re
import random
import string
_escapes = (
("\\", "\\\\"),
(";", r"\:"),
(" ", r"\s"),
("\r", r"\r"),
("\n", r"\n"),
)
# ma... | # -*- coding: utf-8 -*-
'''
Module offering 2 functions, encode() and decode(), to transcode between
IRCv3.2 tags and python dictionaries.
'''
import re
import random
import string
_escapes = (
("\\", "\\\\"),
(";", r"\:"),
(" ", r"\s"),
("\r", r"\r"),
("\n", r"\n"),
)
# make the possibility of... | en | 0.520902 | # -*- coding: utf-8 -*- Module offering 2 functions, encode() and decode(), to transcode between IRCv3.2 tags and python dictionaries. # make the possibility of the substitute actually appearing in the text # negligible. Even for targeted attacks # valid tag-keys must contain of alphanumerics and hyphens only. # for ve... | 3.060029 | 3 |
app/forms.py | Rahmatullina/FinalYearProject | 0 | 9622 | from django import forms
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
# from .models import RegionModel
# from .models import SERVICE_CHOICES, REGION_CHOICES
from django.contrib.auth import authenticate
# from django.contrib.auth.forms import UserCreationForm, UserChangeForm
# from .models i... | from django import forms
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
# from .models import RegionModel
# from .models import SERVICE_CHOICES, REGION_CHOICES
from django.contrib.auth import authenticate
# from django.contrib.auth.forms import UserCreationForm, UserChangeForm
# from .models i... | en | 0.480036 | # from .models import RegionModel # from .models import SERVICE_CHOICES, REGION_CHOICES # from django.contrib.auth.forms import UserCreationForm, UserChangeForm # from .models import CustomUser # class PassResetForm(PasswordResetForm): # email = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control',... | 2.455655 | 2 |
src/fedavg_trainer.py | MrZhang1994/mobile-federated-learning | 0 | 9623 | # newly added libraries
import copy
import wandb
import time
import math
import csv
import shutil
from tqdm import tqdm
import torch
import numpy as np
import pandas as pd
from client import Client
from config import *
import scheduler as sch
class FedAvgTrainer(object):
def __init__(self, dataset, model, device... | # newly added libraries
import copy
import wandb
import time
import math
import csv
import shutil
from tqdm import tqdm
import torch
import numpy as np
import pandas as pd
from client import Client
from config import *
import scheduler as sch
class FedAvgTrainer(object):
def __init__(self, dataset, model, device... | en | 0.687573 | # newly added libraries # record the client number of the dataset # setup dataset # generate the non i.i.d dataset # read the non i.i.d dataset # rm the tmp directory # initialize the recorder of invalid dataset # time counter starts from the first line # initialize the cycle_num here # initialize the scheduler functio... | 2.189646 | 2 |
src/test.py | jfparentledartech/DEFT | 0 | 9624 | <reponame>jfparentledartech/DEFT
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import cv2
import matplotlib.pyplot as plt
import numpy as np
from progress.bar import Bar
import torch
import pickle
import motmetrics as mm
from lib.op... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import cv2
import matplotlib.pyplot as plt
import numpy as np
from progress.bar import Bar
import torch
import pickle
import motmetrics as mm
from lib.opts import opts
from lib.logger im... | en | 0.387302 | # # print('dataset -> ', opt.dataset) # print('lstm -> ', opt.lstm) # print(f'saved {filename}') # with open(filename, 'rb') as f: # opt = pickle.load(f) # print('use pixell ->', opt.use_pixell) # TODO remove # split = "val" if not opt.trainval else "test" # split = "val" # "attribute_name": att, # opt ... | 2.094558 | 2 |
compiler_gym/envs/gcc/datasets/csmith.py | AkillesAILimited/CompilerGym | 0 | 9625 | <reponame>AkillesAILimited/CompilerGym
# 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 logging
import shutil
import subprocess
import tempfile
from pathlib import Path
from threading i... | # 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 logging
import shutil
import subprocess
import tempfile
from pathlib import Path
from threading import Lock
from typing import Iterable,... | en | 0.797456 | # 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. # The maximum value for the --seed argument to csmith. # TODO(github.com/facebookresearch/CompilerGym/issues/325): This can be merged # with th... | 1.729529 | 2 |
dans_pymodules/power_of_two.py | DanielWinklehner/dans_pymodules | 0 | 9626 | <reponame>DanielWinklehner/dans_pymodules
__author__ = "<NAME>"
__doc__ = "Find out if a number is a power of two"
def power_of_two(number):
"""
Function that checks if the input value (data) is a power of 2
(i.e. 2, 4, 8, 16, 32, ...)
"""
res = 0
while res == 0:
res = number % 2
... | __author__ = "<NAME>"
__doc__ = "Find out if a number is a power of two"
def power_of_two(number):
"""
Function that checks if the input value (data) is a power of 2
(i.e. 2, 4, 8, 16, 32, ...)
"""
res = 0
while res == 0:
res = number % 2
number /= 2.0
print("res: {},... | en | 0.609998 | Function that checks if the input value (data) is a power of 2 (i.e. 2, 4, 8, 16, 32, ...) | 4.065114 | 4 |
examples/index/context.py | rmorshea/viewdom | 0 | 9627 | from viewdom import html, render, use_context, Context
expected = '<h1>My Todos</h1><ul><li>Item: first</li></ul>'
# start-after
title = 'My Todos'
todos = ['first']
def Todo(label):
prefix = use_context('prefix')
return html('<li>{prefix}{label}</li>')
def TodoList(todos):
return html('<ul>{[Todo(lab... | from viewdom import html, render, use_context, Context
expected = '<h1>My Todos</h1><ul><li>Item: first</li></ul>'
# start-after
title = 'My Todos'
todos = ['first']
def Todo(label):
prefix = use_context('prefix')
return html('<li>{prefix}{label}</li>')
def TodoList(todos):
return html('<ul>{[Todo(lab... | uk | 0.078813 | # start-after <{Context} prefix="Item: "> <h1>{title}</h1> <{TodoList} todos={todos} /> <//> # '<h1>My Todos</h1><ul><li>Item: first</li></ul>' | 2.53241 | 3 |
biblioteca/views.py | Dagmoores/ProjetoIntegradorIUnivesp | 0 | 9628 | from django.views.generic import DetailView, ListView, TemplateView
from .models import Books
class BooksListView(ListView):
model = Books
class BooksDeitalView(DetailView):
model = Books
class Home(TemplateView):
template_name = './biblioteca/index.html'
class TermsOfService(TemplateView):
templat... | from django.views.generic import DetailView, ListView, TemplateView
from .models import Books
class BooksListView(ListView):
model = Books
class BooksDeitalView(DetailView):
model = Books
class Home(TemplateView):
template_name = './biblioteca/index.html'
class TermsOfService(TemplateView):
templat... | none | 1 | 2.066607 | 2 | |
choir/evaluation/__init__.py | scwangdyd/large_vocabulary_hoi_detection | 9 | 9629 | <filename>choir/evaluation/__init__.py<gh_stars>1-10
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .evaluator import DatasetEvaluator, DatasetEvaluators, inference_context, inference_on_dataset
from .testing import print_csv_format, verify_results
from .hico_evaluation import HICOEvaluator... | <filename>choir/evaluation/__init__.py<gh_stars>1-10
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .evaluator import DatasetEvaluator, DatasetEvaluators, inference_context, inference_on_dataset
from .testing import print_csv_format, verify_results
from .hico_evaluation import HICOEvaluator... | en | 0.812148 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # from .doh_evaluation import DOHDetectionEvaluator | 1.304625 | 1 |
api_yamdb/reviews/models.py | LHLHLHE/api_yamdb | 0 | 9630 | <reponame>LHLHLHE/api_yamdb<filename>api_yamdb/reviews/models.py
import datetime as dt
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.core.exceptions import ValidationError
from users.models import CustomUser
def validate_year(value):
"""
Год... | import datetime as dt
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.core.exceptions import ValidationError
from users.models import CustomUser
def validate_year(value):
"""
Год выпуска произведения не может быть больше текущего.
"""
... | ru | 0.993086 | Год выпуска произведения не может быть больше текущего. Модель категорий. Модель жанров. Модель произведений. Модель для связи произведений и жанров отношением многие ко многим. | 2.493118 | 2 |
angr/engines/pcode/arch/ArchPcode_PowerPC_LE_32_QUICC.py | matthewpruett/angr | 6,132 | 9631 | ###
### This file was automatically generated
###
from archinfo.arch import register_arch, Endness, Register
from .common import ArchPcode
class ArchPcode_PowerPC_LE_32_QUICC(ArchPcode):
name = 'PowerPC:LE:32:QUICC'
pcode_arch = 'PowerPC:LE:32:QUICC'
description = 'PowerQUICC-III 32-bit little endian fa... | ###
### This file was automatically generated
###
from archinfo.arch import register_arch, Endness, Register
from .common import ArchPcode
class ArchPcode_PowerPC_LE_32_QUICC(ArchPcode):
name = 'PowerPC:LE:32:QUICC'
pcode_arch = 'PowerPC:LE:32:QUICC'
description = 'PowerQUICC-III 32-bit little endian fa... | en | 0.818191 | ### ### This file was automatically generated ### | 1.62084 | 2 |
makesense/graph.py | sieben/makesense | 5 | 9632 | # -*- coding: utf-8 -*-
import json
import pdb
import os
from os.path import join as pj
import networkx as nx
import pandas as pd
from networkx.readwrite.json_graph import node_link_data
def chain():
g = nx.Graph()
# Horizontal
for i in range(11, 15):
g.add_edge(i, i + 1)
for i in range(... | # -*- coding: utf-8 -*-
import json
import pdb
import os
from os.path import join as pj
import networkx as nx
import pandas as pd
from networkx.readwrite.json_graph import node_link_data
def chain():
g = nx.Graph()
# Horizontal
for i in range(11, 15):
g.add_edge(i, i + 1)
for i in range(... | en | 0.842828 | # -*- coding: utf-8 -*- # Horizontal # Trans height # Drawing #nx.draw_networkx_edges(g, pos, edge_color="r", arrows=True) Plot the transmission graph of the simulation. TODO: Draw arrows and have a directed graph. http://goo.gl/Z697dH TODO: Graph with big nodes for big transmissions # color for all nodes... | 2.776902 | 3 |
recipes/Python/52228_Remote_control_with_telnetlib/recipe-52228.py | tdiprima/code | 2,023 | 9633 | <reponame>tdiprima/code<filename>recipes/Python/52228_Remote_control_with_telnetlib/recipe-52228.py
# auto_telnet.py - remote control via telnet
import os, sys, string, telnetlib
from getpass import getpass
class AutoTelnet:
def __init__(self, user_list, cmd_list, **kw):
self.host = kw.get('host', 'localho... | # auto_telnet.py - remote control via telnet
import os, sys, string, telnetlib
from getpass import getpass
class AutoTelnet:
def __init__(self, user_list, cmd_list, **kw):
self.host = kw.get('host', 'localhost')
self.timeout = kw.get('timeout', 600)
self.command_prompt = kw.get('command_pro... | en | 0.428796 | # auto_telnet.py - remote control via telnet usage: %s [-h host] [-f cmdfile] [-c "command"] user1 user2 ... -c command -f command file -h host (default: '%s') Example: %s -c "echo $HOME" %s | 2.791927 | 3 |
FFTNet_dilconv.py | mimbres/FFTNet | 0 | 9634 | <filename>FFTNet_dilconv.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 7 09:46:10 2018
@author: sungkyun
FFTNet model using 2x1 dil-conv
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# Models with Preset (for convenience)
'''
dim_input: dimension... | <filename>FFTNet_dilconv.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 7 09:46:10 2018
@author: sungkyun
FFTNet model using 2x1 dil-conv
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# Models with Preset (for convenience)
'''
dim_input: dimension... | en | 0.703387 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Mon May 7 09:46:10 2018 @author: sungkyun FFTNet model using 2x1 dil-conv # Models with Preset (for convenience) dim_input: dimension of input (256 for 8-bit mu-law input) num_layer: number of layers (11 in paper). receptive field = 2^11 (2,048) io_ch: number... | 2.349741 | 2 |
snewpdag/plugins/Copy.py | SNEWS2/snewpdag | 0 | 9635 | <filename>snewpdag/plugins/Copy.py
"""
Copy - copy fields into other (possibly new) fields
configuration:
on: list of 'alert', 'revoke', 'report', 'reset' (optional: def 'alert' only)
cp: ( (in,out), ... )
Field names take the form of dir1/dir2/dir3,
which in the payload will be data[dir1][dir2][dir3]
"""
import ... | <filename>snewpdag/plugins/Copy.py
"""
Copy - copy fields into other (possibly new) fields
configuration:
on: list of 'alert', 'revoke', 'report', 'reset' (optional: def 'alert' only)
cp: ( (in,out), ... )
Field names take the form of dir1/dir2/dir3,
which in the payload will be data[dir1][dir2][dir3]
"""
import ... | en | 0.667257 | Copy - copy fields into other (possibly new) fields configuration: on: list of 'alert', 'revoke', 'report', 'reset' (optional: def 'alert' only) cp: ( (in,out), ... ) Field names take the form of dir1/dir2/dir3, which in the payload will be data[dir1][dir2][dir3] # should just follow references # v should now hol... | 2.356917 | 2 |
pages/aboutus.py | BuildWeek-AirBnB-Optimal-Price/application | 0 | 9636 | <gh_stars>0
'''
houses each team member's
link to personal GitHub io or
website or blog space
RJProctor
'''
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from app... | '''
houses each team member's
link to personal GitHub io or
website or blog space
RJProctor
'''
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from app import app
... | en | 0.705302 | houses each team member's link to personal GitHub io or website or blog space RJProctor # Imports from 3rd party libraries # 1 column layout # https://dash-bootstrap-components.opensource.faculty.ai/l/components/layout ## The Team: Select a link to learn more about each of our team members. # ... | 2.571122 | 3 |
Codes/Python32/Lib/importlib/test/extension/test_path_hook.py | eyantra/FireBird_Swiss_Knife | 319 | 9637 | from importlib import _bootstrap
from . import util
import collections
import imp
import sys
import unittest
class PathHookTests(unittest.TestCase):
"""Test the path hook for extension modules."""
# XXX Should it only succeed for pre-existing directories?
# XXX Should it only work for directories contai... | from importlib import _bootstrap
from . import util
import collections
import imp
import sys
import unittest
class PathHookTests(unittest.TestCase):
"""Test the path hook for extension modules."""
# XXX Should it only succeed for pre-existing directories?
# XXX Should it only work for directories contai... | en | 0.712909 | Test the path hook for extension modules. # XXX Should it only succeed for pre-existing directories? # XXX Should it only work for directories containing an extension module? # Path hook should handle a directory where a known extension module # exists. | 2.513168 | 3 |
3. count_words/solution.py | dcragusa/WeeklyPythonExerciseB2 | 0 | 9638 | import os
from glob import iglob
from concurrent.futures import ThreadPoolExecutor
def count_words_file(path):
if not os.path.isfile(path):
return 0
with open(path) as file:
return sum(len(line.split()) for line in file)
def count_words_sequential(pattern):
return sum(map(count_words_fil... | import os
from glob import iglob
from concurrent.futures import ThreadPoolExecutor
def count_words_file(path):
if not os.path.isfile(path):
return 0
with open(path) as file:
return sum(len(line.split()) for line in file)
def count_words_sequential(pattern):
return sum(map(count_words_fil... | none | 1 | 3.064904 | 3 | |
kafka-connect-azblob/docs/autoreload.py | cirobarradov/kafka-connect-hdfs-datalab | 0 | 9639 | <reponame>cirobarradov/kafka-connect-hdfs-datalab<filename>kafka-connect-azblob/docs/autoreload.py
#!/usr/bin/env python
from livereload import Server, shell
server = Server()
server.watch('*.rst', shell('make html'))
server.serve()
| #!/usr/bin/env python
from livereload import Server, shell
server = Server()
server.watch('*.rst', shell('make html'))
server.serve() | ru | 0.26433 | #!/usr/bin/env python | 1.451584 | 1 |
keras_textclassification/conf/path_config.py | atom-zh/Keras-TextClassification | 0 | 9640 | # -*- coding: UTF-8 -*-
# !/usr/bin/python
# @time :2019/6/5 21:04
# @author :Mo
# @function :file of path
import os
import pathlib
import sys
# 项目的根目录
path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
path_root = path_root.replace('\\', '/')
path_top = str(pathlib.P... | # -*- coding: UTF-8 -*-
# !/usr/bin/python
# @time :2019/6/5 21:04
# @author :Mo
# @function :file of path
import os
import pathlib
import sys
# 项目的根目录
path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
path_root = path_root.replace('\\', '/')
path_top = str(pathlib.P... | zh | 0.355073 | # -*- coding: UTF-8 -*- # !/usr/bin/python # @time :2019/6/5 21:04 # @author :Mo # @function :file of path # 项目的根目录 # path of embedding # classify data of baidu qa 2019 # 今日头条新闻多标签分类 # classify data of baidu qa 2019 # classfiy multi labels 2021 # 路径抽象层 # fast_text config # 模型目录 # 语料地址 # 超参数保存地址 # embedding微调保存地址 ... | 2.251648 | 2 |
tests/test_apyhgnc.py | robertopreste/apyhgnc | 0 | 9641 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Created by <NAME>
import pytest
import asyncio
from pandas.testing import assert_frame_equal
from apyhgnc import apyhgnc
# apyhgnc.info
def test_info_searchableFields(searchable_fields):
result = apyhgnc.info().searchableFields
assert result == searchable_field... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Created by <NAME>
import pytest
import asyncio
from pandas.testing import assert_frame_equal
from apyhgnc import apyhgnc
# apyhgnc.info
def test_info_searchableFields(searchable_fields):
result = apyhgnc.info().searchableFields
assert result == searchable_field... | en | 0.355132 | #!/usr/bin/env python # -*- coding: UTF-8 -*- # Created by <NAME> # apyhgnc.info # apyhgnc.fetch # apyhgnc.search | 2.300894 | 2 |
bdaq/tools/extract_enums.py | magnium/pybdaq | 0 | 9642 | import os.path
import argparse
from xml.etree import ElementTree as ET
class ExtractedEnum(object):
def __init__(self, tag_name, value_names):
self.tag_name = tag_name
self.value_names = value_names
def write_pxd(self, file_):
file_.write("\n ctypedef enum {}:\n".format(self.tag_n... | import os.path
import argparse
from xml.etree import ElementTree as ET
class ExtractedEnum(object):
def __init__(self, tag_name, value_names):
self.tag_name = tag_name
self.value_names = value_names
def write_pxd(self, file_):
file_.write("\n ctypedef enum {}:\n".format(self.tag_n... | en | 0.258079 | # parse XML # extract typedefs # extract enums # write pxd file header # write pyx file header # write enums # parse script arguments # extract enums | 2.854523 | 3 |
Objetos/biblioteca.py | SebaB29/Python | 0 | 9643 | <filename>Objetos/biblioteca.py<gh_stars>0
class Libro:
def __init__(self, titulo, autor):
"""..."""
self.titulo = titulo
self.autor = autor
def obtener_titulo(self):
"""..."""
return str(self.titulo)
def obtener_autor(self):
"""..."""
return... | <filename>Objetos/biblioteca.py<gh_stars>0
class Libro:
def __init__(self, titulo, autor):
"""..."""
self.titulo = titulo
self.autor = autor
def obtener_titulo(self):
"""..."""
return str(self.titulo)
def obtener_autor(self):
"""..."""
return... | sh | 0.88023 | ... ... ... ... ... ... ... | 3.39642 | 3 |
parser_tool/tests/test_htmlgenerator.py | Harvard-ATG/visualizing_russian_tools | 2 | 9644 | <filename>parser_tool/tests/test_htmlgenerator.py<gh_stars>1-10
# -*- coding: utf-8 -*-
import unittest
from xml.etree import ElementTree as ET
from parser_tool import tokenizer
from parser_tool import htmlgenerator
class TestHtmlGenerator(unittest.TestCase):
def _maketokendict(self, **kwargs):
token_te... | <filename>parser_tool/tests/test_htmlgenerator.py<gh_stars>1-10
# -*- coding: utf-8 -*-
import unittest
from xml.etree import ElementTree as ET
from parser_tool import tokenizer
from parser_tool import htmlgenerator
class TestHtmlGenerator(unittest.TestCase):
def _maketokendict(self, **kwargs):
token_te... | en | 0.836133 | # -*- coding: utf-8 -*- # (собака) dog # Check the root element (e.g. container) # Check that we have the expected number of child elements (1 element for each word or russian token) # Now check the first few tokens... # 1) Check that the first child contains the text of the first token # 2) Check that the first child'... | 2.663684 | 3 |
taiga/hooks/gitlab/migrations/0002_auto_20150703_1102.py | threefoldtech/Threefold-Circles | 1 | 9645 | <reponame>threefoldtech/Threefold-Circles
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.core.files import File
def update_gitlab_system_user_photo_to_v2(apps, schema_editor):
# We get the model from the versioned app registry;
# if we dire... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.core.files import File
def update_gitlab_system_user_photo_to_v2(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'll be the wrong version... | en | 0.875612 | # -*- coding: utf-8 -*- # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version | 2.172942 | 2 |
external_plugin_deps.bzl | michalgagat/plugins_oauth | 143 | 9646 | <reponame>michalgagat/plugins_oauth
load("//tools/bzl:maven_jar.bzl", "maven_jar")
def external_plugin_deps(omit_commons_codec = True):
JACKSON_VERS = "2.10.2"
maven_jar(
name = "scribejava-core",
artifact = "com.github.scribejava:scribejava-core:6.9.0",
sha1 = "ed761f450d8382f75787e8fe... | load("//tools/bzl:maven_jar.bzl", "maven_jar")
def external_plugin_deps(omit_commons_codec = True):
JACKSON_VERS = "2.10.2"
maven_jar(
name = "scribejava-core",
artifact = "com.github.scribejava:scribejava-core:6.9.0",
sha1 = "ed761f450d8382f75787e8fee9ae52e7ec768747",
)
maven_j... | none | 1 | 1.498743 | 1 | |
11.-Operaciones_entero_con_float_python.py | emiliocarcanobringas/11.-Operaciones_entero_con_float_python | 0 | 9647 | <filename>11.-Operaciones_entero_con_float_python.py
# Este programa muestra la suma de dos variables, de tipo int y float
print("Este programa muestra la suma de dos variables, de tipo int y float")
print("También muestra que la variable que realiza la operación es de tipo float")
numero1 = 7
numero2 = 3.1416
s... | <filename>11.-Operaciones_entero_con_float_python.py
# Este programa muestra la suma de dos variables, de tipo int y float
print("Este programa muestra la suma de dos variables, de tipo int y float")
print("También muestra que la variable que realiza la operación es de tipo float")
numero1 = 7
numero2 = 3.1416
s... | es | 0.989395 | # Este programa muestra la suma de dos variables, de tipo int y float # Este programa fue escrito por <NAME> | 3.901936 | 4 |
main_gat.py | basiralab/RG-Select | 1 | 9648 | # -*- coding: utf-8 -*-
from sklearn import preprocessing
from torch.autograd import Variable
from models_gat import GAT
import os
import torch
import numpy as np
import argparse
import pickle
import sklearn.metrics as metrics
import cross_val
import time
import random
torch.manual_seed(0)
np.random.seed(0)
random.s... | # -*- coding: utf-8 -*-
from sklearn import preprocessing
from torch.autograd import Variable
from models_gat import GAT
import os
import torch
import numpy as np
import argparse
import pickle
import sklearn.metrics as metrics
import cross_val
import time
import random
torch.manual_seed(0)
np.random.seed(0)
random.s... | en | 0.442512 | # -*- coding: utf-8 -*- Parameters ---------- dataset : dataloader (dataloader for the validation/test dataset). model_GCN : nn model (GAT model). args : arguments threshold_value : float (threshold for adjacency matrices). Description ---------- This methods performs the evaluation... | 2.500538 | 3 |
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Python/piexif/_dump.py | jeikabu/lumberyard | 8 | 9649 | import copy
import numbers
import struct
from ._common import *
from ._exif import *
TIFF_HEADER_LENGTH = 8
def dump(exif_dict_original):
"""
py:function:: piexif.load(data)
Return exif as bytes.
:param dict exif: Exif data({"0th":dict, "Exif":dict, "GPS":dict, "Interop":dict, "1st":dict, "thumbn... | import copy
import numbers
import struct
from ._common import *
from ._exif import *
TIFF_HEADER_LENGTH = 8
def dump(exif_dict_original):
"""
py:function:: piexif.load(data)
Return exif as bytes.
:param dict exif: Exif data({"0th":dict, "Exif":dict, "GPS":dict, "Interop":dict, "1st":dict, "thumbn... | en | 0.700886 | py:function:: piexif.load(data) Return exif as bytes. :param dict exif: Exif data({"0th":dict, "Exif":dict, "GPS":dict, "Interop":dict, "1st":dict, "thumbnail":bytes}) :return: Exif :rtype: bytes # Signed Byte # Signed Short # Double | 2.464272 | 2 |
portal.py | mrahman4782/portalhoop | 0 | 9650 | import pygame
import random
from pygame import *
pygame.init()
width, height = 740, 500
screen = pygame.display.set_mode((width, height))
player = [pygame.transform.scale(pygame.image.load("Resources/Balljump-1(2).png"), (100,100)), pygame.t... | import pygame
import random
from pygame import *
pygame.init()
width, height = 740, 500
screen = pygame.display.set_mode((width, height))
player = [pygame.transform.scale(pygame.image.load("Resources/Balljump-1(2).png"), (100,100)), pygame.t... | en | 0.542941 | # Background image source: https://www.freepik.com/free-vector/floral-ornamental-abstract-background_6189902.htm#page=1&query=black%20background&position=40 #Draw basketball # Animations while the user makes no input # Initial animations before the player jumps #print(pygame.time.get_ticks()) #print(nojump) #if p >= 19... | 2.776063 | 3 |
datadog_cluster_agent/tests/test_datadog_cluster_agent.py | tdimnet/integrations-core | 1 | 9651 | <gh_stars>1-10
# (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from typing import Any, Dict
from datadog_checks.base.stubs.aggregator import AggregatorStub
from datadog_checks.datadog_cluster_agent import DatadogClusterAgentCheck
from datadog_checks.de... | # (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from typing import Any, Dict
from datadog_checks.base.stubs.aggregator import AggregatorStub
from datadog_checks.datadog_cluster_agent import DatadogClusterAgentCheck
from datadog_checks.dev.utils import ... | en | 0.731459 | # (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) # type: (AggregatorStub, Dict[str, Any]) -> None # dry run to build mapping for label joins | 1.714529 | 2 |
prev_ob_models/KaplanLansner2014/plotting_and_analysis/plot_results.py | fameshpatel/olfactorybulb | 5 | 9652 | <gh_stars>1-10
import pylab
import numpy
import sys
if (len(sys.argv) < 2):
fn = raw_input("Please enter data file to be plotted\n")
else:
fn = sys.argv[1]
data = np.loadtxt(fn)
# if the first line contains crap use skiprows=1
#data = np.loadtxt(fn, skiprows=1)
fig = pylab.figure()
ax = fig.add_subplot(111)... | import pylab
import numpy
import sys
if (len(sys.argv) < 2):
fn = raw_input("Please enter data file to be plotted\n")
else:
fn = sys.argv[1]
data = np.loadtxt(fn)
# if the first line contains crap use skiprows=1
#data = np.loadtxt(fn, skiprows=1)
fig = pylab.figure()
ax = fig.add_subplot(111)
# if you wan... | en | 0.329315 | # if the first line contains crap use skiprows=1 #data = np.loadtxt(fn, skiprows=1) # if you want to use multiple figures in one, use #ax1 = fig.add_subplot(211) #ax2 = fig.add_subplot(212) # and # ax.errorbar(data[:,0], data[:,1], yerr=data[:, 2]) # print 'mean y-value:', data[:, 1].mean() # ax.scatter(data[:... | 2.817714 | 3 |
pyeccodes/defs/grib2/tables/15/3_11_table.py | ecmwf/pyeccodes | 7 | 9653 | def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'There is no appended list'},
{'abbr': 1,
'code': 1,
'title': 'Numbers define number of points corresponding to full coordinate '
'circles (i.e. parallels), coordinate values on each circle are '
... | def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'There is no appended list'},
{'abbr': 1,
'code': 1,
'title': 'Numbers define number of points corresponding to full coordinate '
'circles (i.e. parallels), coordinate values on each circle are '
... | none | 1 | 2.328723 | 2 | |
lib/take2/main.py | zacharyfrederick/deep_q_gaf | 0 | 9654 | <filename>lib/take2/main.py<gh_stars>0
from __future__ import division
from lib import env_config
from lib.senior_env import BetterEnvironment
from keras.optimizers import Adam
from rl.agents.dqn import DQNAgent
from rl.policy import LinearAnnealedPolicy, BoltzmannQPolicy, EpsGreedyQPolicy
from rl.memory import Sequen... | <filename>lib/take2/main.py<gh_stars>0
from __future__ import division
from lib import env_config
from lib.senior_env import BetterEnvironment
from keras.optimizers import Adam
from rl.agents.dqn import DQNAgent
from rl.policy import LinearAnnealedPolicy, BoltzmannQPolicy, EpsGreedyQPolicy
from rl.memory import Sequen... | en | 0.926357 | # Get the environment and extract the number of actions. # Next, we build our model. We use the same model that was described by Mnih et al. (2015). # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and # even the metrics! # Select a policy. We use eps-greedy action selection, wh... | 2.339412 | 2 |
src/clcore.py | ShepardPower/PyMCBuilder | 1 | 9655 | <filename>src/clcore.py
# I'm just the one that executes the instructions!
import sys, math, json, operator, time
import mcpi.minecraft as minecraft
from PIL import Image as pillow
from blockid import get_block
import mcpi.block as block
import functions as pymc
from tqdm import tqdm
import tkinter as tk
# Functions
... | <filename>src/clcore.py
# I'm just the one that executes the instructions!
import sys, math, json, operator, time
import mcpi.minecraft as minecraft
from PIL import Image as pillow
from blockid import get_block
import mcpi.block as block
import functions as pymc
from tqdm import tqdm
import tkinter as tk
# Functions
... | en | 0.679236 | # I'm just the one that executes the instructions! # Functions # Main code # The result #print(used[wid + (imhei * hei)]) | 2.428716 | 2 |
gaphor/tools/gaphorconvert.py | 987Frogh/project-makehuman | 1 | 9656 | <reponame>987Frogh/project-makehuman<gh_stars>1-10
#!/usr/bin/python
import optparse
import os
import re
import sys
import cairo
from gaphas.painter import Context, ItemPainter
from gaphas.view import View
import gaphor.UML as UML
from gaphor.application import Application
from gaphor.storage import storage
def pk... | #!/usr/bin/python
import optparse
import os
import re
import sys
import cairo
from gaphas.painter import Context, ItemPainter
from gaphas.view import View
import gaphor.UML as UML
from gaphor.application import Application
from gaphor.storage import storage
def pkg2dir(package):
"""
Return directory path f... | en | 0.78088 | #!/usr/bin/python Return directory path from UML package class. Print message if user set verbose mode. # we should have some gaphor files to be processed at this point # just diagram name # full diagram name including package path | 2.572684 | 3 |
zeta_python_sdk/exceptions.py | prettyirrelevant/zeta-python-sdk | 2 | 9657 | <reponame>prettyirrelevant/zeta-python-sdk
class InvalidSideException(Exception):
"""Invalid side"""
class NotSupportedException(Exception):
"""Not supported by dummy wallet"""
class InvalidProductException(Exception):
"""Invalid product type"""
class OutOfBoundsException(Exception):
"""Attempt to... | class InvalidSideException(Exception):
"""Invalid side"""
class NotSupportedException(Exception):
"""Not supported by dummy wallet"""
class InvalidProductException(Exception):
"""Invalid product type"""
class OutOfBoundsException(Exception):
"""Attempt to access memory outside buffer bounds""" | en | 0.833229 | Invalid side Not supported by dummy wallet Invalid product type Attempt to access memory outside buffer bounds | 2.460676 | 2 |
test/test_ID.py | a-buntjer/tsib | 14 | 9658 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 08 11:33:01 2016
@author: <NAME>
"""
import tsib
def test_get_ID():
# parameterize a building
bdgcfg = tsib.BuildingConfiguration(
{
"refurbishment": False,
"nightReduction": False,
"occControl": Fals... | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 08 11:33:01 2016
@author: <NAME>
"""
import tsib
def test_get_ID():
# parameterize a building
bdgcfg = tsib.BuildingConfiguration(
{
"refurbishment": False,
"nightReduction": False,
"occControl": False,
"c... | en | 0.697297 | # -*- coding: utf-8 -*- Created on Fri Apr 08 11:33:01 2016 @author: <NAME> # parameterize a building # parameterize a building | 2.687924 | 3 |
dislib/model_selection/_search.py | alexbarcelo/dislib | 36 | 9659 | <gh_stars>10-100
from abc import ABC, abstractmethod
from collections import defaultdict
from collections.abc import Sequence
from functools import partial
from itertools import product
import numpy as np
from pycompss.api.api import compss_wait_on
from scipy.stats import rankdata
from sklearn import clone
from sklear... | from abc import ABC, abstractmethod
from collections import defaultdict
from collections.abc import Sequence
from functools import partial
from itertools import product
import numpy as np
from pycompss.api.api import compss_wait_on
from scipy.stats import rankdata
from sklearn import clone
from sklearn.model_selection... | en | 0.631181 | Abstract base class for hyper parameter search with cross-validation. Abstract method to perform the search. The parameter `evaluate_candidates` is a function that evaluates a ParameterGrid at a time Run fit with all sets of parameters. Parameters ---------- x : ds-array ... | 2.672627 | 3 |
webapp/ui/tests/test_parse_search_results.py | robseed/botanist | 0 | 9660 | <filename>webapp/ui/tests/test_parse_search_results.py
import os
from django.test import TestCase
from mock import patch
from ui.views import parse_search_results
FIXTURES_ROOT = os.path.join(os.path.dirname(__file__), 'fixtures')
FX = lambda *relpath: os.path.join(FIXTURES_ROOT, *relpath)
@patch('ui.views.get_rep... | <filename>webapp/ui/tests/test_parse_search_results.py
import os
from django.test import TestCase
from mock import patch
from ui.views import parse_search_results
FIXTURES_ROOT = os.path.join(os.path.dirname(__file__), 'fixtures')
FX = lambda *relpath: os.path.join(FIXTURES_ROOT, *relpath)
@patch('ui.views.get_rep... | none | 1 | 2.278082 | 2 | |
minos/api_gateway/common/exceptions.py | Clariteia/api_gateway_common | 3 | 9661 | """
Copyright (C) 2021 Clariteia SL
This file is part of minos framework.
Minos framework can not be copied and/or distributed without the express permission of Clariteia SL.
"""
from typing import (
Any,
Type,
)
class MinosException(Exception):
"""Exception class for import packages or modules"""
... | """
Copyright (C) 2021 Clariteia SL
This file is part of minos framework.
Minos framework can not be copied and/or distributed without the express permission of Clariteia SL.
"""
from typing import (
Any,
Type,
)
class MinosException(Exception):
"""Exception class for import packages or modules"""
... | en | 0.91464 | Copyright (C) 2021 Clariteia SL This file is part of minos framework. Minos framework can not be copied and/or distributed without the express permission of Clariteia SL. Exception class for import packages or modules represent in a string format the error message passed during the instantiation Base config exception... | 2.245977 | 2 |
tsdl/tools/extensions.py | burgerdev/hostload | 0 | 9662 | <reponame>burgerdev/hostload
"""
Extensions for pylearn2 training algorithms. Those are either reimplemented to
suit the execution model of this package, or new ones for recording metrics.
"""
import os
import cPickle as pkl
import numpy as np
from pylearn2.train_extensions import TrainExtension
from .abcs import ... | """
Extensions for pylearn2 training algorithms. Those are either reimplemented to
suit the execution model of this package, or new ones for recording metrics.
"""
import os
import cPickle as pkl
import numpy as np
from pylearn2.train_extensions import TrainExtension
from .abcs import Buildable
class BuildableTr... | en | 0.818645 | Extensions for pylearn2 training algorithms. Those are either reimplemented to suit the execution model of this package, or new ones for recording metrics. makes a pylearn2 TrainExtension buildable build an instance of this class with given configuration dict override to provide your own default configuration abstract ... | 2.448397 | 2 |
nogi/utils/post_extractor.py | Cooomma/nogi-backup-blog | 0 | 9663 | import asyncio
from io import BytesIO
import logging
import os
import random
import time
from typing import List
from urllib.parse import urlparse
import aiohttp
from aiohttp import ClientSession, TCPConnector
import requests
from requests import Response
from tqdm import tqdm
from nogi import REQUEST_HEADERS
from no... | import asyncio
from io import BytesIO
import logging
import os
import random
import time
from typing import List
from urllib.parse import urlparse
import aiohttp
from aiohttp import ClientSession, TCPConnector
import requests
from requests import Response
from tqdm import tqdm
from nogi import REQUEST_HEADERS
from no... | en | 0.756932 | # DB # GCS Storage # Tasks | 2.014291 | 2 |
sandbox/lib/jumpscale/JumpscaleLibsExtra/sal_zos/gateway/dhcp.py | threefoldtech/threebot_prebuilt | 1 | 9664 | from Jumpscale import j
import signal
from .. import templates
DNSMASQ = "/bin/dnsmasq --conf-file=/etc/dnsmasq.conf -d"
class DHCP:
def __init__(self, container, domain, networks):
self.container = container
self.domain = domain
self.networks = networks
def apply_config(self):
... | from Jumpscale import j
import signal
from .. import templates
DNSMASQ = "/bin/dnsmasq --conf-file=/etc/dnsmasq.conf -d"
class DHCP:
def __init__(self, container, domain, networks):
self.container = container
self.domain = domain
self.networks = networks
def apply_config(self):
... | en | 0.749318 | # check if command is listening for dhcp | 2.228868 | 2 |
answer/a4_type.py | breeze-shared-inc/python_training_01 | 0 | 9665 | hensu_int = 17 #数字
hensu_float = 1.7 #小数点(浮動小数点)
hensu_str = "HelloWorld" #文字列
hensu_bool = True #真偽
hensu_list = [] #リスト
hensu_tuple = () #タプル
hensu_dict = {} #辞書(ディクト)型
print(type(hensu_int))
print(type(hensu_float))
print(type(hensu_str))
print(type(hensu_bool))
print(type(hensu_list))
print(type(hensu_tuple))
prin... | hensu_int = 17 #数字
hensu_float = 1.7 #小数点(浮動小数点)
hensu_str = "HelloWorld" #文字列
hensu_bool = True #真偽
hensu_list = [] #リスト
hensu_tuple = () #タプル
hensu_dict = {} #辞書(ディクト)型
print(type(hensu_int))
print(type(hensu_float))
print(type(hensu_str))
print(type(hensu_bool))
print(type(hensu_list))
print(type(hensu_tuple))
prin... | ja | 0.980488 | #数字 #小数点(浮動小数点) #文字列 #真偽 #リスト #タプル #辞書(ディクト)型 | 3.373268 | 3 |
LEDdebug/examples/led-demo.py | UrsaLeo/LEDdebug | 0 | 9666 | #!/usr/bin/env python3
"""UrsaLeo LEDdebug board LED demo
Turn the LED's on one at a time, then all off"""
import time
ON = 1
OFF = 0
DELAY = 0.5 # seconds
try:
from LEDdebug import LEDdebug
except ImportError:
try:
import sys
import os
sys.path.append("..")
sys.path.appen... | #!/usr/bin/env python3
"""UrsaLeo LEDdebug board LED demo
Turn the LED's on one at a time, then all off"""
import time
ON = 1
OFF = 0
DELAY = 0.5 # seconds
try:
from LEDdebug import LEDdebug
except ImportError:
try:
import sys
import os
sys.path.append("..")
sys.path.appen... | en | 0.799568 | #!/usr/bin/env python3 UrsaLeo LEDdebug board LED demo Turn the LED's on one at a time, then all off # seconds # Create device # Turn on each LED in succession # Turn all the lights of before leaving! | 2.916463 | 3 |
modules/server.py | Nitin-Mane/SARS-CoV-2-xDNN-Classifier | 0 | 9667 | <reponame>Nitin-Mane/SARS-CoV-2-xDNN-Classifier
#!/usr/bin/env python
###################################################################################
##
## Project: COVID -19 xDNN Classifier 2020
## Version: 1.0.0
## Module: Server
## Desription: The COVID -19 xDNN Classifier 2020 server.
## License: M... | #!/usr/bin/env python
###################################################################################
##
## Project: COVID -19 xDNN Classifier 2020
## Version: 1.0.0
## Module: Server
## Desription: The COVID -19 xDNN Classifier 2020 server.
## License: MIT
## Copyright: 2021, Asociacion De Investigac... | en | 0.449243 | #!/usr/bin/env python ################################################################################### ## ## Project: COVID -19 xDNN Classifier 2020 ## Version: 1.0.0 ## Module: Server ## Desription: The COVID -19 xDNN Classifier 2020 server. ## License: MIT ## Copyright: 2021, Asociacion De Investigac... | 1.280707 | 1 |
rdr_service/lib_fhir/fhirclient_3_0_0/models/allergyintolerance_tests.py | all-of-us/raw-data-repository | 39 | 9668 | <reponame>all-of-us/raw-data-repository
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 on 2017-03-22.
# 2017, SMART Health IT.
import io
import json
import os
import unittest
from . import allergyintolerance
from .fhirdate import FHIRDate
class AllergyIntoleranceTests(unittest.... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 on 2017-03-22.
# 2017, SMART Health IT.
import io
import json
import os
import unittest
from . import allergyintolerance
from .fhirdate import FHIRDate
class AllergyIntoleranceTests(unittest.TestCase):
def instantiate_from(self... | en | 0.665441 | #!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 3.0.0.11832 on 2017-03-22. # 2017, SMART Health IT. | 2.525127 | 3 |
jsparse/meijiexia/meijiexia.py | PyDee/Spiders | 6 | 9669 | import time
import random
import requests
from lxml import etree
import pymongo
from .url_file import mjx_weibo, mjx_dy, mjx_ks, mjx_xhs
class DBMongo:
def __init__(self):
self.my_client = pymongo.MongoClient("mongodb://localhost:27017/")
# 连接数据库
self.db = self.my_client["mcn"]
def i... | import time
import random
import requests
from lxml import etree
import pymongo
from .url_file import mjx_weibo, mjx_dy, mjx_ks, mjx_xhs
class DBMongo:
def __init__(self):
self.my_client = pymongo.MongoClient("mongodb://localhost:27017/")
# 连接数据库
self.db = self.my_client["mcn"]
def i... | zh | 0.944813 | # 连接数据库 # 数据写入mongoDB | 2.504928 | 3 |
MLModules/ABD/B_PCAQDA.py | jamster112233/ICS_IDS | 0 | 9670 | import numpy as np
from keras.utils import np_utils
import pandas as pd
import sys
from sklearn.preprocessing import LabelEncoder
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA
from sklearn.decomposition import PCA
import os
from sklearn.externals import joblib
from sklearn.metrics impor... | import numpy as np
from keras.utils import np_utils
import pandas as pd
import sys
from sklearn.preprocessing import LabelEncoder
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA
from sklearn.decomposition import PCA
import os
from sklearn.externals import joblib
from sklearn.metrics impor... | en | 0.218368 | # Create an object called iris with the iris Data # print(str(q) + ":" + str((float(score)/len(classesPred)*100)) + "%") # # preds = classesPred # if(len(preds) > 0): # preds = np.array(list(encoder.inverse_transform(preds))) # # df = pd.crosstab(dftest['Proto'], preds, rownames=['Actual Protocol'], colnames=['Pre... | 2.330605 | 2 |
GR2-Save-Loader.py | 203Null/Gravity-Rush-2-Save-Loader | 2 | 9671 | <reponame>203Null/Gravity-Rush-2-Save-Loader
import struct
import json
from collections import OrderedDict
file_path = "data0002.bin"
show_offset = True
show_hash = False
loaded_data = 0
def unpack(upstream_data_set):
global loaded_data
loaded_data = loaded_data + 1
currentCursor = file.tell()... | import struct
import json
from collections import OrderedDict
file_path = "data0002.bin"
show_offset = True
show_hash = False
loaded_data = 0
def unpack(upstream_data_set):
global loaded_data
loaded_data = loaded_data + 1
currentCursor = file.tell()
print(hex(file.tell()))
file.seek(... | en | 0.888831 | #Use UTF8 because some strings are in Japanese # List # String # Float # Boolean | 2.657665 | 3 |
python/Recursion.py | itzsoumyadip/vs | 1 | 9672 | ## to change recursion limit
import sys
print(sys.getrecursionlimit()) #Return the current value of the recursion limit
#1000
## change the limit
sys.setrecursionlimit(2000) # change value of the recursion limit
#2000
i=0
def greet():
global i
i+=1
print('hellow',i)
greet()
greet() # hellow... | ## to change recursion limit
import sys
print(sys.getrecursionlimit()) #Return the current value of the recursion limit
#1000
## change the limit
sys.setrecursionlimit(2000) # change value of the recursion limit
#2000
i=0
def greet():
global i
i+=1
print('hellow',i)
greet()
greet() # hellow... | en | 0.556779 | ## to change recursion limit #Return the current value of the recursion limit #1000 ## change the limit # change value of the recursion limit #2000 # hellow 1996 then error | 3.759327 | 4 |
pages/tests/test_views.py | andywar65/starter-fullstack | 0 | 9673 | from django.test import TestCase, override_settings
from django.urls import reverse
from pages.models import Article, HomePage
@override_settings(USE_I18N=False)
class PageViewTest(TestCase):
@classmethod
def setUpTestData(cls):
print("\nTest page views")
# Set up non-modified objects used by... | from django.test import TestCase, override_settings
from django.urls import reverse
from pages.models import Article, HomePage
@override_settings(USE_I18N=False)
class PageViewTest(TestCase):
@classmethod
def setUpTestData(cls):
print("\nTest page views")
# Set up non-modified objects used by... | en | 0.836748 | # Set up non-modified objects used by all test methods | 2.249852 | 2 |
poco/services/batch/server.py | sunliwen/poco | 0 | 9674 | <gh_stars>0
#!/usr/bin/env python
import logging
import sys
sys.path.append("../../")
sys.path.append("pylib")
import time
import datetime
import pymongo
import uuid
import os
import subprocess
import os.path
import settings
from common.utils import getSiteDBCollection
sys.path.insert(0, "../../")
class LoggingMana... | #!/usr/bin/env python
import logging
import sys
sys.path.append("../../")
sys.path.append("pylib")
import time
import datetime
import pymongo
import uuid
import os
import subprocess
import os.path
import settings
from common.utils import getSiteDBCollection
sys.path.insert(0, "../../")
class LoggingManager:
de... | en | 0.502758 | #!/usr/bin/env python # execute downlines #ret_code = os.system(command) # if ret_code != 0: # raise ShellExecutionError("Shell Execution Failed, ret_code=%s" % ret_code) # TODO: send message (email, sms) # TODO: record exception info. # FIXME: load correct last_ts from somewhere # FIXME: save last_ts somewhere # Be... | 2.164202 | 2 |
tests/integration/basket/model_tests.py | makielab/django-oscar | 0 | 9675 | from decimal import Decimal as D
from django.test import TestCase
from oscar.apps.basket.models import Basket
from oscar.apps.partner import strategy
from oscar.test import factories
from oscar.apps.catalogue.models import Option
class TestAddingAProductToABasket(TestCase):
def setUp(self):
self.basket... | from decimal import Decimal as D
from django.test import TestCase
from oscar.apps.basket.models import Basket
from oscar.apps.partner import strategy
from oscar.test import factories
from oscar.apps.catalogue.models import Option
class TestAddingAProductToABasket(TestCase):
def setUp(self):
self.basket... | none | 1 | 2.31059 | 2 | |
tests/fixtures/db/sqlite.py | code-watch/meltano | 8 | 9676 | import pytest
import os
import sqlalchemy
import contextlib
@pytest.fixture(scope="session")
def engine_uri(test_dir):
database_path = test_dir.joinpath("pytest_meltano.db")
try:
database_path.unlink()
except FileNotFoundError:
pass
return f"sqlite:///{database_path}"
| import pytest
import os
import sqlalchemy
import contextlib
@pytest.fixture(scope="session")
def engine_uri(test_dir):
database_path = test_dir.joinpath("pytest_meltano.db")
try:
database_path.unlink()
except FileNotFoundError:
pass
return f"sqlite:///{database_path}"
| none | 1 | 1.854784 | 2 | |
experiments/render-tests-avg.py | piotr-karon/realworld-starter-kit | 0 | 9677 | <reponame>piotr-karon/realworld-starter-kit
#!/usr/bin/env python3
import json
import os
from pathlib import Path
import numpy as np
from natsort import natsorted
try:
from docopt import docopt
from marko.ext.gfm import gfm
import pygal
from pygal.style import Style, DefaultStyle
except ImportError a... | #!/usr/bin/env python3
import json
import os
from pathlib import Path
import numpy as np
from natsort import natsorted
try:
from docopt import docopt
from marko.ext.gfm import gfm
import pygal
from pygal.style import Style, DefaultStyle
except ImportError as e:
raise Exception('Some external depe... | en | 0.486867 | #!/usr/bin/env python3 # print('## General Info & Checks', file=out) # render_checks(names, suites, out) # Graphs', file=out) # Use HTML instead of Markdown image to specify the width # round to 3 significant figures Simple decorator to mark a function as a figure generator. # print(vals) # print(suites[name]['stats'])... | 2.3924 | 2 |
litex/build/altera/quartus.py | osterwood/litex | 1,501 | 9678 | #
# This file is part of LiteX.
#
# Copyright (c) 2014-2019 <NAME> <<EMAIL>>
# Copyright (c) 2019 msloniewski <<EMAIL>>
# Copyright (c) 2019 vytautasb <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
import os
import subprocess
import sys
import math
from shutil import which
from migen.fhdl.structure import _Fragmen... | #
# This file is part of LiteX.
#
# Copyright (c) 2014-2019 <NAME> <<EMAIL>>
# Copyright (c) 2019 msloniewski <<EMAIL>>
# Copyright (c) 2019 vytautasb <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
import os
import subprocess
import sys
import math
from shutil import which
from migen.fhdl.structure import _Fragmen... | en | 0.556667 | # # This file is part of LiteX. # # Copyright (c) 2014-2019 <NAME> <<EMAIL>> # Copyright (c) 2019 msloniewski <<EMAIL>> # Copyright (c) 2019 vytautasb <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause # IO/Placement Constraints (.qsf) ------------------------------------------------------------------ # IO location cons... | 2.055563 | 2 |
arxiv/canonical/util.py | arXiv/arxiv-canonical | 5 | 9679 | <gh_stars>1-10
"""Various helpers and utilities that don't belong anywhere else."""
from typing import Dict, Generic, TypeVar
KeyType = TypeVar('KeyType')
ValueType = TypeVar('ValueType')
class GenericMonoDict(Dict[KeyType, ValueType]):
"""A dict with specific key and value types."""
def __getitem__(self, ... | """Various helpers and utilities that don't belong anywhere else."""
from typing import Dict, Generic, TypeVar
KeyType = TypeVar('KeyType')
ValueType = TypeVar('ValueType')
class GenericMonoDict(Dict[KeyType, ValueType]):
"""A dict with specific key and value types."""
def __getitem__(self, key: KeyType) -... | en | 0.931112 | Various helpers and utilities that don't belong anywhere else. A dict with specific key and value types. | 2.975055 | 3 |
records/urls.py | Glucemy/Glucemy-back | 0 | 9680 | from rest_framework.routers import DefaultRouter
from records.views import RecordViewSet
router = DefaultRouter()
router.register('', RecordViewSet, basename='records')
urlpatterns = router.urls
| from rest_framework.routers import DefaultRouter
from records.views import RecordViewSet
router = DefaultRouter()
router.register('', RecordViewSet, basename='records')
urlpatterns = router.urls
| none | 1 | 1.67265 | 2 | |
polystores/stores/azure_store.py | polyaxon/polystores | 50 | 9681 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import os
from rhea import RheaError
from rhea import parser as rhea_parser
from azure.common import AzureHttpError
from azure.storage.blob.models import BlobPrefix
from polystores.clients.azure_client import get_blob_service_c... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import os
from rhea import RheaError
from rhea import parser as rhea_parser
from azure.common import AzureHttpError
from azure.storage.blob.models import BlobPrefix
from polystores.clients.azure_client import get_blob_service_c... | en | 0.525908 | # -*- coding: utf-8 -*- # pylint:disable=arguments-differ Azure store Service. # pylint:disable=protected-access Sets a new Blob service connection. Args: account_name: `str`. The storage account name. account_key: `str`. The storage account key. connection_string: `str`. If specified, ... | 2.078295 | 2 |
analysis/webservice/NexusHandler.py | dataplumber/nexus | 23 | 9682 | """
Copyright (c) 2016 Jet Propulsion Laboratory,
California Institute of Technology. All rights reserved
"""
import sys
import numpy as np
import logging
import time
import types
from datetime import datetime
from netCDF4 import Dataset
from nexustiles.nexustiles import NexusTileService
from webservice.webmodel impor... | """
Copyright (c) 2016 Jet Propulsion Laboratory,
California Institute of Technology. All rights reserved
"""
import sys
import numpy as np
import logging
import time
import types
from datetime import datetime
from netCDF4 import Dataset
from nexustiles.nexustiles import NexusTileService
from webservice.webmodel impor... | en | 0.457101 | Copyright (c) 2016 Jet Propulsion Laboratory, California Institute of Technology. All rights reserved #frmtdTime = datetime.fromtimestamp(entry["time"] ).strftime("%Y-%m") # TODO Pool and Job are forced to a 1-to-1 relationship ################################################################## # Temporary workaround u... | 2.323814 | 2 |
utils/box/metric.py | ming71/SLA | 9 | 9683 | import numpy as np
from collections import defaultdict, Counter
from .rbbox_np import rbbox_iou
def get_ap(recall, precision):
recall = [0] + list(recall) + [1]
precision = [0] + list(precision) + [0]
for i in range(len(precision) - 1, 0, -1):
precision[i - 1] = max(precision[i - 1], precision[i... | import numpy as np
from collections import defaultdict, Counter
from .rbbox_np import rbbox_iou
def get_ap(recall, precision):
recall = [0] + list(recall) + [1]
precision = [0] + list(precision) + [0]
for i in range(len(precision) - 1, 0, -1):
precision[i - 1] = max(precision[i - 1], precision[i... | en | 0.433151 | # [[index, bbox, score, label], ...] | 1.954177 | 2 |
app.py | winstonschroeder/setlistmanager | 0 | 9684 | <filename>app.py
import logging
import pygame
from app import *
from pygame.locals import *
from werkzeug.serving import run_simple
from web import webapp as w
import data_access as da
logging.basicConfig(filename='setlistmanager.log', level=logging.DEBUG)
SCREEN_WIDTH = 160
SCREEN_HEIGHT = 128
class Button:
pa... | <filename>app.py
import logging
import pygame
from app import *
from pygame.locals import *
from werkzeug.serving import run_simple
from web import webapp as w
import data_access as da
logging.basicConfig(filename='setlistmanager.log', level=logging.DEBUG)
SCREEN_WIDTH = 160
SCREEN_HEIGHT = 128
class Button:
pa... | en | 0.679281 | Create a text object. # Color('white') # 'Free Sans' # self.words = [word.split(' ') for word in self.text.splitlines()] # 2D array where each row is a list of words. # self.space = self.font.size(' ')[0] # The width of a space. # max_width, max_height = self.surface.get_size() # x, y = self.pos # for line in self.wo... | 2.959588 | 3 |
sim_keypoints.py | Praznat/annotationmodeling | 8 | 9685 | import json
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import simulation
from eval_functions import oks_score_multi
import utils
def alter_location(points, x_offset, y_offset):
x, y = points.T
return np.array([x + x_offset, y + y_offset]).T
def alter_rotation(points, radians):... | import json
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import simulation
from eval_functions import oks_score_multi
import utils
def alter_location(points, x_offset, y_offset):
x, y = points.T
return np.array([x + x_offset, y + y_offset]).T
def alter_rotation(points, radians):... | none | 1 | 2.409869 | 2 | |
local/controller.py | Loptt/home-automation-system | 0 | 9686 | <reponame>Loptt/home-automation-system
import requests
import time
import os
import sys
import json
import threading
from getpass import getpass
import schedule
import event as e
import configuration as c
import RPi.GPIO as GPIO
#SERVER_URL = "https://home-automation-289621.uc.r.appspot.com"
#SERVER_URL = "http://127.... | import requests
import time
import os
import sys
import json
import threading
from getpass import getpass
import schedule
import event as e
import configuration as c
import RPi.GPIO as GPIO
#SERVER_URL = "https://home-automation-289621.uc.r.appspot.com"
#SERVER_URL = "http://127.0.0.1:4747"
SERVER_URL = "http://192.16... | en | 0.580712 | #SERVER_URL = "https://home-automation-289621.uc.r.appspot.com" #SERVER_URL = "http://127.0.0.1:4747" # Next day calculation # Same day calculation # Initialize separate thread to run scheduling jobs | 2.947129 | 3 |
src/graphql_sqlalchemy/graphql_types.py | gzzo/graphql-sqlalchemy | 12 | 9687 | from typing import Dict, Union
from graphql import (
GraphQLBoolean,
GraphQLFloat,
GraphQLInputField,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLScalarType,
GraphQLString,
)
from sqlalchemy import ARRAY, Boolean, Float, Integer
from sqlalchemy.dialects.postgresql import ARRAY as PG... | from typing import Dict, Union
from graphql import (
GraphQLBoolean,
GraphQLFloat,
GraphQLInputField,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLScalarType,
GraphQLString,
)
from sqlalchemy import ARRAY, Boolean, Float, Integer
from sqlalchemy.dialects.postgresql import ARRAY as PG... | none | 1 | 2.301189 | 2 | |
Knapsack.py | byterubpay/mininero1 | 182 | 9688 | <reponame>byterubpay/mininero1
import Crypto.Random.random as rand
import itertools
import math #for log
import sys
def decomposition(i):
#from stack exchange, don't think it's uniform
while i > 0:
n = rand.randint(1, i)
yield n
i -= n
def Decomposition(i):
while True:
l = l... | import Crypto.Random.random as rand
import itertools
import math #for log
import sys
def decomposition(i):
#from stack exchange, don't think it's uniform
while i > 0:
n = rand.randint(1, i)
yield n
i -= n
def Decomposition(i):
while True:
l = list(decomposition(i))
i... | en | 0.884011 | #for log #from stack exchange, don't think it's uniform #home-brewed, returns no duplicates, includes the number d #a.append(d) #print("a", a) #print(t, a) #print("b", b) #a combination of both methods, designed to get some smaller values #fuzz is an optional amount to fuzz the transaction by #so if you start with a bi... | 2.883427 | 3 |
drought_impact_forecasting/models/model_parts/Conv_Transformer.py | rudolfwilliam/satellite_image_forecasting | 4 | 9689 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .shared import Conv_Block
from ..utils.utils import zeros, mean_cube, last_frame, ENS
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def f... | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .shared import Conv_Block
from ..utils.utils import zeros, mean_cube, last_frame, ENS
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def f... | en | 0.734672 | # important note: shared convolution is intentional here # 3 times num_hidden for out_channels due to queries, keys & values # only 2 times num_hidden for keys & values # s is num queries, t is num keys/values # x correspond to queries # concatenate queries and keys for cross-channel convolution # only feed in 'previou... | 2.226383 | 2 |
tests/test_clients.py | rodrigoapereira/python-hydra-sdk | 0 | 9690 | # Copyright (C) 2017 O.S. Systems Software LTDA.
# This software is released under the MIT License
import unittest
from hydra import Hydra, Client
class ClientsTestCase(unittest.TestCase):
def setUp(self):
self.hydra = Hydra('http://localhost:4444', 'client', 'secret')
self.client = Client(
... | # Copyright (C) 2017 O.S. Systems Software LTDA.
# This software is released under the MIT License
import unittest
from hydra import Hydra, Client
class ClientsTestCase(unittest.TestCase):
def setUp(self):
self.hydra = Hydra('http://localhost:4444', 'client', 'secret')
self.client = Client(
... | en | 0.846674 | # Copyright (C) 2017 O.S. Systems Software LTDA. # This software is released under the MIT License | 2.556292 | 3 |
test/PR_test/unit_test/backend/test_binary_crossentropy.py | Phillistan16/fastestimator | 0 | 9691 | <gh_stars>0
# Copyright 2020 The FastEstimator Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | # Copyright 2020 The FastEstimator Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | en | 0.806703 | # Copyright 2020 The FastEstimator Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl... | 2.116326 | 2 |
ats_hex.py | kyeser/scTools | 0 | 9692 | <reponame>kyeser/scTools
#!/usr/bin/env python
from scTools import interval, primeForm
from scTools.rowData import ats
from scTools.scData import *
count = 1
for w in ats:
prime = primeForm(w[0:6])
print '%3d\t' % count,
for x in w:
print '%X' % x,
print ' ',
intervals = interval(w)
... | #!/usr/bin/env python
from scTools import interval, primeForm
from scTools.rowData import ats
from scTools.scData import *
count = 1
for w in ats:
prime = primeForm(w[0:6])
print '%3d\t' % count,
for x in w:
print '%X' % x,
print ' ',
intervals = interval(w)
for y in intervals:
... | ru | 0.26433 | #!/usr/bin/env python | 3.280977 | 3 |
src/precon/commands.py | Albert-91/precon | 0 | 9693 | import asyncio
import click
from precon.devices_handlers.distance_sensor import show_distance as show_distance_func
from precon.remote_control import steer_vehicle, Screen
try:
import RPi.GPIO as GPIO
except (RuntimeError, ModuleNotFoundError):
import fake_rpi
GPIO = fake_rpi.RPi.GPIO
@click.command(n... | import asyncio
import click
from precon.devices_handlers.distance_sensor import show_distance as show_distance_func
from precon.remote_control import steer_vehicle, Screen
try:
import RPi.GPIO as GPIO
except (RuntimeError, ModuleNotFoundError):
import fake_rpi
GPIO = fake_rpi.RPi.GPIO
@click.command(n... | none | 1 | 2.741586 | 3 | |
midway.py | sjtichenor/midway-ford | 0 | 9694 | <reponame>sjtichenor/midway-ford
import csv
import string
import ftplib
import math
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expect... | import csv
import string
import ftplib
import math
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import sqlite... | en | 0.693517 | # Misc stuff # FMC Dealer Scrapes #returns random float roughly between 1.5 and 2.75 # Switch between MyLot/States #Switch default search back to Dealership Proximity # Check what default is currently set to #print('Setting After:', currentSetting) This doesn't work.. #Logs into fmcdealer and returns browser # Fire u... | 2.552218 | 3 |
monolithe/generators/sdkgenerator.py | edwinfeener/monolithe | 18 | 9695 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# no... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# no... | en | 0.725448 | # -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent Inc # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # no... | 1.239567 | 1 |
rllab-taewoo/rllab/plotter/plotter.py | kyuhoJeong11/GrewRL | 0 | 9696 | import atexit
import sys
if sys.version_info[0] == 2:
from Queue import Empty
else:
from queue import Empty
from multiprocessing import Process, Queue
from rllab.sampler.utils import rollout
import numpy as np
__all__ = [
'init_worker',
'init_plot',
'update_plot'
]
process = None
queue = None
de... | import atexit
import sys
if sys.version_info[0] == 2:
from Queue import Empty
else:
from queue import Empty
from multiprocessing import Process, Queue
from rllab.sampler.utils import rollout
import numpy as np
__all__ = [
'init_worker',
'init_plot',
'update_plot'
]
process = None
queue = None
de... | en | 0.10871 | # Only fetch the last message of each type # env.start_viewer() ###################init_worker") | 2.389042 | 2 |
OpenCV/bookIntroCV_008_binarizacao.py | fotavio16/PycharmProjects | 0 | 9697 | <gh_stars>0
'''
Livro-Introdução-a-Visão-Computacional-com-Python-e-OpenCV-3
Repositório de imagens
https://github.com/opencv/opencv/tree/master/samples/data
'''
import cv2
import numpy as np
from matplotlib import pyplot as plt
#import mahotas
VERMELHO = (0, 0, 255)
VERDE = (0, 255, 0)
AZUL = (255, 0, 0)
AMARELO... | '''
Livro-Introdução-a-Visão-Computacional-com-Python-e-OpenCV-3
Repositório de imagens
https://github.com/opencv/opencv/tree/master/samples/data
'''
import cv2
import numpy as np
from matplotlib import pyplot as plt
#import mahotas
VERMELHO = (0, 0, 255)
VERDE = (0, 255, 0)
AZUL = (255, 0, 0)
AMARELO = (0, 255, ... | pt | 0.444198 | Livro-Introdução-a-Visão-Computacional-com-Python-e-OpenCV-3 Repositório de imagens https://github.com/opencv/opencv/tree/master/samples/data #import mahotas # Flag 1 = Color, 0 = Gray, -1 = Unchanged # Diminui a imagem #Binarização com limiar # aplica blur resultado = np.vstack([ np.hstack([suave, bin]), np.h... | 3.048664 | 3 |
djangito/backends.py | mechanicbuddy/djangito | 0 | 9698 | <reponame>mechanicbuddy/djangito
import base64
import json
import jwt
import requests
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
USER_MODEL = get_user_model()
class ALBAuth(ModelBackend):
def authenticate(self, request... | import base64
import json
import jwt
import requests
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
USER_MODEL = get_user_model()
class ALBAuth(ModelBackend):
def authenticate(self, request, **kwargs):
if request:
... | en | 0.750759 | # Step 1: Get the key id from JWT headers (the kid field) # Step 2: Get the public key from regional endpoint # Step 3: Get the payload | 2.290329 | 2 |
data_profiler/labelers/regex_model.py | gme5078/data-profiler | 0 | 9699 | <reponame>gme5078/data-profiler<gh_stars>0
import json
import os
import sys
import re
import copy
import numpy as np
from data_profiler.labelers.base_model import BaseModel
from data_profiler.labelers.base_model import AutoSubRegistrationMeta
_file_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(_fi... | import json
import os
import sys
import re
import copy
import numpy as np
from data_profiler.labelers.base_model import BaseModel
from data_profiler.labelers.base_model import AutoSubRegistrationMeta
_file_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(_file_dir)
class RegexModel(BaseModel, metac... | en | 0.573184 | Regex Model Initializer. Example regex_patterns: regex_patterns = { "LABEL_1": [ "LABEL_1_pattern_1", "LABEL_1_pattern_2", ... ], "LABEL_2": [ "LABEL_2_pattern_1", ... | 2.316002 | 2 |