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 |
|---|---|---|---|---|---|---|---|---|---|---|
homeassistant/components/brother/const.py | tbarbette/core | 1 | 6626851 | <reponame>tbarbette/core<filename>homeassistant/components/brother/const.py<gh_stars>1-10
"""Constants for Brother integration."""
from homeassistant.const import ATTR_ICON, PERCENTAGE
ATTR_BELT_UNIT_REMAINING_LIFE = "belt_unit_remaining_life"
ATTR_BLACK_DRUM_COUNTER = "black_drum_counter"
ATTR_BLACK_DRUM_REMAINING_LI... | """Constants for Brother integration."""
from homeassistant.const import ATTR_ICON, PERCENTAGE
ATTR_BELT_UNIT_REMAINING_LIFE = "belt_unit_remaining_life"
ATTR_BLACK_DRUM_COUNTER = "black_drum_counter"
ATTR_BLACK_DRUM_REMAINING_LIFE = "black_drum_remaining_life"
ATTR_BLACK_DRUM_REMAINING_PAGES = "black_drum_remaining_p... | en | 0.754871 | Constants for Brother integration. | 1.361719 | 1 |
test/integration/test_connectors.py | cool-RR/py2neo | 0 | 6626852 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2020, <NAME>
#
# 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 re... | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2020, <NAME>
#
# 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 re... | en | 0.368014 | #!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2020, <NAME> # # 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 req... | 2.223907 | 2 |
chapter17/0_starting_point/plot_imu_fusion.py | dannystaple/Learn-Robotics-Programming-Second-Edition | 19 | 6626853 | <reponame>dannystaple/Learn-Robotics-Programming-Second-Edition<filename>chapter17/0_starting_point/plot_imu_fusion.py<gh_stars>10-100
import vpython as vp
from robot_imu import RobotImu, ImuFusion
from delta_timer import DeltaTimer
import imu_settings
imu = RobotImu(gyro_offsets=imu_settings.gyro_offsets,
... | import vpython as vp
from robot_imu import RobotImu, ImuFusion
from delta_timer import DeltaTimer
import imu_settings
imu = RobotImu(gyro_offsets=imu_settings.gyro_offsets,
mag_offsets=imu_settings.mag_offsets)
fusion = ImuFusion(imu)
vp.graph(xmin=0, xmax=60, scroll=True)
graph_pitch = vp.gcurve(color... | none | 1 | 2.406602 | 2 | |
src/image_loader.py | BastiHz/epicycles | 1 | 6626854 | <filename>src/image_loader.py
# TODO: Load an image file. Ideally the path should be a single pixel wide
# and must be of a single color. Construct the point list either by using
# nearest neighbor search or try finding the shortest path using
# a travelling salesman approach.
# Return the sorted list of coordinates... | <filename>src/image_loader.py
# TODO: Load an image file. Ideally the path should be a single pixel wide
# and must be of a single color. Construct the point list either by using
# nearest neighbor search or try finding the shortest path using
# a travelling salesman approach.
# Return the sorted list of coordinates... | en | 0.813379 | # TODO: Load an image file. Ideally the path should be a single pixel wide # and must be of a single color. Construct the point list either by using # nearest neighbor search or try finding the shortest path using # a travelling salesman approach. # Return the sorted list of coordinates. | 3.156735 | 3 |
src/visual_encoders.py | lukoshkin/text2video | 20 | 6626855 | <filename>src/visual_encoders.py
import torch
from torch import nn
from torch.nn.utils import spectral_norm
from blocks import DBlock
from convgru import ConvGRU
from functools import partial
def SN(sn):
return spectral_norm if sn else lambda x: x
class VideoEncoder(nn.Module):
def __init__(self, in_colors... | <filename>src/visual_encoders.py
import torch
from torch import nn
from torch.nn.utils import spectral_norm
from blocks import DBlock
from convgru import ConvGRU
from functools import partial
def SN(sn):
return spectral_norm if sn else lambda x: x
class VideoEncoder(nn.Module):
def __init__(self, in_colors... | en | 0.286377 | images # images.shape (N, k, C, H, W) # images.shape (N*k, C, H, W) # H.shape (N*k, base_width*32, 1, 1) # output.shape (N, k, base_width*32) | 2.253807 | 2 |
Scripts/articletts.py | SainathPoojary/PyAutomate | 14 | 6626856 | from os import system
from time import sleep
import requests
from bs4 import BeautifulSoup
from gtts import gTTS
from playsound import playsound
another_article = ""
while another_article != "n":
system("clear")
url = input("Enter article url: ")
page = requests.get(url).text
soup = BeautifulSoup(page... | from os import system
from time import sleep
import requests
from bs4 import BeautifulSoup
from gtts import gTTS
from playsound import playsound
another_article = ""
while another_article != "n":
system("clear")
url = input("Enter article url: ")
page = requests.get(url).text
soup = BeautifulSoup(page... | none | 1 | 3.123392 | 3 | |
setup.py | vubon/pyfi | 2 | 6626857 | <reponame>vubon/pyfi<filename>setup.py
import os
import re
from setuptools import setup, find_packages
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
def get_version(package: str) -> str:
with open(os.path.join(BASE_DIR, f'{package}/__version__.py')) as version:
version = version.readline()
m... | import os
import re
from setuptools import setup, find_packages
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
def get_version(package: str) -> str:
with open(os.path.join(BASE_DIR, f'{package}/__version__.py')) as version:
version = version.readline()
match = re.search("__version__ = ['\"]([... | en | 0.607496 | # 2 - Pre-Alpha, 3 - Alpha, 4 - Beta, 5 - Production/Stable | 1.934901 | 2 |
experiments/BBVI/planar_robot.py | OlegArenz/tensorflow_VI | 0 | 6626858 | <filename>experiments/BBVI/planar_robot.py
from experiments.target_lnpdfs.Planar_Robot import make_four_goal, make_single_goal
from experiments.BBVI.experiment_script import sample, construct_initial_mixture
import os
import numpy as np
if __name__ == "__main__":
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
num_d... | <filename>experiments/BBVI/planar_robot.py
from experiments.target_lnpdfs.Planar_Robot import make_four_goal, make_single_goal
from experiments.BBVI.experiment_script import sample, construct_initial_mixture
import os
import numpy as np
if __name__ == "__main__":
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
num_d... | none | 1 | 2.066332 | 2 | |
tests/test_compose_array.py | dgketchum/IrrMapper | 6 | 6626859 | <filename>tests/test_compose_array.py
# ===============================================================================
# Copyright 2018 dgketchum
#
# Licensed under the Apache License, Version 2.(the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License a... | <filename>tests/test_compose_array.py
# ===============================================================================
# Copyright 2018 dgketchum
#
# Licensed under the Apache License, Version 2.(the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License a... | en | 0.72253 | # =============================================================================== # Copyright 2018 dgketchum # # Licensed under the Apache License, Version 2.(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/L... | 2.026507 | 2 |
jsk_2015_05_baxter_apc/node_scripts/sift_matcher_for_imgs.py | pazeshun/jsk_apc | 0 | 6626860 | #!/usr/bin/env python
#
"""
This script is to visualize how match sift features are matched between
an image and camera frame.
Usage
-----
$ roslaunch roseus_tutorials usb-camera.launch
$ roslaunch jsk_2015_05_baxter_apc sift_matcher_for_imgs.launch
$ rosrun image_view image_view image:=/sift_matcher_for_... | #!/usr/bin/env python
#
"""
This script is to visualize how match sift features are matched between
an image and camera frame.
Usage
-----
$ roslaunch roseus_tutorials usb-camera.launch
$ roslaunch jsk_2015_05_baxter_apc sift_matcher_for_imgs.launch
$ rosrun image_view image_view image:=/sift_matcher_for_... | en | 0.667253 | #!/usr/bin/env python # This script is to visualize how match sift features are matched between an image and camera frame. Usage ----- $ roslaunch roseus_tutorials usb-camera.launch $ roslaunch jsk_2015_05_baxter_apc sift_matcher_for_imgs.launch $ rosrun image_view image_view image:=/sift_matcher_for_imgs... | 2.834453 | 3 |
drdown/users/tests/test_view_health_team.py | fga-gpp-mds/2018.1-Cris-Down | 11 | 6626861 | from test_plus.test import TestCase
from django.test import RequestFactory
from django.test.client import Client
from ..models.model_health_team import HealthTeam
class TestViewHealthTeam (TestCase):
"""
Test if View Health_Team is working correctly
"""
def setUp(self):
"""
This met... | from test_plus.test import TestCase
from django.test import RequestFactory
from django.test.client import Client
from ..models.model_health_team import HealthTeam
class TestViewHealthTeam (TestCase):
"""
Test if View Health_Team is working correctly
"""
def setUp(self):
"""
This met... | en | 0.827258 | Test if View Health_Team is working correctly This method will run before any test. Test if the view health team is passing the data correctly | 2.376943 | 2 |
sets/set-symmetric-difference-operation.py | vcelis/hackerrank-python | 0 | 6626862 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Title : Set .symmetric_difference() Operation
Subdomain : Sets
Author : <NAME>
Created : 20 July 2018
https://www.hackerrank.com/challenges/py-set-symmetric-difference-operation/problem
"""
if __name__ == '__main__':
_ = inpu... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Title : Set .symmetric_difference() Operation
Subdomain : Sets
Author : <NAME>
Created : 20 July 2018
https://www.hackerrank.com/challenges/py-set-symmetric-difference-operation/problem
"""
if __name__ == '__main__':
_ = input()
set_... | en | 0.632722 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Title : Set .symmetric_difference() Operation Subdomain : Sets Author : <NAME> Created : 20 July 2018 https://www.hackerrank.com/challenges/py-set-symmetric-difference-operation/problem | 3.398071 | 3 |
scrapper/migrations/0008_auto_20200912_1324.py | Dalakoti07/optimal-price-back-end | 0 | 6626863 | <reponame>Dalakoti07/optimal-price-back-end<filename>scrapper/migrations/0008_auto_20200912_1324.py
# Generated by Django 3.1 on 2020-09-12 07:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('scrapper', '0007_productde... | # Generated by Django 3.1 on 2020-09-12 07:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('scrapper', '0007_productdetails_review'),
]
operations = [
migrations.RemoveField(
model_name='pr... | en | 0.802738 | # Generated by Django 3.1 on 2020-09-12 07:54 | 1.584083 | 2 |
src/m3u_gen_acestream.py | SCP002/m3u-gen-ttv | 1 | 6626864 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from os import chdir
from socket import gethostbyname, gethostname
from sys import path, stderr
from time import sleep
from traceback import format_exc, print_exc
from channel.channel_handler import ChannelHandler
from config.config ... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from os import chdir
from socket import gethostbyname, gethostname
from sys import path, stderr
from time import sleep
from traceback import format_exc, print_exc
from channel.channel_handler import ChannelHandler
from config.config ... | en | 0.734661 | #!/usr/bin/python3 # -*- coding: utf-8 -*- # If remain at least one DataSet to process # If do not have cached channels for the next DataSet # Main start point. # noinspection PyBroadException | 2.36553 | 2 |
src/pansim/cli.py | parantapa/pansim | 0 | 6626865 | """PanSim Command Line Interface."""
import click
import click_completion
from .simplesim import simplesim
from .distsim import distsim
@click.group()
def cli():
"""PanSim: The Pandemic Simulator."""
cli.add_command(simplesim)
cli.add_command(distsim)
click_completion.init()
| """PanSim Command Line Interface."""
import click
import click_completion
from .simplesim import simplesim
from .distsim import distsim
@click.group()
def cli():
"""PanSim: The Pandemic Simulator."""
cli.add_command(simplesim)
cli.add_command(distsim)
click_completion.init()
| en | 0.564407 | PanSim Command Line Interface. PanSim: The Pandemic Simulator. | 1.842339 | 2 |
core/network/ViTAE_S/NormalCell.py | ViTAE-Transformer/ViTAE-Transformer-Matting | 8 | 6626866 | <reponame>ViTAE-Transformer/ViTAE-Transformer-Matting
# Copyright (c) [2012]-[2021] Shanghai Yitu Technology Co., Ltd.
#
# This source code is licensed under the Clear BSD License
# LICENSE file in the root directory of this file
# All rights reserved.
"""
Borrow from timm(https://github.com/rwightman/pytorch-ima... | # Copyright (c) [2012]-[2021] Shanghai Yitu Technology Co., Ltd.
#
# This source code is licensed under the Clear BSD License
# LICENSE file in the root directory of this file
# All rights reserved.
"""
Borrow from timm(https://github.com/rwightman/pytorch-image-models)
"""
import torch
import torch.nn as nn
... | en | 0.710244 | # Copyright (c) [2012]-[2021] Shanghai Yitu Technology Co., Ltd. # # This source code is licensed under the Clear BSD License # LICENSE file in the root directory of this file # All rights reserved. Borrow from timm(https://github.com/rwightman/pytorch-image-models) # for stable in division # part of the function is bo... | 2.685949 | 3 |
beta_rec/datasets/movielens.py | ChaosCodes/beta-recsys | 0 | 6626867 | <gh_stars>0
import os
import numpy as np
import pandas as pd
from beta_rec.datasets.dataset_base import DatasetBase
from beta_rec.utils.constants import (
DEFAULT_ITEM_COL,
DEFAULT_RATING_COL,
DEFAULT_TIMESTAMP_COL,
DEFAULT_USER_COL,
)
# download_url
ML_100K_URL = r"http://files.grouplens.org/dataset... | import os
import numpy as np
import pandas as pd
from beta_rec.datasets.dataset_base import DatasetBase
from beta_rec.utils.constants import (
DEFAULT_ITEM_COL,
DEFAULT_RATING_COL,
DEFAULT_TIMESTAMP_COL,
DEFAULT_USER_COL,
)
# download_url
ML_100K_URL = r"http://files.grouplens.org/datasets/movielens/... | en | 0.858973 | # download_url # processed data url # indicators of the colunmn name # raw dataset # dataset dir under temporal split # dataset dir under leave-one-out split Movielens 100k Dataset. Init Movielens_100k Class. Preprocess the raw file. Preprocess the file downloaded via the url, convert it to a dataframe consist... | 2.227994 | 2 |
definitions/srcwriter.py | Atlamillias/pixl-engine | 6 | 6626868 | from __future__ import annotations
from inspect import Parameter, formatannotation, _empty
from typing import Union
from io import StringIO
from pathlib import Path
import functools
class _PyTextList(list):
def append(self, value):
if not isinstance(value, PyTextObject):
value = PyTextObject(v... | from __future__ import annotations
from inspect import Parameter, formatannotation, _empty
from typing import Union
from io import StringIO
from pathlib import Path
import functools
class _PyTextList(list):
def append(self, value):
if not isinstance(value, PyTextObject):
value = PyTextObject(v... | en | 0.607638 | An object representing any Python object. It can be represented in a file-friendly text format. Args: * obj (object): The object or object reference. Can also be a string. * namespace (PyNamespace): The namespace for <obj>. An object representing a Python namespace (import, etc). It can... | 3.016671 | 3 |
samples/python/src/main/service/ZoweClient.py | BroadcomMFD/test4z | 6 | 6626869 | # ZOWE and Z/OSMF client for the job submission
import sys
sys.path.append("../../main")
from zowe.zos_console_for_zowe_sdk import Console
from zowe.zos_jobs_for_zowe_sdk import Jobs
from polling import TimeoutException, poll
from utility import get_zosmf_connection, get_polling_timeout, get_polling_interval
# Job su... | # ZOWE and Z/OSMF client for the job submission
import sys
sys.path.append("../../main")
from zowe.zos_console_for_zowe_sdk import Console
from zowe.zos_jobs_for_zowe_sdk import Jobs
from polling import TimeoutException, poll
from utility import get_zosmf_connection, get_polling_timeout, get_polling_interval
# Job su... | en | 0.755556 | # ZOWE and Z/OSMF client for the job submission # Job submission through ZOSMF # Waits until the job return code and returns it # @dataset - JCL dataset with the job/s # Python polling check_success method, # checks the job execution. # @response - polling request response # @returns - boolean status of the polling met... | 2.269495 | 2 |
cqi_cpp/src/wrapper/setup.py | AMR-/Conservative-Q-Improvement | 0 | 6626870 | <filename>cqi_cpp/src/wrapper/setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
file_list = ["qtree_wrapper.pyx", "../discrete.cpp", "../box.cpp", "../leafsplit.cpp", "../qtreeleaf.cpp", "../qtreeinternal.cpp", "../qtree.cpp", "../state.cpp", "..... | <filename>cqi_cpp/src/wrapper/setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
file_list = ["qtree_wrapper.pyx", "../discrete.cpp", "../box.cpp", "../leafsplit.cpp", "../qtreeleaf.cpp", "../qtreeinternal.cpp", "../qtree.cpp", "../state.cpp", "..... | none | 1 | 1.479067 | 1 | |
src/Compile.py | laubonghaudoi/Cantonese | 0 | 6626871 | <gh_stars>0
class Compile(object):
def __init__(self, ast, target, path) -> None:
self.ast = ast
self.target = target
self.path = path
self.TO_JS_CODE = ""
self.TO_C_CODE = ""
self.TO_ASM_CODE = ""
if self.target == "js":
self.run_js(self.ast)
... | class Compile(object):
def __init__(self, ast, target, path) -> None:
self.ast = ast
self.target = target
self.path = path
self.TO_JS_CODE = ""
self.TO_C_CODE = ""
self.TO_ASM_CODE = ""
if self.target == "js":
self.run_js(self.ast)
if sel... | none | 1 | 2.732922 | 3 | |
configure.py | StarMKWii/mkw-sp | 0 | 6626872 | #!/usr/bin/env python3
from argparse import ArgumentParser
import io
import os, sys
from vendor.ninja_syntax import Writer
try:
import json5
del json5
except ModuleNotFoundError:
raise SystemExit("Error: pyjson5 not found. Please install it with `python -m pip install json5`")
import subprocess
parser ... | #!/usr/bin/env python3
from argparse import ArgumentParser
import io
import os, sys
from vendor.ninja_syntax import Writer
try:
import json5
del json5
except ModuleNotFoundError:
raise SystemExit("Error: pyjson5 not found. Please install it with `python -m pip install json5`")
import subprocess
parser ... | en | 0.639917 | #!/usr/bin/env python3 # https://stackoverflow.com/questions/14989858/get-the-current-git-hash-in-a-python-script/14989911#14989911 # '-fplan9-extensions', # '-Werror=implicit-function-declaration', # '-Werror=incompatible-pointer-types', # Keyboard module # # Security module # Settings module # # Storage module # # En... | 2.283672 | 2 |
alveo/examples/deployment_modes/test_classify.py | dendisuhubdy/Vitis-AI | 3 | 6626873 | <reponame>dendisuhubdy/Vitis-AI
#!/usr/bin/env python
# Copyright 2019 Xilinx 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
#
# Unles... | #!/usr/bin/env python
# Copyright 2019 Xilinx 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 ... | en | 0.824791 | #!/usr/bin/env python # Copyright 2019 Xilinx 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 ... | 1.85907 | 2 |
PnP/DenoiserScaling.py | sebemery/Lipschitz-constrained-neural-networks | 0 | 6626874 | import os
import numpy as np
import argparse
import json
import torch
import cv2
import scipy.io as sio
import matplotlib.pyplot as plt
import sys
sys.path.append('..')
import PnP
import models
def parse_arguments():
parser = argparse.ArgumentParser(description='PyTorch Training')
parser.add_argument('--confi... | import os
import numpy as np
import argparse
import json
import torch
import cv2
import scipy.io as sio
import matplotlib.pyplot as plt
import sys
sys.path.append('..')
import PnP
import models
def parse_arguments():
parser = argparse.ArgumentParser(description='PyTorch Training')
parser.add_argument('--confi... | en | 0.303107 | # ---- input arguments ---- # CONFIG -> assert if config is here # ---- load the model ---- # create the output directory and return the path to it # ---- load the ground truth ---- # ---- load mask matrix ---- # ---- load noises ----- # ---- set options ----- # ---- plug and play !!! ----- # directory # ---- print res... | 2.340425 | 2 |
20160305_2.py | JaeGyu/PythonEx_1 | 0 | 6626875 | <filename>20160305_2.py<gh_stars>0
#_*_ coding: utf-8 _*_
class MyClass:
def set(self, v): #self라는 인자가 있으면 이 메서드는 인스턴스 메서드임을 나타낸다.
self.value = v
def get(self):
return self.value
class Simple:
pass
t = MyClass()
print t
t.set("hello")
print t.get()
print t.value
c = MyClass()
c.set("egg")
print c.get()
pri... | <filename>20160305_2.py<gh_stars>0
#_*_ coding: utf-8 _*_
class MyClass:
def set(self, v): #self라는 인자가 있으면 이 메서드는 인스턴스 메서드임을 나타낸다.
self.value = v
def get(self):
return self.value
class Simple:
pass
t = MyClass()
print t
t.set("hello")
print t.get()
print t.value
c = MyClass()
c.set("egg")
print c.get()
pri... | ko | 1.000049 | #_*_ coding: utf-8 _*_ #self라는 인자가 있으면 이 메서드는 인스턴스 메서드임을 나타낸다. #인스턴스 객체 없이 클래스에서 직접 호출 #인스턴스 객체를 통해서도 호출 가능 #클래스 D는 클래스 C를 상속한다. | 3.766464 | 4 |
VirtulizeOS/module.py | wuzirui/SchedulingLab | 0 | 6626876 | <filename>VirtulizeOS/module.py
import copy
from Schedulers import module
from .process import Process
import heapq
class Processor:
history = None
def __init__(self):
pass
def boot(self):
assert self.history is None, "already booted, shutdown() first"
self.histor... | <filename>VirtulizeOS/module.py
import copy
from Schedulers import module
from .process import Process
import heapq
class Processor:
history = None
def __init__(self):
pass
def boot(self):
assert self.history is None, "already booted, shutdown() first"
self.histor... | zh | 0.827203 | # 所有process加入待处理字典 # 判断是否有已经就绪者,加入就绪 # 每一次都要加一然后进入time_pulse | 2.592783 | 3 |
main.py | VSBoiko/python-basics | 0 | 6626877 | <reponame>VSBoiko/python-basics<gh_stars>0
from math import inf
from itertools import pairwise
class Point:
"""
Класс для представление точки на координатной плоскости
Атрибуты
x (int): координата по оси X
y (int): координата по оси Y
key (str): ключ (короткое название на латинице... | from math import inf
from itertools import pairwise
class Point:
"""
Класс для представление точки на координатной плоскости
Атрибуты
x (int): координата по оси X
y (int): координата по оси Y
key (str): ключ (короткое название на латинице)
name (str): название
"""
... | ru | 0.966773 | Класс для представление точки на координатной плоскости Атрибуты x (int): координата по оси X y (int): координата по оси Y key (str): ключ (короткое название на латинице) name (str): название Устанавливает все необходимые атрибуты для объекта Point Параметры: x ... | 3.623612 | 4 |
app/api/domains/__init__.py | tsuuki/gulag | 4 | 6626878 | <reponame>tsuuki/gulag
from . import api
from . import ava
from . import cho
from . import map
from . import osu
| from . import api
from . import ava
from . import cho
from . import map
from . import osu | none | 1 | 1.087008 | 1 | |
config.py | SmartNetConf/SmartNetConf | 1 | 6626879 | # Builtin config values: http://flask.pocoo.org/docs/0.10/config/
DEBUG = True
HOST = '0.0.0.0'
PORT = 5000
LOGGING_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOGGING_LOCATION = 'smartnetconf_flask.log'
LOGGING_LEVEL = 'DEBUG'
| # Builtin config values: http://flask.pocoo.org/docs/0.10/config/
DEBUG = True
HOST = '0.0.0.0'
PORT = 5000
LOGGING_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOGGING_LOCATION = 'smartnetconf_flask.log'
LOGGING_LEVEL = 'DEBUG'
| en | 0.252248 | # Builtin config values: http://flask.pocoo.org/docs/0.10/config/ | 1.497754 | 1 |
pandas/io/formats/csvs.py | meeseeksmachine/pandas | 2 | 6626880 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Module for formatting output data into CSV files.
"""
from __future__ import print_function
import warnings
import csv as csvlib
from zipfile import ZipFile
import numpy as np
from pandas._libs import writers as libwriters
from pandas import compat
from pandas.compat imp... | # -*- coding: utf-8 -*-
"""
Module for formatting output data into CSV files.
"""
from __future__ import print_function
import warnings
import csv as csvlib
from zipfile import ZipFile
import numpy as np
from pandas._libs import writers as libwriters
from pandas import compat
from pandas.compat import StringIO, r... | en | 0.815127 | # -*- coding: utf-8 -*- Module for formatting output data into CSV files. # prevents crash in _csv # validate mi options # update columns to include possible multiplicity of dupes # and make sure sure cols is just a list of labels # save it # preallocate data 2d list # create the writer & save # GH 21227 internal compr... | 2.706453 | 3 |
cycli/buffer.py | erayon/cycli | 290 | 6626881 | from prompt_toolkit.buffer import Buffer
from prompt_toolkit.filters import Condition
class UserWantsOut(Exception):
pass
class CypherBuffer(Buffer):
def __init__(self, *args, **kwargs):
@Condition
def is_multiline():
return not self.user_wants_out(self.document.text)
super(self.__class__, se... | from prompt_toolkit.buffer import Buffer
from prompt_toolkit.filters import Condition
class UserWantsOut(Exception):
pass
class CypherBuffer(Buffer):
def __init__(self, *args, **kwargs):
@Condition
def is_multiline():
return not self.user_wants_out(self.document.text)
super(self.__class__, se... | none | 1 | 2.426115 | 2 | |
src/attributes/osm.py | Jugendhackt/SMArt | 4 | 6626882 | <reponame>Jugendhackt/SMArt
import datetime
from math import radians, cos, sin, asin, sqrt
import requests
class OSM:
def __init__(self):
self.OVERPASS_URL = "https://lz4.overpass-api.de/api/interpreter"
self.OSM_ID = 0
def get_data(self, attribute: str, req_time: int, lat: float, lon: float... | import datetime
from math import radians, cos, sin, asin, sqrt
import requests
class OSM:
def __init__(self):
self.OVERPASS_URL = "https://lz4.overpass-api.de/api/interpreter"
self.OSM_ID = 0
def get_data(self, attribute: str, req_time: int, lat: float, lon: float, distance: int) -> dict:
... | en | 0.282085 | # self.check_date('timestring', req_time//1000) # km [out:json][timeout:25]; ( node["shop"="{OSM.get_parent_class(attribute)}"](48.289,9.803,48.474,10.26); ); out body; | 3.157907 | 3 |
interp_Pwhile.py | IUCompilerCourse/python-student-support-code | 3 | 6626883 | <reponame>IUCompilerCourse/python-student-support-code
from ast import *
from interp_Pif import InterpPif
from utils import *
class InterpPwhile(InterpPif):
def interp_stmts(self, ss, env):
if len(ss) == 0:
return
match ss[0]:
case While(test, body, []):
while self.interp_exp(test, env):... | from ast import *
from interp_Pif import InterpPif
from utils import *
class InterpPwhile(InterpPif):
def interp_stmts(self, ss, env):
if len(ss) == 0:
return
match ss[0]:
case While(test, body, []):
while self.interp_exp(test, env):
self.interp_stmts(body, env)
retur... | none | 1 | 2.365899 | 2 | |
src/__init__.py | JordanRex/YAAML | 1 | 6626884 | # yaaml __init__.py
__version__ = '0.0.5'
__author__ = 'varunrajan'
__name__ = 'yaaml'
__org__ = '...'
# importing packages
import os as os
# the base packages
import collections # for the Counter function
import csv # for reading/writing csv files
import pandas as pd, numpy as np, time as time, gc as gc, bisect as ... | # yaaml __init__.py
__version__ = '0.0.5'
__author__ = 'varunrajan'
__name__ = 'yaaml'
__org__ = '...'
# importing packages
import os as os
# the base packages
import collections # for the Counter function
import csv # for reading/writing csv files
import pandas as pd, numpy as np, time as time, gc as gc, bisect as ... | en | 0.628452 | # yaaml __init__.py # importing packages # the base packages # for the Counter function # for reading/writing csv files # Evaluation of the model # hyperopt modules # modelling/clustering algorithms # import xgboost as xgb # import lightgbm as lgb # from sklearn.covariance import EllipticEnvelope # from sklearn.ensembl... | 1.906024 | 2 |
gladier_kanzus/tools/dials_stills.py | globus-gladier/kanzus_client | 0 | 6626885 | from gladier import GladierBaseTool, generate_flow_definition
def stills_process(**data):
import os
import subprocess
from subprocess import PIPE
proc_dir = data['proc_dir']
data_dir = data['data_dir']
input_files = data['input_files']
run_num = data['input_files'].split("_")[-2]
... | from gladier import GladierBaseTool, generate_flow_definition
def stills_process(**data):
import os
import subprocess
from subprocess import PIPE
proc_dir = data['proc_dir']
data_dir = data['data_dir']
input_files = data['input_files']
run_num = data['input_files'].split("_")[-2]
... | en | 0.958943 | ##Need to guarantee the worker is at the correct location.. | 2.250767 | 2 |
scripts/sell_unused_slots.py | DataBiosphere/azul | 17 | 6626886 | <gh_stars>10-100
"""
Delete BigQuery reservation resources if no ongoing reindex is detected.
"""
import argparse
from datetime import (
datetime,
timedelta,
)
import sys
import time
from typing import (
Dict,
FrozenSet,
Iterable,
List,
)
from azul import (
RequirementError,
cached_pro... | """
Delete BigQuery reservation resources if no ongoing reindex is detected.
"""
import argparse
from datetime import (
datetime,
timedelta,
)
import sys
import time
from typing import (
Dict,
FrozenSet,
Iterable,
List,
)
from azul import (
RequirementError,
cached_property,
config... | en | 0.77516 | Delete BigQuery reservation resources if no ongoing reindex is detected. # Minutes # Maximum number of contribution Lambda invocations per interval for a # reindexing to be considered inactive # Keep looping to log status of remaining lambdas Search Lambda functions for the names of contribution Lambdas. # FIXME: Elimi... | 2.157458 | 2 |
gtfspy/routing/test/test_forward_journey.py | Leo-Ryu/gtfspy | 118 | 6626887 | <gh_stars>100-1000
import unittest
from gtfspy.routing.forwardjourney import ForwardJourney
from gtfspy.routing.connection import Connection
class ForwardJourneyTest(unittest.TestCase):
def test_add_leg(self):
journey = ForwardJourney()
leg1 = Connection(departure_stop=0, arrival_stop=1, departu... | import unittest
from gtfspy.routing.forwardjourney import ForwardJourney
from gtfspy.routing.connection import Connection
class ForwardJourneyTest(unittest.TestCase):
def test_add_leg(self):
journey = ForwardJourney()
leg1 = Connection(departure_stop=0, arrival_stop=1, departure_time=0, arrival_... | none | 1 | 2.89887 | 3 | |
Scripts/simulation/objects/gallery_tuning.py | velocist/TS4CheatsInfo | 0 | 6626888 | # uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\objects\gallery_tuning.py
# Compiled at: 2019-09-03 17:10:04
# Size of source mod 2**32: 1108 bytes
... | # uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\objects\gallery_tuning.py
# Compiled at: 2019-09-03 17:10:04
# Size of source mod 2**32: 1108 bytes
... | en | 0.51459 | # uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\objects\gallery_tuning.py # Compiled at: 2019-09-03 17:10:04 # Size of source mod 2**32: 1108 bytes | 1.90311 | 2 |
src/app/db/models.py | pyronear/pyro-api | 8 | 6626889 | # Copyright (C) 2021, Pyronear contributors.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
import enum
from .session import Base
from sqlalchemy.sql import func
from sqlalchemy import Column, DateTime, ... | # Copyright (C) 2021, Pyronear contributors.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
import enum
from .session import Base
from sqlalchemy.sql import func
from sqlalchemy import Column, DateTime, ... | en | 0.789458 | # Copyright (C) 2021, Pyronear contributors. # This program is licensed under the Apache License version 2. # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. # index for fast lookup # Linked tables | 2.293704 | 2 |
oneflow/python/test/ops/test_fused_bias_add_gelu.py | wanghongsheng01/framework_enflame | 1 | 6626890 | <filename>oneflow/python/test/ops/test_fused_bias_add_gelu.py
"""
Copyright 2020 The OneFlow 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/... | <filename>oneflow/python/test/ops/test_fused_bias_add_gelu.py
"""
Copyright 2020 The OneFlow 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/... | en | 0.864155 | Copyright 2020 The OneFlow 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 applicable law or agreed ... | 2.059255 | 2 |
python/euclid_test.py | smenjas/programming-languages-compared | 0 | 6626891 | import unittest
from euclid import euclid
class TestEuclid(unittest.TestCase):
def test_types(self):
self.assertRaises(TypeError, euclid, 1, None)
self.assertRaises(TypeError, euclid, 1, 1.0)
self.assertRaises(TypeError, euclid, 1, "")
self.assertRaises(TypeError, euclid, 1, ())
... | import unittest
from euclid import euclid
class TestEuclid(unittest.TestCase):
def test_types(self):
self.assertRaises(TypeError, euclid, 1, None)
self.assertRaises(TypeError, euclid, 1, 1.0)
self.assertRaises(TypeError, euclid, 1, "")
self.assertRaises(TypeError, euclid, 1, ())
... | none | 1 | 3.245981 | 3 | |
grapl_analyzerlib/nodes/process_outbound_network_connection.py | wittekm/grapl_analyzerlib | 3 | 6626892 | from typing import *
from pydgraph import DgraphClient
from grapl_analyzerlib.nodes.comparators import (
Cmp,
IntCmp,
_int_cmps,
StrCmp,
_str_cmps,
PropertyFilter,
)
from grapl_analyzerlib.nodes.queryable import NQ, Queryable
from grapl_analyzerlib.nodes.types import PropertyT, Property
from g... | from typing import *
from pydgraph import DgraphClient
from grapl_analyzerlib.nodes.comparators import (
Cmp,
IntCmp,
_int_cmps,
StrCmp,
_str_cmps,
PropertyFilter,
)
from grapl_analyzerlib.nodes.queryable import NQ, Queryable
from grapl_analyzerlib.nodes.types import PropertyT, Property
from g... | en | 0.224699 | # type: List[List[Cmp[int]]] # type: List[List[Cmp[int]]] # type: List[List[Cmp[int]]] # type: List[List[Cmp[int]]] # type: List[List[Cmp[str]]] # type: List[List[Cmp[str]]] # type: Optional[IIpPortQuery] # type: Optional[IIpPortQuery] # Reverse edge # type: Optional[IProcessQuery] # type: Dict[str, Optional["EdgeViewT... | 2.206487 | 2 |
Allura/allura/ext/admin/admin_main.py | isabella232/allura | 113 | 6626893 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | en | 0.842948 | # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (t... | 1.21775 | 1 |
yaaz/src/evaluator.py | swasun/Yet-Another-AlphaZero | 2 | 6626894 | #####################################################################################
# MIT License #
# #
# Copyright (C) 2019 <NAME> ... | #####################################################################################
# MIT License #
# #
# Copyright (C) 2019 <NAME> ... | en | 0.626177 | ##################################################################################### # MIT License # # # # Copyright (C) 2019 <NAME> ... | 1.238247 | 1 |
Python/maximum-subarray.py | ZhiliangGong/LeetCode | 5 | 6626895 | # Time: O(n)
# Space: O(1)
#
# Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
#
# For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
# the contiguous subarray [4,-1,2,1] has the largest sum = 6.
#
# click to show more practice.
#
# More practice:
# If you ha... | # Time: O(n)
# Space: O(1)
#
# Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
#
# For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
# the contiguous subarray [4,-1,2,1] has the largest sum = 6.
#
# click to show more practice.
#
# More practice:
# If you ha... | en | 0.792384 | # Time: O(n) # Space: O(1) # # Find the contiguous subarray within an array (containing at least one number) which has the largest sum. # # For example, given the array [-2,1,-3,4,-1,2,1,-5,4], # the contiguous subarray [4,-1,2,1] has the largest sum = 6. # # click to show more practice. # # More practice: # If you ha... | 4.044676 | 4 |
versebot/verse.py | Team-VerseBot/versebot | 13 | 6626896 | <gh_stars>10-100
"""
VerseBot for Reddit
By <NAME>
Continued by Team VerseBot
verse.py
Copyright (c) 2015 <NAME> (MIT License)
"""
import books
import database
import webparser
class Verse:
""" Class that holds the properties and methods of a Verse object. """
def __init__(self, book, chapter, translation, ... | """
VerseBot for Reddit
By <NAME>
Continued by Team VerseBot
verse.py
Copyright (c) 2015 <NAME> (MIT License)
"""
import books
import database
import webparser
class Verse:
""" Class that holds the properties and methods of a Verse object. """
def __init__(self, book, chapter, translation, user, subreddit, ... | en | 0.886486 | VerseBot for Reddit By <NAME> Continued by Team VerseBot verse.py Copyright (c) 2015 <NAME> (MIT License) Class that holds the properties and methods of a Verse object. Initializes a Verse object with book, chapter, verse (if exists), and translation (if exists). Determines which translation should be used when... | 3.528168 | 4 |
Iteration examples.py | KuanZhasulan/Python-Games | 0 | 6626897 | <filename>Iteration examples.py
# Iterating over lists
def count_odd(numbers):
count = 0
for num in numbers:
if num % 2 == 1:
count += 1
return count
def check_odd(numbers):
for num in numbers:
if num % 2 == 1:
return True
return False
def re... | <filename>Iteration examples.py
# Iterating over lists
def count_odd(numbers):
count = 0
for num in numbers:
if num % 2 == 1:
count += 1
return count
def check_odd(numbers):
for num in numbers:
if num % 2 == 1:
return True
return False
def re... | en | 0.704717 | # Iterating over lists | 4.176619 | 4 |
ale/transformation.py | kaitlyndlee/ale | 0 | 6626898 | import numpy as np
from numpy.polynomial.polynomial import polyval, polyder
import networkx as nx
from networkx.algorithms.shortest_paths.generic import shortest_path
import spiceypy as spice
from ale.rotation import ConstantRotation, TimeDependentRotation
def create_rotations(rotation_table):
"""
Convert an... | import numpy as np
from numpy.polynomial.polynomial import polyval, polyder
import networkx as nx
from networkx.algorithms.shortest_paths.generic import shortest_path
import spiceypy as spice
from ale.rotation import ConstantRotation, TimeDependentRotation
def create_rotations(rotation_table):
"""
Convert an... | en | 0.747993 | Convert an ISIS rotation table into rotation objects. Parameters ---------- rotation_table : dict The rotation ISIS table as a dictionary Returns ------- : list A list of time dependent or constant rotation objects from the table. This list will always have eit... | 2.680593 | 3 |
1558.py | gabzin/beecrowd | 3 | 6626899 | <gh_stars>1-10
from math import sqrt
q=[0]*11001
for i in range(int(sqrt(11000))+1):
for j in range(i, int(sqrt(11000))+1):
if i*i+j*j>11000:
break
q[i*i+j*j]=1
while True:
try:
n=int(input())
if n<0:print("NO")
else:
print("YES") if q[n] else prin... | from math import sqrt
q=[0]*11001
for i in range(int(sqrt(11000))+1):
for j in range(i, int(sqrt(11000))+1):
if i*i+j*j>11000:
break
q[i*i+j*j]=1
while True:
try:
n=int(input())
if n<0:print("NO")
else:
print("YES") if q[n] else print("NO")
exc... | none | 1 | 2.940024 | 3 | |
tests/test_grid_search_cv.py | franneck94/TensorCross | 9 | 6626900 | """Test code for the grid search cv.
"""
import os
import unittest
import numpy as np
import tensorflow as tf
from tensorcross.model_selection import GridSearchCV
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
np.random.seed(0)
tf.random.set_seed(0)
def f(x: np.ndarray) -> np.ndarray:
return 2 * x + 1
class DA... | """Test code for the grid search cv.
"""
import os
import unittest
import numpy as np
import tensorflow as tf
from tensorcross.model_selection import GridSearchCV
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
np.random.seed(0)
tf.random.set_seed(0)
def f(x: np.ndarray) -> np.ndarray:
return 2 * x + 1
class DA... | en | 0.505266 | Test code for the grid search cv. Build the test model. | 2.639778 | 3 |
rising_threads/lib/frontpage_scanner.py | RGood/rising_threads | 2 | 6626901 | <filename>rising_threads/lib/frontpage_scanner.py<gh_stars>1-10
import time
class FrontpageScanner:
def __init__(self, reddit, db_collection):
self.reddit = reddit
self.collection = db_collection
def scan_frontpage(self):
while(True):
index = 0
try:
for post in self.reddit.subreddit('all').... | <filename>rising_threads/lib/frontpage_scanner.py<gh_stars>1-10
import time
class FrontpageScanner:
def __init__(self, reddit, db_collection):
self.reddit = reddit
self.collection = db_collection
def scan_frontpage(self):
while(True):
index = 0
try:
for post in self.reddit.subreddit('all').... | en | 0.312707 | #print("Logged frontpage post found.") | 2.859485 | 3 |
Hacker Rank/Equal.py | MhmdRyhn/Programming-Sloution | 1 | 6626902 | # Warning:
# In the problem, it is said that "Christy can give 1, 2 or 5 chocolates".
# Correct: Christy can give 1, 2 or 5 chocolates.
# Otherwise you will get "Wrong Answer"
def oper_per_person(n):
ans =0
ans += int(n//5)
n %= 5
ans += int(n//2)
n %= 2
ans += n
return ans
def total_op... | # Warning:
# In the problem, it is said that "Christy can give 1, 2 or 5 chocolates".
# Correct: Christy can give 1, 2 or 5 chocolates.
# Otherwise you will get "Wrong Answer"
def oper_per_person(n):
ans =0
ans += int(n//5)
n %= 5
ans += int(n//2)
n %= 2
ans += n
return ans
def total_op... | en | 0.841287 | # Warning: # In the problem, it is said that "Christy can give 1, 2 or 5 chocolates". # Correct: Christy can give 1, 2 or 5 chocolates. # Otherwise you will get "Wrong Answer" | 3.479971 | 3 |
chap_06/exe_136_reverse_lookup.py | aleattene/python-workbook | 0 | 6626903 | <gh_stars>0
"""
Write a function named reverseLookup that finds all of the keys in a dictionary that map to a specific value.
The function will take the dictionary and the value to search for as its only parameters.
It will return a (possibly empty) list of keys from the dictionary that map to the provided value.
Inclu... | """
Write a function named reverseLookup that finds all of the keys in a dictionary that map to a specific value.
The function will take the dictionary and the value to search for as its only parameters.
It will return a (possibly empty) list of keys from the dictionary that map to the provided value.
Include a main pr... | en | 0.849056 | Write a function named reverseLookup that finds all of the keys in a dictionary that map to a specific value. The function will take the dictionary and the value to search for as its only parameters. It will return a (possibly empty) list of keys from the dictionary that map to the provided value. Include a main progra... | 4.720161 | 5 |
tests/commands/test_init.py | aurule/npc | 13 | 6626904 | import npc
import os
import json
from util import fixture_dir
def test_init_bare(prefs, campaign):
npc.commands.init(prefs=prefs)
for k, p in prefs.get('paths.required').items():
if k in ["additional_paths"]:
continue
assert os.path.exists(p)
def test_init_additional_paths(prefs, c... | import npc
import os
import json
from util import fixture_dir
def test_init_bare(prefs, campaign):
npc.commands.init(prefs=prefs)
for k, p in prefs.get('paths.required').items():
if k in ["additional_paths"]:
continue
assert os.path.exists(p)
def test_init_additional_paths(prefs, c... | none | 1 | 2.251431 | 2 | |
stand_mapping/utils/metrics.py | d-diaz/stand_mapping | 0 | 6626905 | <gh_stars>0
import numpy as np
import torch
import torch.nn.functional as F
def batchify(targets, predictions, nodata, score_func,
aggregate=True, *args, **kwargs):
"""
Applies a scoring function to each sample image in a batch.
Parameters
----------
targets : array-like, shape (batc... | import numpy as np
import torch
import torch.nn.functional as F
def batchify(targets, predictions, nodata, score_func,
aggregate=True, *args, **kwargs):
"""
Applies a scoring function to each sample image in a batch.
Parameters
----------
targets : array-like, shape (batch_size, heig... | en | 0.770267 | Applies a scoring function to each sample image in a batch. Parameters ---------- targets : array-like, shape (batch_size, height, width) observed, ground-truth target images predictions : array-like, shape (batch_size, height, width) predicted images nodata : array-like, shape (batch_s... | 2.873411 | 3 |
gcloud/logging/sink.py | waprin/google-cloud-python | 0 | 6626906 | # Copyright 2016 Google Inc. 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 applicable law or a... | # Copyright 2016 Google Inc. 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 applicable law or a... | en | 0.711966 | # Copyright 2016 Google Inc. 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 applicable law or a... | 2.228599 | 2 |
demo_train.py | amitaifrey/learn-to-hash | 0 | 6626907 |
'''
Demo for running training or linear models.
'''
import utils
from kahip.kmkahip import run_kmkahip
if __name__ == '__main__':
opt = utils.parse_args()
#adjust the number of parts and the height of the hierarchy
n_cluster_l = [opt.n_clusters]
height_l = [opt.height]
# lo... |
'''
Demo for running training or linear models.
'''
import utils
from kahip.kmkahip import run_kmkahip
if __name__ == '__main__':
opt = utils.parse_args()
#adjust the number of parts and the height of the hierarchy
n_cluster_l = [opt.n_clusters]
height_l = [opt.height]
# lo... | en | 0.891004 | Demo for running training or linear models. #adjust the number of parts and the height of the hierarchy # load dataset #specify which action to take at each level, actions can be km, kahip, train, or svm. Lower keys indicate closer to leaf. #Note that if 'kahip' is included, evaluation must be on training rather than t... | 2.27372 | 2 |
blog/templatetags/blog_tags.py | sometimeslove/www.superstrong.com | 0 | 6626908 | <filename>blog/templatetags/blog_tags.py
#!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: superstrongz
@license: MIT Licence
@contact: <EMAIL>
@site: http://www.superstrongz.com/
@software: PyCharm
@file: blog_tags.py
@time: ??
"""
from django import template
from django.db.models import Q
from djan... | <filename>blog/templatetags/blog_tags.py
#!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: superstrongz
@license: MIT Licence
@contact: <EMAIL>
@site: http://www.superstrongz.com/
@software: PyCharm
@file: blog_tags.py
@time: ??
"""
from django import template
from django.db.models import Q
from djan... | en | 0.215921 | #!/usr/bin/env python # encoding: utf-8 @version: ?? @author: superstrongz @license: MIT Licence @contact: <EMAIL> @site: http://www.superstrongz.com/ @software: PyCharm @file: blog_tags.py @time: ?? # print(data.strftime(settings.TIME_FORMAT)) # return "ddd" 获得文章内容的摘要 :param content: :return: 获得文章面包屑 :para... | 2.221107 | 2 |
eval_psdb_mobiLess.py | cgangEE/ssd | 0 | 6626909 | basepath=$(cd `dirname $0`; pwd)
./evaluate_mobi.py \
--rec-path ${basepath}/data/psdb/val.rec \
--network mobilenetLess \
--num-class 4 \
--data-shape 300 \
--cpu \
--epoch 240 \
--batch-size 1 \
--prefix ${basepath}/output/psdbMobileNetLess/ssd \
--class-names 'pedestrian, head, head-shouler, upp... | basepath=$(cd `dirname $0`; pwd)
./evaluate_mobi.py \
--rec-path ${basepath}/data/psdb/val.rec \
--network mobilenetLess \
--num-class 4 \
--data-shape 300 \
--cpu \
--epoch 240 \
--batch-size 1 \
--prefix ${basepath}/output/psdbMobileNetLess/ssd \
--class-names 'pedestrian, head, head-shouler, upp... | sr | 0.319517 | #--gpus 0 \ | 1.268038 | 1 |
libs/rbv/utils.py | hexatester/ut-telegram-bot | 0 | 6626910 | import os
from bs4 import BeautifulSoup, Tag
from logging import getLogger
from requests import Response
from config import IMG_PATH
from .base import SESSION, USERNAME, PASSWORD
from .page import Page
logger = getLogger(__name__)
def get_chaptcha(soup: Tag) -> str:
c = ""
try:
ccaptcha: Tag = soup.f... | import os
from bs4 import BeautifulSoup, Tag
from logging import getLogger
from requests import Response
from config import IMG_PATH
from .base import SESSION, USERNAME, PASSWORD
from .page import Page
logger = getLogger(__name__)
def get_chaptcha(soup: Tag) -> str:
c = ""
try:
ccaptcha: Tag = soup.f... | id | 0.752548 | # 'Berapa hasil dari 3 + 9 =' # NOQA # NOQA # NOQA | 2.757946 | 3 |
utils_lm.py | exelents/soft-prompt-tuning | 7 | 6626911 | from transformers.data.datasets.language_modeling import *
import copy
class LineByLineWebNLGTextDataset(Dataset):
"""
This will be superseded by a framework-agnostic approach
soon.
"""
def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str,
block_size: int, bos_tok:st... | from transformers.data.datasets.language_modeling import *
import copy
class LineByLineWebNLGTextDataset(Dataset):
"""
This will be superseded by a framework-agnostic approach
soon.
"""
def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str,
block_size: int, bos_tok:st... | en | 0.440476 | This will be superseded by a framework-agnostic approach soon. # Here, we do not cache the features, operating under the assumption # that we will soon use fast multithreaded tokenizers from the # `tokenizers` repo everywhere =) # !!!! # <NAME> # self.labels = copy.deepcopy(self.examples) # split into category word... | 2.41137 | 2 |
Gathered CTF writeups/2018-04-30-rhme3/CPA/collect_same.py | mihaid-b/CyberSakura | 1 | 6626912 | from library import *
import sys
with open(sys.argv[1], "w") as f:
for i in range(int(sys.argv[2])):
save_sample(f, chr(int(sys.argv[3], 0))*16)
| from library import *
import sys
with open(sys.argv[1], "w") as f:
for i in range(int(sys.argv[2])):
save_sample(f, chr(int(sys.argv[3], 0))*16)
| none | 1 | 2.508249 | 3 | |
python/tests/custom_dictionary_test.py | sqdk/brotli | 5 | 6626913 | #!/usr/bin/env python
from __future__ import print_function
import sys
import os
from subprocess import check_call, Popen, PIPE
from _test_utils import PYTHON, BRO, TEST_ENV, diff_q
INPUTS = """\
testdata/alice29.txt
testdata/asyoulik.txt
testdata/lcet10.txt
testdata/plrabn12.txt
../enc/encode.c
../common/dictionary... | #!/usr/bin/env python
from __future__ import print_function
import sys
import os
from subprocess import check_call, Popen, PIPE
from _test_utils import PYTHON, BRO, TEST_ENV, diff_q
INPUTS = """\
testdata/alice29.txt
testdata/asyoulik.txt
testdata/lcet10.txt
testdata/plrabn12.txt
../enc/encode.c
../common/dictionary... | en | 0.215286 | #!/usr/bin/env python \ testdata/alice29.txt testdata/asyoulik.txt testdata/lcet10.txt testdata/plrabn12.txt ../enc/encode.c ../common/dictionary.h ../dec/decode.c %s | 2.278584 | 2 |
UI/ui_MainWindows.py | BeiChenYx/NetDebug | 9 | 6626914 | <filename>UI/ui_MainWindows.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MainWindows.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
... | <filename>UI/ui_MainWindows.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MainWindows.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
... | en | 0.777901 | # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'MainWindows.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! | 1.78347 | 2 |
homeassistant/components/flock/notify.py | alemuro/home-assistant | 2 | 6626915 | """Flock platform for notify component."""
import asyncio
import logging
import async_timeout
import voluptuous as vol
from homeassistant.const import CONF_ACCESS_TOKEN
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.com... | """Flock platform for notify component."""
import asyncio
import logging
import async_timeout
import voluptuous as vol
from homeassistant.const import CONF_ACCESS_TOKEN
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.com... | en | 0.718297 | Flock platform for notify component. Get the Flock notification service. Implement the notification service for Flock. Initialize the Flock notification service. Send the message to the user. | 2.46706 | 2 |
server/auvsi_suas/views/teams.py | dcat52/interop | 0 | 6626916 | """Teams view."""
import json
from auvsi_suas.models.mission_clock_event import MissionClockEvent
from auvsi_suas.models.uas_telemetry import UasTelemetry
from auvsi_suas.models.takeoff_or_landing_event import TakeoffOrLandingEvent
from auvsi_suas.views import logger
from auvsi_suas.views.decorators import require_supe... | """Teams view."""
import json
from auvsi_suas.models.mission_clock_event import MissionClockEvent
from auvsi_suas.models.uas_telemetry import UasTelemetry
from auvsi_suas.models.takeoff_or_landing_event import TakeoffOrLandingEvent
from auvsi_suas.views import logger
from auvsi_suas.views.decorators import require_supe... | en | 0.733635 | Teams view. Generate JSON-style dict for user. Gets a list of all teams. # Only standard users are exported GET/PUT specific team. PUT allows updating status. # Potential events to update. # Update whether UAS is in air. # New event only necessary if changing status # Update whether UAS in on clock or timeout. # New ev... | 2.209967 | 2 |
sample/ch4/cross-iris.py | wagase/scraping | 0 | 6626917 | from sklearn import svm, metrics
import random, re
# アヤメのCSVデータを読み込む --- (※1)
lines = open('iris.csv', 'r', encoding='utf-8').read().split("\n")
f_tonum = lambda n : float(n) if re.match(r'^[0-9\.]+$', n) else n
f_cols = lambda li: list(map(f_tonum,li.strip().split(',')))
csv = list(map(f_cols, lines))
del csv[0] # 先... | from sklearn import svm, metrics
import random, re
# アヤメのCSVデータを読み込む --- (※1)
lines = open('iris.csv', 'r', encoding='utf-8').read().split("\n")
f_tonum = lambda n : float(n) if re.match(r'^[0-9\.]+$', n) else n
f_cols = lambda li: list(map(f_tonum,li.strip().split(',')))
csv = list(map(f_cols, lines))
del csv[0] # 先... | ja | 0.999637 | # アヤメのCSVデータを読み込む --- (※1) # 先頭のヘッダ行を削除 # データをシャッフル # データをK分割する --- (※2) # リストを訓練データとラベルに分割する関数 # 正解率を求める --- (※3) # 区連データを学習して分類して正解率を求める # K分割したデータについて正解率を求める --- (※4) # testc以外のデータを訓練データとする | 2.63743 | 3 |
scripts/db_add_sentiment.py | dwlmt/Story-Untangling | 7 | 6626918 | <gh_stars>1-10
import argparse
import asyncio
from concurrent.futures.process import ProcessPoolExecutor
from story_untangling.dataset_readers.dataset_features import save_sentiment
engine_kwargs = {"pool_recycle": 3600, "connect_args": {'timeout': 1000, "check_same_thread": False}}
async def add_sentiment_features(... | import argparse
import asyncio
from concurrent.futures.process import ProcessPoolExecutor
from story_untangling.dataset_readers.dataset_features import save_sentiment
engine_kwargs = {"pool_recycle": 3600, "connect_args": {'timeout': 1000, "check_same_thread": False}}
async def add_sentiment_features(args):
data... | none | 1 | 2.517728 | 3 | |
Python/Regex And Parsing/Hex Color Code.py | abivilion/Hackerank-Solutions- | 0 | 6626919 | import re, sys
# print(sys.stdin)
for i in sys.stdin:
# print(i)
for j in re.findall('[\s:](#[a-f0-9]{6}|#[a-f0-9]{3})', i, re.I):
print(j)
| import re, sys
# print(sys.stdin)
for i in sys.stdin:
# print(i)
for j in re.findall('[\s:](#[a-f0-9]{6}|#[a-f0-9]{3})', i, re.I):
print(j)
| fa | 0.082394 | # print(sys.stdin) # print(i) #[a-f0-9]{6}|#[a-f0-9]{3})', i, re.I): | 2.949183 | 3 |
mahjong/hand_calculating/fu.py | otamajakusi/mahjong | 0 | 6626920 | # -*- coding: utf-8 -*-
from mahjong.constants import HONOR_INDICES, TERMINAL_INDICES
from mahjong.meld import Meld
from mahjong.utils import contains_terminals, is_pair, is_pon_or_kan, simplify
class FuCalculator(object):
BASE = "base"
PENCHAN = "penchan"
KANCHAN = "kanchan"
VALUED_PAIR = "valued_pa... | # -*- coding: utf-8 -*-
from mahjong.constants import HONOR_INDICES, TERMINAL_INDICES
from mahjong.meld import Meld
from mahjong.utils import contains_terminals, is_pair, is_pon_or_kan, simplify
class FuCalculator(object):
BASE = "base"
PENCHAN = "penchan"
KANCHAN = "kanchan"
VALUED_PAIR = "valued_pa... | en | 0.850943 | # -*- coding: utf-8 -*- Calculate hand fu with explanations :param hand: :param win_tile: 136 tile format :param win_group: one set where win tile exists :param config: HandConfig object :param valued_tiles: dragons, player wind, round wind :param melds: opened sets ... | 2.588241 | 3 |
application.py | tcharts-boop/registration_notifications_usf | 0 | 6626921 | <reponame>tcharts-boop/registration_notifications_usf
import mechanicalsoup
from bs4 import BeautifulSoup
import unicodedata
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import csv
import sys
class ApplicationMethods:
# Static method to load text file into... | import mechanicalsoup
from bs4 import BeautifulSoup
import unicodedata
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import csv
import sys
class ApplicationMethods:
# Static method to load text file into variables/list
@staticmethod
def load_file():... | en | 0.766042 | # Static method to load text file into variables/list # Set up email and password variables # Strip line and split by ', ' into array if the value is not blank # Return variables in dictionary data type # Static method to return duration and duration counter variables # Try to get an int input # Try again if not int in... | 3.056531 | 3 |
package/spack-openexr/package.py | ctuning/ck-spack | 1 | 6626922 | <gh_stars>1-10
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by <NAME>, <EMAIL>, All rights reserved.
# LLNL-CODE-647... | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by <NAME>, <EMAIL>, All rights reserved.
# LLNL-CODE-647188
#
# For det... | en | 0.749616 | ############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by <NAME>, <EMAIL>, All rights reserved. # LLNL-CODE-647188 # # For det... | 1.31146 | 1 |
models/proposal.py | NSLS-II/nsls2-api | 0 | 6626923 | <filename>models/proposal.py<gh_stars>0
from typing import Optional, List
from pydantic.main import BaseModel
class Proposal(BaseModel):
proposal_id: str
users_admin: List[str] # PI(s)
users: List[str]
| <filename>models/proposal.py<gh_stars>0
from typing import Optional, List
from pydantic.main import BaseModel
class Proposal(BaseModel):
proposal_id: str
users_admin: List[str] # PI(s)
users: List[str]
| none | 1 | 2.208384 | 2 | |
tests/integration-tests/tests/common/mpi_common.py | siddharthsalot/aws-parallelcluster | 0 | 6626924 | import logging
import pathlib
from assertpy import assert_that
from tests.common.assertions import assert_no_errors_in_logs, assert_scaling_worked
from tests.common.schedulers_common import get_scheduler_commands
OS_TO_ARCHITECTURE_TO_OPENMPI_MODULE = {
"alinux": {"x86_64": "openmpi"},
"alinux2": {"x86_64": "... | import logging
import pathlib
from assertpy import assert_that
from tests.common.assertions import assert_no_errors_in_logs, assert_scaling_worked
from tests.common.schedulers_common import get_scheduler_commands
OS_TO_ARCHITECTURE_TO_OPENMPI_MODULE = {
"alinux": {"x86_64": "openmpi"},
"alinux2": {"x86_64": "... | en | 0.782109 | # Compile mpi script # submit script using additional files # not checking assert_job_succeeded after cluster scale down cause the scheduler history might be gone # mpi_out expected output # Hello world from processor ip-192-168-53-169, rank 0 out of 2 processors # Process 0 received token -1 from process 1 # Hello wor... | 2.028123 | 2 |
main.py | ZackDowning/CommandRunner | 0 | 6626925 | from gui import ManagementFileBrowseWindow, ConfigFileBrowseWindow
from net_async import AsyncSessions, ForceSessionRetry
from getpass import getpass
import re
import time
# TODO: Add support for config file
# PyInstaller bundle command:
# pyinstaller -F --hidden-import PySimpleGUI,net_async --add-data templates;temp... | from gui import ManagementFileBrowseWindow, ConfigFileBrowseWindow
from net_async import AsyncSessions, ForceSessionRetry
from getpass import getpass
import re
import time
# TODO: Add support for config file
# PyInstaller bundle command:
# pyinstaller -F --hidden-import PySimpleGUI,net_async --add-data templates;temp... | en | 0.555159 | # TODO: Add support for config file # PyInstaller bundle command: # pyinstaller -F --hidden-import PySimpleGUI,net_async --add-data templates;templates main.py # Outputs failed device list to CSV file with columns: # 'ip_address,connectivity,authentication,authorization,con_type,con_exception' Type 'use_file' if you wa... | 2.108429 | 2 |
styler_rest_framework/pubsub/publishers/pubsub_handler.py | STYLER-Inc/styler-rest-framework | 3 | 6626926 | """ Handler for pubsub
"""
from concurrent import futures
import logging
from google.cloud import pubsub_v1
def get_callback(data):
"""Wrap message data in the context of the callback function."""
def callback(api_future):
try:
api_future.result()
except Exception:
lo... | """ Handler for pubsub
"""
from concurrent import futures
import logging
from google.cloud import pubsub_v1
def get_callback(data):
"""Wrap message data in the context of the callback function."""
def callback(api_future):
try:
api_future.result()
except Exception:
lo... | en | 0.635749 | Handler for pubsub Wrap message data in the context of the callback function. # pragma: no coverage Publishes a message to a Pub/Sub topic. # Initialize a Publisher client. # When you publish a message, the client returns a future. | 2.828336 | 3 |
ner/3DownLoadHTML.py | 196sigma/ner-10ks | 2 | 6626927 | <gh_stars>1-10
import os,sys,csv,urllib2,time
os.chdir('/Users/alvinzuyinzheng/Dropbox/PythonWorkshop/scripts/')#<===The location of your file "LongCompanyList.csv
htmlSubPath = "./HTML/" #<===The subfolder with the 10-K files in HTML format
Form10kListFile = "10kList.csv" #a csv file (output of the 2Get10kLin... | import os,sys,csv,urllib2,time
os.chdir('/Users/alvinzuyinzheng/Dropbox/PythonWorkshop/scripts/')#<===The location of your file "LongCompanyList.csv
htmlSubPath = "./HTML/" #<===The subfolder with the 10-K files in HTML format
Form10kListFile = "10kList.csv" #a csv file (output of the 2Get10kLinks.py script) w... | en | 0.870104 | #<===The location of your file "LongCompanyList.csv #<===The subfolder with the 10-K files in HTML format #a csv file (output of the 2Get10kLinks.py script) with the list of 10-K links #a csv file (output of the current script) with the download history of 10-K forms ### <=== keep all HTML files in this subfolder ### <... | 2.738972 | 3 |
src/Case1.py | EstudoAAS/linear-algebra-refresher-course | 0 | 6626928 | <reponame>EstudoAAS/linear-algebra-refresher-course
import vector
def main():
vetor1 = vector.Vector([8.218,-9.341])
print(vetor1.plus(vector.Vector([-1.129,2.111])))
vetor2 = vector.Vector([7.119,8.215])
print(vetor2.minus(vector.Vector([-8.223,0.878])))
vetor3 = vector.Vector([1.671,-1.012,-0.3... | import vector
def main():
vetor1 = vector.Vector([8.218,-9.341])
print(vetor1.plus(vector.Vector([-1.129,2.111])))
vetor2 = vector.Vector([7.119,8.215])
print(vetor2.minus(vector.Vector([-8.223,0.878])))
vetor3 = vector.Vector([1.671,-1.012,-0.318])
print(vetor3.times_scalar(7.41))
main() | none | 1 | 3.586724 | 4 | |
utils.py | cianfrocco-lab/GAN-for-Cryo-EM-image-denoising | 10 | 6626929 | <filename>utils.py<gh_stars>1-10
import numpy as np
import tensorflow as tf
import scipy.misc
def batch_norm(x, scope):
return tf.contrib.layers.batch_norm(x, decay=0.9, updates_collections=None, epsilon=1e-5, scale=True, scope=scope)
def conv2d(input, output_dim, f=4, stride=2, stddev=0.02, name="conv2d... | <filename>utils.py<gh_stars>1-10
import numpy as np
import tensorflow as tf
import scipy.misc
def batch_norm(x, scope):
return tf.contrib.layers.batch_norm(x, decay=0.9, updates_collections=None, epsilon=1e-5, scale=True, scope=scope)
def conv2d(input, output_dim, f=4, stride=2, stddev=0.02, name="conv2d... | none | 1 | 2.323254 | 2 | |
astropy_helpers/commands/test.py | jayvdb/astropy-helpers | 30 | 6626930 | <reponame>jayvdb/astropy-helpers
"""
Different implementations of the ``./setup.py test`` command depending on
what's locally available.
If Astropy v1.1 or later is available it should be possible to import
AstropyTest from ``astropy.tests.command``. Otherwise there is a skeleton
implementation that allows users to at... | """
Different implementations of the ``./setup.py test`` command depending on
what's locally available.
If Astropy v1.1 or later is available it should be possible to import
AstropyTest from ``astropy.tests.command``. Otherwise there is a skeleton
implementation that allows users to at least discover the ``./setup.py ... | en | 0.865599 | Different implementations of the ``./setup.py test`` command depending on what's locally available. If Astropy v1.1 or later is available it should be possible to import AstropyTest from ``astropy.tests.command``. Otherwise there is a skeleton implementation that allows users to at least discover the ``./setup.py test... | 2.483687 | 2 |
experiment/session.py | yvinkesteijn/RL_visual_task | 0 | 6626931 | from __future__ import absolute_import, division, print_function
from psychopy import visual, core, event, prefs
import sys, csv, time, os,datetime, time
import random as rd
class session(object):
def __init__(self, ppn, a_side, rwrd_sc,control_ph, learn_ph, test_ph, demo_ph,
img_time=1.250, cros... | from __future__ import absolute_import, division, print_function
from psychopy import visual, core, event, prefs
import sys, csv, time, os,datetime, time
import random as rd
class session(object):
def __init__(self, ppn, a_side, rwrd_sc,control_ph, learn_ph, test_ph, demo_ph,
img_time=1.250, cros... | en | 0.768396 | # print(self.cur_reward) # Function creates second phase. Shows one image for 100ms and registers keys Takes phasename, list with image names and number of trials as ppn_input adds variables [key pressed, image name, RT, reward, total reward, etc.] to log list of participant session ... | 2.126368 | 2 |
src/Basic_knowledge/Manual_implementation_neural_network/简单感知器.py | wynshiter/NLP_DEMO | 7 | 6626932 |
'''
1. 处理单个输入
2. 处理2分类
'''
class Perceptron(object):
'''
初始化参数lr(用于调整训练步长,即 learning),iterations(迭代次数),权重w 与 bias 偏执
'''
def __init__(self,eta=0.01,iterations=10):
self.lr = eta
self.iterations = iterations
self.w = 0.0
self.bias = 0.0
#'''
#公式:
#Δw = lr * (y - y') ... |
'''
1. 处理单个输入
2. 处理2分类
'''
class Perceptron(object):
'''
初始化参数lr(用于调整训练步长,即 learning),iterations(迭代次数),权重w 与 bias 偏执
'''
def __init__(self,eta=0.01,iterations=10):
self.lr = eta
self.iterations = iterations
self.w = 0.0
self.bias = 0.0
#'''
#公式:
#Δw = lr * (y - y') ... | zh | 0.944729 | 1. 处理单个输入 2. 处理2分类 初始化参数lr(用于调整训练步长,即 learning),iterations(迭代次数),权重w 与 bias 偏执 #''' #公式: #Δw = lr * (y - y') * x #Δbias = lr * (y - y') #''' #首先获得真实值 y 与预测值 y' 的偏差,乘以一个较小的参数 # 【lr 值过小导致训练时间过长,难以判断是否收敛】 # 【lr 值过大则容易造成步长过大而无法收敛】 # y'(预测值) = w * x + bias | 4.007336 | 4 |
bcbio/upload/galaxy.py | brentp/bcbio-nextgen | 1 | 6626933 | """Move files to local Galaxy upload directory and add to Galaxy Data Libraries.
Required configurable variables in upload:
dir
"""
import collections
import os
from bcbio import utils
from bcbio.log import logger
from bcbio.upload import filesystem
# Avoid bioblend import errors, raising at time of use
try:
f... | """Move files to local Galaxy upload directory and add to Galaxy Data Libraries.
Required configurable variables in upload:
dir
"""
import collections
import os
from bcbio import utils
from bcbio.log import logger
from bcbio.upload import filesystem
# Avoid bioblend import errors, raising at time of use
try:
f... | en | 0.730962 | Move files to local Galaxy upload directory and add to Galaxy Data Libraries. Required configurable variables in upload: dir # Avoid bioblend import errors, raising at time of use Update file in Galaxy data libraries. Upload a file to a Galaxy data library in a project specific folder. Check if file exists on Galaxy... | 2.650936 | 3 |
src/config.py | palmtreemodel/PalmTree | 29 | 6626934 | <gh_stars>10-100
"""
Configuration file.
"""
VOCAB_SIZE = 10000
USE_CUDA = True
DEVICES = [0]
CUDA_DEVICE = DEVICES[0]
VERSION = 1
MAXLEN = 10
| """
Configuration file.
"""
VOCAB_SIZE = 10000
USE_CUDA = True
DEVICES = [0]
CUDA_DEVICE = DEVICES[0]
VERSION = 1
MAXLEN = 10 | en | 0.385016 | Configuration file. | 1.239893 | 1 |
pipe-cli/src/utilities/cluster_manager.py | AlfiyaRF/cloud-pipeline | 126 | 6626935 | <reponame>AlfiyaRF/cloud-pipeline<filename>pipe-cli/src/utilities/cluster_manager.py
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
#
# 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 Lice... | # Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
#
# 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 appli... | en | 0.841866 | # Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) # # 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 appli... | 1.633637 | 2 |
src/adk/api/remote_api.py | QuTech-Delft/qne-adk | 1 | 6626936 | <gh_stars>1-10
from pathlib import Path
from typing import Any, cast, Dict, List, Optional, Tuple, Union
import time
from apistar.exceptions import ErrorResponse
from adk import utils
from adk.api.qne_client import QneFrontendClient
from adk.exceptions import (ApiClientError, ApplicationNotFound, ExperimentFailed, Ex... | from pathlib import Path
from typing import Any, cast, Dict, List, Optional, Tuple, Union
import time
from apistar.exceptions import ErrorResponse
from adk import utils
from adk.api.qne_client import QneFrontendClient
from adk.exceptions import (ApiClientError, ApplicationNotFound, ExperimentFailed, ExperimentValueEr... | en | 0.825976 | The status of the qne_job can be 'NEW', 'RUNNING', 'COMPLETE', 'FAILED' # The final status of the qne_job, either successful or not # The status of the qne_job when it is executed successfully Defines the methods used for remote communication with api-router Login the user on host (uri) based upon the username/password... | 1.8773 | 2 |
course_grader/apps.py | uw-it-aca/gradepage | 1 | 6626937 | # Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.apps import AppConfig
from restclients_core.dao import MockDAO
import os
class CourseGraderConfig(AppConfig):
name = 'course_grader'
def ready(self):
mocks = os.path.join(os.path.dirname(__file__), 're... | # Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.apps import AppConfig
from restclients_core.dao import MockDAO
import os
class CourseGraderConfig(AppConfig):
name = 'course_grader'
def ready(self):
mocks = os.path.join(os.path.dirname(__file__), 're... | en | 0.374447 | # Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 | 1.986374 | 2 |
FPSTest/onChip/display_num.py | AndyZ-Salz/BadApple_QuecPython | 0 | 6626938 | <reponame>AndyZ-Salz/BadApple_QuecPython<filename>FPSTest/onChip/display_num.py<gh_stars>0
# -*- coding: UTF-8 -*-
import utime
'''
如果用户使用的固件版本中没有checkNet库,请将checkNet.mpy文件上传到模块的usr目录,
并将 import checkNet 改为 from usr import checkNet
'''
import checkNet
from usr import st7789v
'''
下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变... | # -*- coding: UTF-8 -*-
import utime
'''
如果用户使用的固件版本中没有checkNet库,请将checkNet.mpy文件上传到模块的usr目录,
并将 import checkNet 改为 from usr import checkNet
'''
import checkNet
from usr import st7789v
'''
下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值,
在执行用户代码前,会先打印这两个变量的值。
'''
PROJECT_NAME = "QuecPython_ST7789V_LCD_FPSTest"
PROJECT_VERS... | zh | 0.908343 | # -*- coding: UTF-8 -*- 如果用户使用的固件版本中没有checkNet库,请将checkNet.mpy文件上传到模块的usr目录, 并将 import checkNet 改为 from usr import checkNet 下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值, 在执行用户代码前,会先打印这两个变量的值。 手动运行本例程时,可以去掉该延时,如果将例程文件名改为main.py,希望开机自动运行时,需要加上该延时, 否则无法从CDC口看到下面的 poweron_print_once() 中打印的信息 # utime.sleep(5) 如果用户程序包含网络相关代码,... | 2.14234 | 2 |
test/TestSkipInsideYaml.py | xoxys/ansible-lint | 0 | 6626939 | <reponame>xoxys/ansible-lint
import pytest
ROLE_TASKS = '''\
---
- name: test 303
command: git log
changed_when: false
- name: test 303 (skipped)
command: git log # noqa 303
changed_when: false
'''
ROLE_TASKS_WITH_BLOCK = '''\
---
- name: bad git 1 # noqa 401
action: git a=b c=d
- name: bad git 2
action... | import pytest
ROLE_TASKS = '''\
---
- name: test 303
command: git log
changed_when: false
- name: test 303 (skipped)
command: git log # noqa 303
changed_when: false
'''
ROLE_TASKS_WITH_BLOCK = '''\
---
- name: bad git 1 # noqa 401
action: git a=b c=d
- name: bad git 2
action: git a=b c=d
- name: Block w... | en | 0.462376 | \ --- - name: test 303 command: git log changed_when: false - name: test 303 (skipped) command: git log # noqa 303 changed_when: false \ --- - name: bad git 1 # noqa 401 action: git a=b c=d - name: bad git 2 action: git a=b c=d - name: Block with rescue and always section block: - name: bad git 3 #... | 2.032583 | 2 |
pyecobee/objects/thermostat.py | gleblanc1783/Pyecobee | 29 | 6626940 | """
This module is home to the Thermostat class
"""
from pyecobee.ecobee_object import EcobeeObject
class Thermostat(EcobeeObject):
"""
This class has been auto generated by scraping
https://www.ecobee.com/home/developer/api/documentation/v1/objects/Thermostat.shtml
Attribute names have been generate... | """
This module is home to the Thermostat class
"""
from pyecobee.ecobee_object import EcobeeObject
class Thermostat(EcobeeObject):
"""
This class has been auto generated by scraping
https://www.ecobee.com/home/developer/api/documentation/v1/objects/Thermostat.shtml
Attribute names have been generate... | en | 0.706711 | This module is home to the Thermostat class This class has been auto generated by scraping https://www.ecobee.com/home/developer/api/documentation/v1/objects/Thermostat.shtml Attribute names have been generated by converting ecobee property names from camelCase to snake_case. A getter property has bee... | 2.141803 | 2 |
api/config/settings/env.py | nonwander/dating-site | 0 | 6626941 | import environ
ROOT_DIR = environ.Path(__file__) - 4
APPS_DIR = ROOT_DIR.path('api')
env = environ.Env()
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False)
if READ_DOT_ENV_FILE:
env_file = str(ROOT_DIR.path('.env'))
print(f'Loading : {env_file}')
env.read_env(env_file)
print('Th... | import environ
ROOT_DIR = environ.Path(__file__) - 4
APPS_DIR = ROOT_DIR.path('api')
env = environ.Env()
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False)
if READ_DOT_ENV_FILE:
env_file = str(ROOT_DIR.path('.env'))
print(f'Loading : {env_file}')
env.read_env(env_file)
print('Th... | none | 1 | 2.151277 | 2 | |
python/learn/mqtt/sub.py | qrsforever/workspace | 2 | 6626942 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @file app.py
# @brief
# @author QRS
# @blog qrsforever.github.io
# @version 1.0
# @date 2019-05-13 17:21:59
import paho.mqtt.client as mqtt
import os
HOST = "127.0.0.1"
PORT = 1883
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+ str... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @file app.py
# @brief
# @author QRS
# @blog qrsforever.github.io
# @version 1.0
# @date 2019-05-13 17:21:59
import paho.mqtt.client as mqtt
import os
HOST = "127.0.0.1"
PORT = 1883
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+ str... | en | 0.19373 | #!/usr/bin/python3 # -*- coding: utf-8 -*- # @file app.py # @brief # @author QRS # @blog qrsforever.github.io # @version 1.0 # @date 2019-05-13 17:21:59 #") # client.loop_forever() | 2.684138 | 3 |
mmdet3d/core/optimizer/hybrid_optimizer.py | zhyever/SimIPU | 29 | 6626943 | from mmcv.runner.optimizer import OPTIMIZERS
from torch.optim import Optimizer
@OPTIMIZERS.register_module()
class HybridOptimizer(Optimizer):
"""Hybrid Optimizer that contains multiple optimizers This optimizer
applies the hybrid optimzation for multi-modality models."""
def __init__(self, optimizers, s... | from mmcv.runner.optimizer import OPTIMIZERS
from torch.optim import Optimizer
@OPTIMIZERS.register_module()
class HybridOptimizer(Optimizer):
"""Hybrid Optimizer that contains multiple optimizers This optimizer
applies the hybrid optimzation for multi-modality models."""
def __init__(self, optimizers, s... | en | 0.759741 | Hybrid Optimizer that contains multiple optimizers This optimizer applies the hybrid optimzation for multi-modality models. Loads the optimizer state. Arguments: state_dict (dict): optimizer state. Should be an object returned from a call to :meth:`state_dict`. Clears the gradien... | 2.403013 | 2 |
test/test_data_on_home_page.py | JuliaBessonova/python_training | 0 | 6626944 | import re
from model.contact import Contact
def test_data_on_home_page(app, db):
uicontacts = sorted(app.contact.get_contact_list(), key=Contact.id_or_max)
dbcontacts = sorted(db.get_contact_list(), key=Contact.id_or_max)
for contact in range(len(uicontacts)):
assert uicontacts[contact].lastname ==... | import re
from model.contact import Contact
def test_data_on_home_page(app, db):
uicontacts = sorted(app.contact.get_contact_list(), key=Contact.id_or_max)
dbcontacts = sorted(db.get_contact_list(), key=Contact.id_or_max)
for contact in range(len(uicontacts)):
assert uicontacts[contact].lastname ==... | none | 1 | 2.651837 | 3 | |
examples/plot_summary.py | Jiaming1999/ChainConsumer | 55 | 6626945 | # -*- coding: utf-8 -*-
"""
============
Plot Summary
============
Have a bunch of models and want to compare summaries, but in a plot instead of LaTeX? Can do!
"""
###############################################################################
# Lets add a bunch of chains represnting all these different models of ... | # -*- coding: utf-8 -*-
"""
============
Plot Summary
============
Have a bunch of models and want to compare summaries, but in a plot instead of LaTeX? Can do!
"""
###############################################################################
# Lets add a bunch of chains represnting all these different models of ... | en | 0.334376 | # -*- coding: utf-8 -*- ============ Plot Summary ============ Have a bunch of models and want to compare summaries, but in a plot instead of LaTeX? Can do! ############################################################################### # Lets add a bunch of chains represnting all these different models of ours. # Add... | 2.511575 | 3 |
freyja/updates.py | tomkinsc/Freyja | 19 | 6626946 | import urllib.request
import os
import sys
import subprocess
def download_tree(locDir):
url = "http://hgdownload.soe.ucsc.edu/goldenPath/wuhCor1/"\
"UShER_SARS-CoV-2/public-latest.all.masked.pb.gz"
treePath = os.path.join(locDir, "public-latest.all.masked.pb.gz")
urllib.request.urlretrieve(url, ... | import urllib.request
import os
import sys
import subprocess
def download_tree(locDir):
url = "http://hgdownload.soe.ucsc.edu/goldenPath/wuhCor1/"\
"UShER_SARS-CoV-2/public-latest.all.masked.pb.gz"
treePath = os.path.join(locDir, "public-latest.all.masked.pb.gz")
urllib.request.urlretrieve(url, ... | en | 0.61542 | # force python to flush | 2.695351 | 3 |
config.py | LordMartian/pytorch-template | 0 | 6626947 | <gh_stars>0
"""
Author: <NAME>
Description: File for setting values for the configuration options.
- Project structure paths
- Hyperparameters
"""
args = dict()
# project structure
args["CODE_DIRECTORY"] = "absolute path to code directory"
args["DATA_DIRECTORY"] = "absolute path to dataset directory"
args["DEMO_DI... | """
Author: <NAME>
Description: File for setting values for the configuration options.
- Project structure paths
- Hyperparameters
"""
args = dict()
# project structure
args["CODE_DIRECTORY"] = "absolute path to code directory"
args["DATA_DIRECTORY"] = "absolute path to dataset directory"
args["DEMO_DIRECTORY"] = ... | en | 0.61938 | Author: <NAME> Description: File for setting values for the configuration options. - Project structure paths - Hyperparameters # project structure # data # training # optimizer and scheduler # loss | 2.113589 | 2 |
pyqtgraph/examples/test_Arrow.py | robertsj/poropy | 1 | 6626948 | # -*- coding: utf-8 -*-
## Add path to library (just for examples; you do not need this)
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
import numpy as np
from PyQt4 import QtGui, QtCore
import pyqtgraph as pg
app = QtGui.QApplication([])
mw = QtGui.QMainWindow()
p = pg.Plot... | # -*- coding: utf-8 -*-
## Add path to library (just for examples; you do not need this)
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
import numpy as np
from PyQt4 import QtGui, QtCore
import pyqtgraph as pg
app = QtGui.QApplication([])
mw = QtGui.QMainWindow()
p = pg.Plot... | en | 0.680104 | # -*- coding: utf-8 -*- ## Add path to library (just for examples; you do not need this) ## Start Qt event loop unless running in interactive mode. | 2.386478 | 2 |
devp2p/tests/test_peer.py | vaporyproject/pydevp2p | 0 | 6626949 | <filename>devp2p/tests/test_peer.py<gh_stars>0
from devp2p import peermanager
from devp2p import crypto
from devp2p.app import BaseApp
import devp2p.muxsession
import rlp
import devp2p.p2p_protocol
import time
import gevent
import copy
def get_connected_apps():
a_config = dict(p2p=dict(listen_host='127.0.0.1', li... | <filename>devp2p/tests/test_peer.py<gh_stars>0
from devp2p import peermanager
from devp2p import crypto
from devp2p.app import BaseApp
import devp2p.muxsession
import rlp
import devp2p.p2p_protocol
import time
import gevent
import copy
def get_connected_apps():
a_config = dict(p2p=dict(listen_host='127.0.0.1', li... | en | 0.521297 | # connect # money patches # 0.03 secs for 0.1mb # 0.28 secs for 1mb # 2.7 secs for 10mb # 3.7 MB/s == 30Mbit # connect # ethereum -loglevel 5 --bootnodes '' # connect_go() | 2.261127 | 2 |
algos/tf2algos/ioc.py | H0wardx/RLs | 1 | 6626950 | import rls
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from algos.tf2algos.base.off_policy import make_off_policy_class
from utils.tf2_utils import gaussian_clip_rsample, gaussian_likelihood_sum, gaussian_entropy
class IOC(make_off_policy_class(mode='share')):
'''
Learning ... | import rls
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from algos.tf2algos.base.off_policy import make_off_policy_class
from utils.tf2_utils import gaussian_clip_rsample, gaussian_likelihood_sum, gaussian_entropy
class IOC(make_off_policy_class(mode='share')):
'''
Learning ... | zh | 0.363415 | Learning Options with Interest Functions, https://www.aaai.org/ojs/index.php/AAAI/article/view/5114/4987 Options of Interest: Temporal Abstraction with Interest Functions, http://arxiv.org/abs/2001.00271 # [P, A] xxxx xxxxxx xxxxxxx xx xxx xxxx xxxx xxx xx ... | 2.009248 | 2 |