id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
118875
import re # FIXME: depends on builtin_signed ######## COMMON API ########## E_INTEGER = 'INT' E_STRING = 'STR' E_BIN_RAW = 'RAW' E_BLOCK = 'BLK' E_BUILTIN_FUNC = 'BUILTIN' E_NEEDS_WORK = 'NEEDS_WORK' def e_needs_work(length=None): return {'len': length, 'final': False, 'type':E_NEEDS_WORK, 'data': None} ...
StarcoderdataPython
128657
<filename>streamlit/streamlit_sample.py #streamlitをpipでインストール後、 # streamlit run sample-streamlit.pyで実行 import streamlit as st import numpy as np import pandas as pd import requests from typing import Any st.title("HIT & BLOW") URL = "https://damp-earth-70561.herokuapp.com" def get_room(session: requests.Session, ro...
StarcoderdataPython
187578
<reponame>Doun92/UNIL_DH_memoire<filename>script_11/main.py """ Ce script unit tous les autres scrits qui s'occupent de tâches plus ponctuelles. Il parcourt chaque mot, lettre par lettre ou syllabe par syllabe, selon les particularités de chacun. auteur : <NAME> license : license UNIL """ class EvolutionPhone...
StarcoderdataPython
3264619
<filename>src/Day 3/feature/matching.py import cv2 from matplotlib import pyplot as plt # Load the images. img0 = cv2.imread(r'C:\Users\harrizazham98\Desktop\OpenCVForPython\resources\Day 3\kfc2.png', cv2.IMREAD_GRAYSCALE) img1 = cv2.imread(r'C:\Users\harrizazham98\Desktop\OpenCVForPython\resources\Day 3\kfc1.jpg...
StarcoderdataPython
1774656
<filename>TP_04/ejercicio_7/script_2/retrieval.py import re import struct from importer import * from normalizer import * from entity_extractor import * from constants import * class Retrieval: def __init__(self, metadata, on_memory=False, avoid_sets=False, avoid_skips=False): self.metadata = metadata ...
StarcoderdataPython
3256309
<gh_stars>0 import random import unittest import unittest.mock as mock import learning class TestLearning(unittest.TestCase): def test_get_random_belief_bit(self): with mock.patch('random.uniform', mock.Mock()) as mock_uniform: mock_uniform.return_value = 0 bit = learning.get_rand...
StarcoderdataPython
1758143
#!/usr/bin/env python3 # Copyright (C) 2016 Intel Corporation # # SPDX-License-Identifier: MIT # import unittest import logging import os from common import setup_sys_path, TestBase setup_sys_path() from oeqa.core.exception import OEQAMissingVariable from oeqa.core.utils.test import getCaseMethod, getSuiteCasesName...
StarcoderdataPython
1593
<reponame>Tillsten/skultrafast # -*- coding: utf-8 -*- """ Created on Thu Sep 17 21:33:24 2015 @author: Tillsten """ import matplotlib import matplotlib.pyplot as plt import numpy as np tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138...
StarcoderdataPython
1670812
<filename>genalg/sonicfeatures.py import librosa import numpy as np def silence_ratio(filename, thresh=20): """Ratio of quiet frames to not quiet frames.""" # read audiofile y, sr = librosa.load(filename, mono=True, sr=44100) # loudness S, phase = librosa.magphase(librosa.stft(y)) log_S = libro...
StarcoderdataPython
1694938
<reponame>GYosifov88/Python-Fundamentals # def factorial (a, b): # first_num = 1 # second_num = 1 # while a >= 1: # first_num = first_num * a # a -= 1 # while b >= 1: # second_num = second_num * b # b -= 1 # final_result = first_num / second_num # print (f'{final_...
StarcoderdataPython
136381
""" Command line utility for converting from pdf to text - Part of the basic business (decode parameters, open file and main function) are in fucntion, not classes. """ import time import threading import json import sys import getopt import os import signal from common.logmanager import LogManager from pdfut...
StarcoderdataPython
23679
# Flight duration model: Just distance # In this exercise you'll build a regression model to predict flight duration (the duration column). # For the moment you'll keep the model simple, including only the distance of the flight (the km column) as a predictor. # The data are in flights. The first few records are disp...
StarcoderdataPython
15425
from flask_wtf import FlaskForm from wtforms import SubmitField, SelectField, IntegerField, FloatField, StringField from wtforms.validators import DataRequired import pandas as pd uniq_vals = pd.read_csv("data/unique_cat_vals.csv", index_col=0) class InputData(FlaskForm): car = SelectField(label="Car", choices=u...
StarcoderdataPython
1663844
from kw_sorter.interfaces import ISortEntry from kw_sorter.sorter import Sorter, SortByEntry from kw_tests.common_class import CommonTestClass class ItemTest(CommonTestClass): def test_entry(self): entry = SortByEntry() assert not entry.get_key() assert ISortEntry.DIRECTION_ASC == entry.g...
StarcoderdataPython
68779
#sample_grammar.py import argparse import random import numpy.random import pcfgfactory import pcfg import utility parser = argparse.ArgumentParser(description='Replace low probability tokens with an UNK token for a given PCFG') parser.add_argument("inputfilename", help="File where the original PCFG is.") parser.ad...
StarcoderdataPython
1622464
#!/usr/bin/env python3 # by dongchao <<EMAIL>> from flask import render_template from . import dashboard @dashboard.route('/dashboard_index/', methods=['POST', 'GET']) def dashboard_index(): return render_template('dashboard.html')
StarcoderdataPython
167782
<filename>pyanime4k/error.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Name: PyAnime4K error Author: TianZerL Editor: K4YT3X """ from pyanime4k.wrapper import * """ typedef enum ac_error { AC_OK = 0, AC_ERROR_NULL_INSTANCE, AC_ERROR_NULL_PARAMETERS, AC_ERROR_NULL_Data,...
StarcoderdataPython
3211934
<reponame>bradhackinen/frdocs<filename>preprocessing/compile_parsed.py import os from argparse import ArgumentParser from pathlib import Path import random from collections import Counter from tqdm import tqdm import gzip from lxml import etree as et import pandas as pd from frdocs.preprocessing.parsing import parse_r...
StarcoderdataPython
1674720
#!/usr/bin/python3 """ imports Flask instance for gunicorn configurations gunicorn --bind 127.0.0.1:8001 wsgi:web_flask.app """ web_flask = __import__('web_flask.6-number_odd_or_even', globals(), locals(), ['*']) if __name__ == "__main__": """runs the main flask app""" web_flask.app.run...
StarcoderdataPython
21756
<gh_stars>0 from .l2norm import L2Norm from .multibox_loss import MultiBoxLoss from .multibox_focalloss import MultiBoxFocalLoss __all__ = ['L2Norm', 'MultiBoxLoss', 'MultiBoxFocalLoss']
StarcoderdataPython
83753
# Copyright (c) 2016-2020, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
StarcoderdataPython
3271287
<reponame>zatang007/BayesianOptimization<gh_stars>1-10 from bayes_opt.bayesian_optimization import Observable EVENTS = ["a", "b", "c"] class SimpleObserver(): def __init__(self): self.counter = 0 def update(self, event, instance): self.counter += 1 def test_get_subscribers(): observer...
StarcoderdataPython
3354519
# -*- coding: utf-8 -*- from dot_commands import setupCommands, fileAnalizer import os registerd = ["setup", "info"] '' def _prettyTable(data, total): maxSize = 0 postWordSize = 7 for line in data: if len(line["label"]) > maxSize: maxSize = len(line["label"]) data = sorted(data, key=lambda k: k['count'])[::-1...
StarcoderdataPython
3282622
<gh_stars>1-10 #! /usr/bin/python # -*- coding: utf-8 -*- import tensorflow as tf from tensorlayer import logging from tensorlayer.decorators import deprecated_alias from tensorlayer.layers.core import Layer from tensorlayer.files import utils # from tensorlayer.layers.core import TF_GRAPHKEYS_VARIABLES __all__ = [...
StarcoderdataPython
102345
# Generated by Django 4.0 on 2021-12-26 07:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stats', '0025_alter_player_created_by'), ] operations = [ migrations.AlterField( model_name='player', name='hash_redee...
StarcoderdataPython
3283629
<reponame>jasoncao11/nlp-notebook import torch import numpy as np from sklearn import metrics from transformers import BertModel from load_data import traindataloader, valdataloader BERT_PATH = '../bert-base-chinese' device = "cuda" if torch.cuda.is_available() else 'cpu' bert = BertModel.from_pretrained(BERT_PATH).to...
StarcoderdataPython
1790954
# -*- coding: utf-8 -*- """ A module into which all ORM classes are imported. To avoid circular imports almost all code should import ORM classes from this module rather than importing them directly, ``from h import models`` rather than ``from h.foo import models`` This is a convenience - you can just import this one...
StarcoderdataPython
4823451
<reponame>manishanker/octopuslabs-test #!/usr/bin/env python2.7 import MySQLdb import base64 from asymmetric_encryption import encrypt_message, decrypt_message import config class DBConnection: def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME): self.host = DB_HOST self.port = DB_P...
StarcoderdataPython
3325518
from .mixins import GroupRequiredMixin from rest_framework.response import Response from rest_framework.views import APIView import datetime, time import pandas as pd import sys, os import numpy as np import re from pandas.tseries.offsets import BDay import scipy.stats import igraph try: from .semutils.analytics....
StarcoderdataPython
167622
<reponame>Amazinggrace-Oduye/inventory_app<filename>updating_inventoryApp.py # -*- coding: utf-8 -*- """ Created on Tue May 19 21:29:59 2020 @author: <NAME> """ # -*- coding: utf-8 -*- """ Created on Thu Apr 23 20:43:03 2020 @author: <NAME> """ #importing modules from tkinter import * import tkint...
StarcoderdataPython
22662
# Copyright 2017 Rice University # # 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 writin...
StarcoderdataPython
3259041
# Import ParaMol modules from ParaMol.System.system import * from ParaMol.Force_field.force_field import * from ParaMol.Parameter_space.parameter_space import * import numpy as np class TestParameterSpace: # Kwargs dictionary for AMBER topology system. These are shared between all instances. kwargs_dict = {"...
StarcoderdataPython
3200731
<gh_stars>1-10 import argparse from collections import defaultdict from os import remove from random import randrange import genanki from pycasia import CASIA from hsk import HSK from models import get_model EXAMPLE_COUNT = 50 def create_deck(name, character_list=None, example_count=30): """ Create a deck ...
StarcoderdataPython
112117
# Copyright (c) 2021 PaddlePaddle 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 appli...
StarcoderdataPython
3375224
''' Initial conditions for the sctipt "int_sis_1.py" ''' import sympy as sym from sympy.utilities.lambdify import lambdify import numpy as np import math from scipy.constants import c as c_luz #metros/segundos c_luz_km = c_luz/1000; import os import git path_git = git.Repo('.', search_parent_directories=True).working...
StarcoderdataPython
3293261
# # -*- coding: utf-8 -*- # flake8: noqa F401 """This simply imports certain things for backwards compatibility.""" from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed pass from .thg...
StarcoderdataPython
1665873
<gh_stars>0 # rest_framework from rest_framework.generics import ListCreateAPIView from rest_framework.response import Response from rest_framework.views import APIView # api serializers from core.api.serializers import ( ContentSerializer, IssueSerializer, ) # models from core.cooggerapp.models import ( ...
StarcoderdataPython
3287031
<filename>py/closest_pair_test.py import unittest from py.closest_pair import ClosestPair class TestClosestPair(unittest.TestCase): def test_one_dimensional(self): with open("../src/closest_pair/test_data/one_dimensional_points.txt") as values: pair_util = ClosestPair([float(value) for value ...
StarcoderdataPython
83852
""" Contains classes and methods to obtain various regression based metrics to evaluate""" from sklearn import metrics import numpy as np import pandas as pd import math import sys sys.path.append("../config") class MetricsEval: """MetricsEval Class Evaluate metrics to evaluate model performance """ def metr...
StarcoderdataPython
3312455
# -*- encoding: utf-8 -*- """ Created by <NAME> at 22/09/2021 at 23:08:17 Project: py_dss_tools [set, 2021] """ class CNData: name = "CNData" name_plural = "CNData" columns = ['capradius', 'diacable', 'diains', 'diam', 'diastrand', 'emergamps', 'epsr', 'gmrac', 'gmrstrand', 'gmrunits', 'i...
StarcoderdataPython
56574
<filename>wealthbot/ria/forms/__init__.py from .riskQuestions import * from .riaSearchClients import * from .inviteProspect import * from .suggestedPortfolio import * from .riaClientAccount import *
StarcoderdataPython
1742792
<gh_stars>1-10 #!/usr/bin/env python3 import MySQLdb import sys import os from importlib import import_module USING_DB = 'default' if __name__ == '__main__': if len(sys.argv) < 2: print("File name of netflow required") exit(1) FNAME = sys.argv[1] cur_dir = os.path.dirname(os.path.abspa...
StarcoderdataPython
11376
from openpyxl import Workbook wb = Workbook() ws = wb.active data = [ ["Fruit", "Quantity"], ["Kiwi", 3], ["Grape", 15], ["Apple", 3], ["Peach", 3], ["Pomegranate", 3], ["Pear", 3], ["Tangerine", 3], ["Blueberry", 3], ["Mango", 3], ["Watermelon", 3], ["Blackberry", 3], ...
StarcoderdataPython
1768455
<filename>seed/setting.py import os from dynaconf import Dynaconf _root_path: str = os.path.dirname(os.path.abspath(__file__)) setting: Dynaconf = Dynaconf( env=os.environ.get('ENV', 'development').lower(), envvar_prefix='SEED', environments=True, settings_files=[ os.path.join(_root_path, '....
StarcoderdataPython
1672942
<filename>neutron/plugins/ml2/drivers/ovn/mech_driver/ovsdb/ovn_client.py # Copyright 2019 Red Hat, 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 # # ...
StarcoderdataPython
3227012
import numpy as np from tqdm import tqdm from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold, StratifiedKFold import multiprocessing as mp from model_eval_mse import ae_eval, vae_binned_eval, vae_eval # ============================================ # hyperparameter explorati...
StarcoderdataPython
3258119
import os import pytest from main import app, db from models import User @pytest.fixture def client(): app.config['TESTING'] = True os.environ["DATABASE_URL"] = "sqlite:///:memory:" client = app.test_client() cleanup() # clean up before every test db.create_all() yield client def test_ho...
StarcoderdataPython
115823
import getpass import os import sys import math from io import StringIO import shutil import datetime from os.path import splitext from difflib import unified_diff import pytest from astropy.io import fits from astropy.io.fits import FITSDiff from astropy.utils.data import conf import numpy as np import stwcs from st...
StarcoderdataPython
3380574
<gh_stars>0 import ipywidgets as ipw def get_start_widget(appbase, jupbase): #http://fontawesome.io/icons/ template = """ <table> <tr> <th style="text-align:center">Structures</th> <th style="width:70px" rowspan=2></th> <th style="text-align:center">Nanoribbons</th> <th ...
StarcoderdataPython
64146
<filename>masonite/helpers/misc.py def dot(data, compile_to=None): notation_list = data.split('.') compiling = "" compiling += notation_list[0] beginning_string = compile_to.split('{1}')[0] compiling = beginning_string + compiling dot_split = compile_to.replace(beginning_string + '{1}', '').spl...
StarcoderdataPython
3235159
<gh_stars>0 import setuptools setuptools.setup(name="nn-common-modules", version="1.2", url="https://github.com/abhi4ssj/nn-common-modules", author="<NAME>, <NAME>, <NAME>", author_email="<EMAIL>", description="Common modules, blocks ...
StarcoderdataPython
1680277
#!/usr/bin/env python from nodes import RootNode, FilterNode, HamlNode, create_node from optparse import OptionParser import sys VALID_EXTENSIONS=['haml', 'hamlpy'] class Compiler: def __init__(self, options_dict=None): options_dict = options_dict or {} self.debug_tree = options_dict.pop('debug_t...
StarcoderdataPython
1681219
<filename>thoughts/ricochet.py<gh_stars>1-10 # Data Structures & common logic from enum import Enum import heapq import matplotlib.pyplot as plt DIMENSION = 16 # size of the board DIRX = [0, 0, -1, 1] # directional vectors DIRY = [1, -1, 0, 0] # color vectors COLORS = ['red','blue','green','purple'] MAX_DEPTH = 30 cl...
StarcoderdataPython
4842885
<gh_stars>1-10 import pytest from mixer.main import mixer from smpa.models.address import Address, SiteAddress @pytest.fixture def address(): obj = Address() obj.number = "42" obj.property_name = "property name" obj.address_line_1 = "address line 1" obj.address_line_2 = "address line 2" obj.a...
StarcoderdataPython
199081
import sys import pkgutil import inspect import importlib from collections import OrderedDict def find_components(package, directory, base_class): components = OrderedDict() for module_loader, module_name, ispkg in pkgutil.iter_modules([directory]): full_module_name = "%s.%s" % (package, module_name)...
StarcoderdataPython
1680224
import os import sys import click from ftcli.Lib.Font import Font from ftcli.Lib.utils import getFontsList, makeOutputFileName, guessFamilyName @click.group() def setLineGap(): pass @setLineGap.command() @click.argument('input_path', type=click.Path(exists=True, resolve_path=True)) @click.option('-p', '--perce...
StarcoderdataPython
83153
<reponame>sunshot/LeetCode<gh_stars>0 from typing import List class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: prefix = "" if not strs or not strs[0]: return prefix for i in range(len(strs[0])): curr = None for x in strs: ...
StarcoderdataPython
1765679
<filename>app/maths.py<gh_stars>0 def get_semester(*, month: int) -> int: if month <= 6: return 1 return 2
StarcoderdataPython
3256659
<reponame>kenchan0226/control-sum-cmdp """ Evaluate the baselines ont ROUGE/METEOR""" """ Adapted from https://github.com/ChenRocks/fast_abs_rl """ import argparse import json import os from os.path import join, exists from utils.evaluate import eval_meteor, eval_rouge def main(args): dec_dir = join(args.decode_...
StarcoderdataPython
3334069
import hashlib import unittest from unittest.mock import Mock, patch from kademlia.crypto import Crypto from kademlia.domain.domain import PersistMode, is_new_value_valid, validate_authorization from kademlia.exceptions import InvalidSignException from kademlia.utils import digest, sharedPrefix, OrderedSet class Uti...
StarcoderdataPython
1779851
from networkx.algorithms.euler import is_eulerian from networkx.algorithms.efficiency_measures import global_efficiency from networkx.algorithms.efficiency_measures import local_efficiency from networkx.algorithms.distance_regular import is_distance_regular from networkx.algorithms.components import number_connected_co...
StarcoderdataPython
3345814
DEFAULT_COMMAND_MAP = { ".c": "$CC -o $target $CFLAGS $CCFLAGS $sources", ".cpp": "$CXX -o $target $CXXFLAGS $CCFLAGS $sources", }
StarcoderdataPython
3325869
import setuptools __version__ = "1.0rc1" __author__ = "<NAME>" def readme(): with open('README.md') as f: return f.read() setuptools.setup( name='N_Network', version=__version__, license='MIT License', description='A personal implementation of a Neural Network', long_description=read...
StarcoderdataPython
3349633
"""Objects Module.""" def jlpoint(x, y, z): """Return a 3D coordinate dict. Args: x (float): X-coordinate. y (float): Y-coordinate. z (float): Z-coordinate. Returns: (dict): 3D coordinate object. """ try: x, y, z = floa...
StarcoderdataPython
50694
import cv2 import numpy as np img1 = cv2.imread('3D-Matplotlib.png') img2 = cv2.imread('mainlogo.png') # THREE DIFFERENT WAYS OF ADDING TWO PICTURE #1 #add = img1+ img2 #2 #img = cv2.add(img1,img2) # USING BUILT IN FUNCTION OF CV2 TO ADD TWO IMAGES #3 #weighted_add = cv2.addWeighted(img1, 0.6, img2,...
StarcoderdataPython
28231
<reponame>chfw/gease from mock import MagicMock, patch from nose.tools import eq_ from gease.contributors import EndPoint from gease.exceptions import NoGeaseConfigFound class TestPublish: @patch("gease.contributors.get_token") @patch("gease.contributors.Api.get_public_api") def test_all_contributors(sel...
StarcoderdataPython
53058
<reponame>Ntermast/BKE<filename>bke/bke_client/forms.py from django import forms from django.core.validators import FileExtensionValidator from .models import Channel, Podcast class ChannelForm(forms.ModelForm): image = forms.ImageField(required=True) class Meta: model = Channel fields = ('im...
StarcoderdataPython
4810441
# coding=utf-8 from flask import Flask, request, jsonify, g from Plan import RequestException import Plan import traceback app = Flask(__name__) def wrap_response(result): return jsonify(result=result, error=None) def success(): return wrap_response(True) # 测试服务器 @app.route('/') def ping(): return su...
StarcoderdataPython
1702342
<gh_stars>0 #!/usr/bin/env python import argparse import os from odt import ODTPage class HTMLGenerator: def __init__(self, odtfile, page=1, pagename='page', title='Title', index=None): self.page = page self.pagename = pagename self.title = title self.index = index self.ge...
StarcoderdataPython
138720
<gh_stars>0 from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from .models import SlackAlertUserData from cabot3.cabotapp.models import Service import json import re @csrf_exempt def slack_message_callback(request): payload = json.loads(request.POST['payload']) service...
StarcoderdataPython
182216
from setuptools import setup setup( name='foucluster', description='Clustering of songs using Fourier Transform', long_description='Similarities among songs are computed using Fast Fourier ' 'Transform. With this information, unsupervised machine learning' ' is applied.', ...
StarcoderdataPython
78655
"""Author: <NAME>, Copyright 2019, MIT License""" from multiarchy.loggers.logger import Logger import tensorflow as tf class TensorboardInterface(Logger): def __init__( self, replay_buffer, logging_dir, ): # create a separate tensor board logging thread self.replay_b...
StarcoderdataPython
133389
<filename>flex_config/__init__.py import json from typing import Any, Dict, Iterable, Optional, Sequence, Set, Union from .aws_source import AWSSource from .config_source import ConfigSource from .env_source import EnvSource from .yaml_source import YAMLSource class FlexConfig(Dict[str, Any]): """ Holds config v...
StarcoderdataPython
3358151
# coding: utf-8 import socketserver import os # Copyright 2020 <NAME>, <NAME>, <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 # ...
StarcoderdataPython
3393941
<gh_stars>1-10 """This module implements the main basic methods to Image Processing.""" try: from postimpressionism.Setimpressionism import * except ModuleNotFoundError: from Setimpressionism import * # If I am testing from the directory . . . img_path = "C:\\" def _path_ (p = None): """Setter and Getter for de...
StarcoderdataPython
4804193
<filename>compose/views.py<gh_stars>1-10 import datetime import itertools from django.contrib import auth from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import AuthenticationForm from django.shortcuts import get_object_or_404, redirect, render from .models import DailyEntry, ...
StarcoderdataPython
1731032
import sys sys.path.insert(0, './') from raspberrypy.network.wifi import Wifi from time import sleep if __name__ == '__main__': wifi = Wifi(interface='wlan0', ignore_root_limit=True) def get_pos(wifi): wifi.update() return (wifi.cells['CandyTime_804_plus'].siglevel, wifi.cells['CandyTime_804...
StarcoderdataPython
4828198
import sys import os import torch import torch.nn as nn import numpy as np # import torchvision from torch.utils.data import DataLoader from datetime import datetime import random import argparse from utils import * def parse_args(): parser = argparse.ArgumentParser() parser.add_argument(...
StarcoderdataPython
1776479
<reponame>LatticeLabVentures/BeamNet<filename>examples/starkex-cairo/starkware/python/expression_string.py """ The class ExpressionString allows creating strings that represent arithmetic expressions with the correct amount of parentheses. For example, you may define: a = ExpressionString.highest('a') b = Expr...
StarcoderdataPython
3266828
import uuid from django.db import models from multiselectfield import MultiSelectField from common.util.choices import ( treasure_grade_choices, treasure_type_choices, currency_denomination_choices, dices_choices, damage_type_choices, weapon_type_choices, weapon_properties_choices, ) # Cre...
StarcoderdataPython
46099
__all__ = [ 'order_rate_over_time' ] from .order_rate_over_time import order_rate_over_time
StarcoderdataPython
3355823
from design_baselines.data import StaticGraphTask, build_pipeline from design_baselines.logger import Logger from design_baselines.utils import spearman from design_baselines.permmdtraining_rep_coms_cleaned.trainers import ConservativeObjectiveModel from design_baselines.data import StaticGraphTask, build_pipeline from...
StarcoderdataPython
3244789
<reponame>jia-wan/GeneralizedLoss-Counting-Pytorch import torch import os import numpy as np from datasets.crowd import Crowd from models.vgg import vgg19 import argparse args = None def train_collate(batch): transposed_batch = list(zip(*batch)) images = torch.stack(transposed_batch[0], 0) points = transp...
StarcoderdataPython
121281
from api.dataset.models import DataSchema, Dataset def verify_settings(model, p_key, settings): details = eval(model).get(p_key) for key, setting in settings.items(): print(getattr(details, key), setting) setting = setting if setting else None assert getattr(details, key) == setting ...
StarcoderdataPython
1622367
#!/usr/bin/python import subprocess import argparse from prometheus_client import Summary from prometheus_client import start_http_server, Gauge import random import time def bandwidth_measure_metric(server_ip,server_port): ''' Returns current network bandwidth in Mbps ''' try: p = subprocess....
StarcoderdataPython
3230229
<filename>streaming_helpers.py import queue import time import numpy as np class CameraInformation: def __init__(self, cam_id: str): self._frame_queue: queue.Queue = queue.Queue(maxsize=1) self._frame_shape = None self._last_frame_time = None self.is_online = True self.node...
StarcoderdataPython
1798481
<gh_stars>0 from flask import Flask, jsonify, render_template, request, redirect, session, url_for import requests,os,json from flask_googlemaps import Map from flask_googlemaps import icons from app import app, mainEngine, gMap @app.route('/') def index(): return render_template("mainlogin.html") @app.route('/lo...
StarcoderdataPython
3214227
import torch from torch import nn class Model(nn.Module): def __init__(self): super().__init__() self._conv_part = nn.Sequential( nn.Conv2d(3, 6, 5, padding=2), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(6, 16, 5), nn.ReLU(), nn.Ma...
StarcoderdataPython
3278805
# В рамках этого испытания вы реализуете небольшой набор функций, работающих с отрезками прямых на двухмерной плоскости. # Отрезок в нашем случае будет кодироваться в виде пары пар и выглядеть как-то так: ((x1, y1), (x2, y2)) # (вложенные пары — это концы отрезка). Вам нужно реализовать четыре функции: # # is_degenerat...
StarcoderdataPython
4820067
""" Code Generator - https://github.com/wj-Mcat/code-generator Authors: <NAME> (吴京京) <https://github.com/wj-Mcat> 2020-now @ Copyright wj-Mcat 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 h...
StarcoderdataPython
1796884
<reponame>ryanapfel/clustering from src.utils import Cluster, Scenes, Users, User import pandas as pd import numpy as np import math import random class K_Mean: def __init__(self, _df, _K): self.df = _df self.emotions = self.df.emotion.unique() self.emotionMap = {e: idx for idx, e in enumerate(self.emo...
StarcoderdataPython
3303845
#!/usr/bin/env python import npyscreen, curses class MyTestApp(npyscreen.NPSAppManaged): def on_start(self): # When Application starts, set up the Forms that will be used. # These two forms are persistent between each edit. self.add_form("MAIN", MainForm, name="Screen 1", color="IMPORTANT",...
StarcoderdataPython
1769739
""" This modules implements the bulk of Bot Evolution. """ import numpy as np import copy import settings from utility import seq_is_equal, distance_between, angle_is_between, find_angle from neural_network import NNetwork, sigmoid, softmax class Population: """ The environment of bots and food. """ ...
StarcoderdataPython
96603
<gh_stars>1-10 '''This module implement deepracer boto client''' import abc import time import random import logging import botocore import boto3 from markov.log_handler.logger import Logger from markov.constants import (NUM_RETRIES, CONNECT_TIMEOUT) from markov.boto.constants import BOTO_ERROR_MSG_FORMAT LOG = Logg...
StarcoderdataPython
43021
"""Views fo the node settings page.""" # -*- coding: utf-8 -*- import logging import httplib as http from dropbox.rest import ErrorResponse from dropbox.client import DropboxClient from urllib3.exceptions import MaxRetryError from framework.exceptions import HTTPError from website.addons.dropbox.serializer import Dro...
StarcoderdataPython
1669588
<gh_stars>10-100 import torch import numpy as np from PIL import Image import torchvision.transforms as transforms from data.augmentations import Augmentation from data import BaseTransform import cv2 class LoadImage(object): def __init__(self, space='BGR'): self.space = space def __call__(self, path...
StarcoderdataPython
3306903
<reponame>oswald-pro/LocatePhoneNumber import phonenumbers import folium from PhoneNumbers import number from phonenumbers import geocoder # Get your API key from https://opencagedata.com/ Api_key = '<YOUR API KEY>' oswaldNumber = phonenumbers.parse(number) # Get Country Location of the number yourLacation = geocode...
StarcoderdataPython
36366
import argparse import os import torch import matplotlib.pyplot as plt from torch.utils.data.distributed import DistributedSampler from torch import distributed as dist from torch import optim from tqdm import tqdm from torch_ema import ExponentialMovingAverage from cifr.core.config import Config from cifr.models.bui...
StarcoderdataPython
1776549
#!/usr/bin/env python3 import sys from readers.read_ape import ApeReader FILE_PATH = sys.argv[1] ape_reader = ApeReader(FILE_PATH) print('Ocorrencias do erro: {}'.format(len(ape_reader.error_lines))) cores = list() for k in ape_reader.corrections: flat = [sub[1] for sub in k] cores.append(flat) print('Nenh...
StarcoderdataPython
42361
#!/usr/bin/python2.6 # Copyright 2011 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 ...
StarcoderdataPython