id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3385769 | <filename>appenv.py<gh_stars>0
#!/usr/bin/env python3
# appenv - a single file 'application in venv bootstrapping and updating
# mechanism for python-based (CLI) applications
# Assumptions:
#
# - the appenv file is placed in a repo with the name of the application
# - the name of the application/file is an ... | StarcoderdataPython |
3204008 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""Evalutate model output.
"""
from argparse import ArgumentParser
import numpy as np
import pandas as pd
from irmet import NDCG
parser = ArgumentParser(description='evaluate cdfm model output.')
parser.add_argument('--measure', type=str, help='a evaluation measure.')
parser.add... | StarcoderdataPython |
150750 | # -*- coding: utf-8 -*-
countries_data = [
{
'name': u'Afghanistan',
'alpha2': u'AF',
'alpha3': u'AFG',
'numeric': 4,
'independent': True,
},
{
'name': u'Åland Islands',
'alpha2': u'AX',
'alpha3': u'ALA',
'numeric': 248,
'indep... | StarcoderdataPython |
4824853 | <filename>sklearn_genetic/callbacks/validations.py
from ..parameters import Metrics
from .base import BaseCallback
def check_stats(metric):
if metric not in Metrics.list():
raise ValueError(
f"metric must be one of {Metrics.list()}, but got {metric} instead"
)
def check_callback(call... | StarcoderdataPython |
36569 | variable1 = input('Variable 1:')
variable2 = input('Variable 2:')
variable1, variable2 = variable2, variable1
print(f"Variable 1: {variable1}")
print(f"Variable 2: {variable2}") | StarcoderdataPython |
63276 | <reponame>ben174/pydvorak
import random
import threading
import time
from keymaps import DvorakMapper
from pool import Pool
from prompt import Prompt
from scoring import ScoreCard
from window import Window
class Game:
def __init__(self, screen):
self.scorecard = ScoreCard()
self.pool = Pool('EAINT... | StarcoderdataPython |
3312192 | <filename>yauber_algo/errors.py<gh_stars>1-10
class YaUberError(Exception):
pass
class YaUberAlgoArgumentError(YaUberError):
pass
class YaUberAlgoDtypeNotSupportedError(YaUberError):
pass
class YaUberAlgoInternalError(YaUberError):
pass
class YaUberAlgoFutureReferenceError(YaUberError):
pa... | StarcoderdataPython |
1758616 | <reponame>JacoRuit/tgbot<gh_stars>1-10
import json
class ReplyMarkup(object):
def dict(self):
raise NotImplementedError()
def json(self):
return json.dumps(self.dict())
def __str__(self):
return str(self.dict())
class ReplyKeyboardMarkup(ReplyMarkup):
def __init__(self, butto... | StarcoderdataPython |
3242711 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 NTT
# 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/LICEN... | StarcoderdataPython |
146142 | """
Copyright (c) 2020 <NAME> <<EMAIL>>. All rights reserved.
Licensed under the MIT License.
"""
import mido
DEBUG = False
class Note:
"""
Helper Class for Extracting Notes from MidiFile
"""
def __init__(self, pitch, velocity, channel):
"""
Initializing Note - Object
Args:
... | StarcoderdataPython |
118809 | from numpy import random # only used to simulate data loss
from decoder import Decoder # necessary for the functionality
from encoder import Encoder # necessary for the functionality
from utils import NUMBER_OF_ENCODED_BITS # only used for statistic
# showcase steering elements:
STOP_ENCODER_ON_DECODING = True #... | StarcoderdataPython |
133025 | <reponame>kbturk/Advent_of_Code2020
import sys, itertools
from copy import deepcopy
def main(args):
with open(args[1], 'r') as f:
l = sorted([int(line.strip()) for line in f])
mn, mx = 0, int(max(l)+3)
diff = []
#part1:
my_list = deepcopy(l)
my_list.insert(0,mn)
my_list.append(mx... | StarcoderdataPython |
1649508 | <filename>railrl/envs/contextual/__init__.py
from railrl.envs.contextual.contextual_env import (
ContextualEnv,
ContextualRewardFn,
)
__all__ = [
'ContextualEnv',
'ContextualRewardFn',
] | StarcoderdataPython |
30128 | <reponame>Elite-Volumetric-Capture-Sqad/DDRNet<filename>src/ops.py
import numpy as np
import sys
import tensorflow as tf
slim = tf.contrib.slim
def convertNHWC2NCHW(data, name):
out = tf.transpose(data, [0, 3, 1, 2], name=name)
return out
def convertNCHW2NHWC(data, name):
out = tf.transpose(data, [0, 2,... | StarcoderdataPython |
1693799 | <gh_stars>1-10
from collections import namedtuple
from dataclasses import dataclass
from typing import List
from .do_file_section import DoFileSection
from .imported_dataset import ImportedDataset, StataVar
from .stata_utils import (clean_stata_varname, gen_tmp_varname,
stata_string_escape, s... | StarcoderdataPython |
1714351 | '''Test case for whole template
'''
import unittest
class TemplateTestCase(unittest.TestCase):
def setUp(self):
pass
def test():
suite = unittest.TestSuite()
return suite
| StarcoderdataPython |
1790076 | # Script to register a new vSnap Backup Storage provider in SPP
# Use registervsnap.py -h for help
import json
import logging
from optparse import OptionParser
import copy
import sys
import spplib.sdk.client as client
logging.basicConfig()
logger = logging.getLogger('logger')
logger.setLevel(logging.INFO)
parser = Op... | StarcoderdataPython |
1706575 | import tensorflow as tf
import numpy as np
def residual_unit(inputs, depth, block_num, unit_num,l2_value = 0.00001):
f1, f2, f3 = depth
main_path = tf.keras.layers.BatchNormalization(axis=-1, name='BN_Unit_%s-%s-1' % (block_num, unit_num))(inputs)
main_path = tf.keras.layers.Activation('relu', name='Acti... | StarcoderdataPython |
3228331 | <gh_stars>1-10
# Copyright (c) 2014 Red Hat, 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 ag... | StarcoderdataPython |
3291564 | from feincms.module.page.models import Page
from feincms_button.contents import ButtonContent
Page.register_templates(
{
"title": "default",
"path": "base.html",
"regions": (("main", "Main content area"),),
}
)
PageButtonContent = Page.create_content_type(ButtonContent)
| StarcoderdataPython |
1667517 | #--- Exercicio 5 - Input, Estrutura de decisão e operações matemáticas
#--- Crie um programa que leia o salário de uma pessoa
#--- Use o método 50-20-10-20 - https://www.jaseimevirar.com/blog/como-voce-organiza-seu-orcamento-mensal/
#--- Informe os percentuais e valores que a pessoa deve utilizar em cada categoria
#--... | StarcoderdataPython |
98334 | # Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
... | StarcoderdataPython |
163214 | import random
n = int(input('Enter the number of friends joining (including you):\n'))
if n > 0:
names = {}
print('Enter the name of every friend (including you), each on a new line:')
while n > 0:
names[input()] = 0
n = n - 1
print('Enter the total bill value:')
bill = int(input())... | StarcoderdataPython |
3373677 | import os
import io
import regex
path = input("PATH: ")
count = 1
for subdir, dirs, _ in os.walk(path):
if any(
fname.upper().endswith((".JPG", ".JPEG"))
for fname in os.listdir(subdir)
):
try:
gmina = regex.match(
r"[0-9][0-9][0-9][0-9]([0-9][0-9][0-9])", s... | StarcoderdataPython |
1687596 | <filename>src/compas_slicer/print_organization/print_organization_utilities/data_smoothing.py
import logging
from copy import deepcopy
logger = logging.getLogger('logger')
__all__ = ['smooth_printpoint_attribute',
'smooth_printpoints_up_vectors',
'smooth_printpoints_layer_heights']
def smooth_... | StarcoderdataPython |
111916 | <filename>rele/management/commands/runrele.py
import logging
from django.conf import settings
from django.core.management import BaseCommand
from rele import config
from rele.management.discover import discover_subs_modules
from rele.worker import create_and_run
logger = logging.getLogger(__name__)
class Command(B... | StarcoderdataPython |
105481 | #! /usr/bin/env python3
# coding: utf-8
# modified example from https://weatherstack.com/documentation
import requests, hvac, getpass
# sets up the vault client, prompts for creds, and gather's the data
client = hvac.Client(url='http://localhost:8200')
client.auth.userpass.login(input("username: "), getpass.getpass(pr... | StarcoderdataPython |
1740875 | import logging
import subprocess
import tempfile
from aladdin.config import load_git_configs
from aladdin.lib.docker import DockerCommands, Tag
from aladdin.lib.git import Git
from aladdin.lib.k8s.helm import Helm
from aladdin.lib.utils import working_directory
from aladdin.lib.project_conf import ProjectConf
from ala... | StarcoderdataPython |
194049 | <filename>numba/minivect/llvm_codegen.py
"""
Generate LLVM code for a minivect AST.
"""
import sys
try:
import llvm.core
import llvm.ee
import llvm.passes
except ImportError:
llvm = None
import codegen
import minierror
import minitypes
import minivisitor
import ctypes_conversion
class LLVMCodeGen(co... | StarcoderdataPython |
3295549 | <reponame>ShenTengTu/leak_monitoring_app<gh_stars>0
import logging
from .data_class import DC_EMQXWebHookBody, DCSet_EMQXWebHookBody
from .endec import Decode
from .sse import SSEManager
logger = logging.getLogger("app_server")
class Tasks:
@staticmethod
async def emqx_webhook_to_sse(data_ins: DC_EMQXWebHook... | StarcoderdataPython |
43858 | import torch.utils.data as data
import os
import numpy as np
import cv2
#/mnt/lustre/share/dingmingyu/new_list_lane.txt
class MyDataset(data.Dataset):
def __init__(self, file, dir_path, new_width, new_height, label_width, label_height):
imgs = []
fw = open(file, 'r')
lines = fw.readlines()
... | StarcoderdataPython |
3243876 | """
blastn related functions
"""
import sys
import shlex
import subprocess
import re
import config
import core
if ( __name__ == '__main__'):
sys.stderr.write( "This is a module and not meant to be run as a stand alone program\n" )
exit( 1 )
def map_primers( region_id, primer3_dict, target_chrom, targe... | StarcoderdataPython |
155790 | <reponame>nickpalmer789/pokedex<filename>train.py
# set the matplotlib backend so figures can be saved in the background
import matplotlib
matplotlib.use("Agg")
# import the necessary packages
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras.preprocessing.image impo... | StarcoderdataPython |
1651836 | <gh_stars>0
#!/usr/bin/env python3
"""
Advent of Code 2019 Day 6: Universal Orbit Map
https://adventofcode.com/2019/day/6
"""
class Node:
def __init__(self, name):
self.__name = name
self.__known_distance_to_root = -1
self.parent = None
def distance_to_root(self):
if self.__... | StarcoderdataPython |
4829949 | <filename>utils/get_data.py
from encode_decode import *
## Getting data from the filename
NUM_STEPS = 60
def read_data(filename, vocab, window=NUM_STEPS, overlap=NUM_STEPS/2):
for text in open(filename):
text = encode_vocab(text, vocab)
for start in range(0, len(text) - window, overlap):
... | StarcoderdataPython |
21045 | <reponame>KaranToor/MA450<gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright 2013 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... | StarcoderdataPython |
3239876 | import requests
from django.conf import settings
def _build_url(path):
return "http://{host}:{port}{path}".format(
host = getattr(settings, 'NGX_CACHE_PURGE_HOST', 'localhost'),
port = getattr(settings, 'NGX_CACHE_PURGE_PORT', 80),
path = path,
)
class NginxManager(object):
def pur... | StarcoderdataPython |
1617022 | """
Date: 2022.02.02 18:14
Description: Omit
LastEditors: <NAME>
LastEditTime: 2022.02.02 18:14
"""
import contextlib
import os
import shutil
import click
from click_aliases import ClickAliasedGroup
from .c import Qt5Templates, c as _c, qt5 as _qt5
from .common import create_common_files
from .docker import docker as... | StarcoderdataPython |
1752779 | # This sample tests situations where bidirectional type inference
# influences the type of a generic function call.
from typing import Callable, Iterable, List, Literal, TypeVar
_T = TypeVar("_T")
def func1(arg: _T) -> _T:
return arg
v1: Literal["test"] = func1("test")
x: List[Literal["test"]] = ["test"]
v2... | StarcoderdataPython |
16760 | # Implementation of Shell Sort algorithm in Python
def shellSort(arr):
interval = 1
# Initializes interval
while (interval < (len(arr) // 3)):
interval = (interval * 3) + 1
while (interval > 0):
for i in range(interval, len(arr)):
# Select val to be inserted
... | StarcoderdataPython |
1632442 | from json import loads
from sqlite3 import connect
from shutil import copyfile
from base64 import b64decode
from os import environ, sep, path, remove, mkdir
from Crypto.Cipher import AES
from win32crypt import CryptUnprotectData
class Opera_Default:
def __init__(self, storage_path: str, storage_folder: str, bro... | StarcoderdataPython |
1697222 | from django.test import TestCase
from django.contrib.auth import get_user_model, authenticate
from django.core.exceptions import ValidationError
from core import models
def sample_user(email='<EMAIL>', password='<PASSWORD>'):
return get_user_model().objects.create_user(email, password)
class ModelTests(TestCase):... | StarcoderdataPython |
1672903 | # 读取人数和分数后输出最低分和最高分
print('计算最低分和最高分。')
print('注:输入"End"后停止读取分数。')
number = 0
tensu = [] # 空列表
while True:
s = input('第{}名的分数:'.format(number + 1))
if s == 'End':
break
tensu.append(int(s)) # 在末尾添加
number += 1
minimum = maximum = tensu[0]
for i in range(1... | StarcoderdataPython |
1620737 | class SolutionSort:
def longestWord(self, words: List[str]) -> str:
word_set = set(words)
# sort the words on the length and then the lexical word
words.sort(key = lambda s: (-len(s), s))
# Greedily to find the first word that qualifies
for word in words:
if all... | StarcoderdataPython |
1723443 | <reponame>haesleinhuepf/napari-workflow-optimizer<gh_stars>1-10
"""
This module is an example of a barebones QWidget plugin for napari
It implements the ``napari_experimental_provide_dock_widget`` hook specification.
see: https://napari.org/docs/dev/plugins/hook_specifications.html
Replace code below according to you... | StarcoderdataPython |
1611772 | <reponame>Asap7772/railrl_evalsawyer<filename>experiments/vitchyr/one_offs/try_doodad.py
import os
import doodad as pd
import doodad.ssh as ssh
import doodad.mount as mount
from doodad.ec2.credentials import AWSCredentials
THIS_FILE_DIR = os.path.dirname(os.path.realpath(__file__))
REPO_DIR = os.path.dirname(THIS_FI... | StarcoderdataPython |
3260391 | <filename>handlers/hint.py
from biothings_explorer.hint import Hint
import json
from .base import BaseHandler
ht = Hint()
class HintHandler(BaseHandler):
def get(self):
_input = self.get_query_argument('q', None)
print('input is {}'.format(_input))
if _input:
result = ht.query... | StarcoderdataPython |
83202 | <reponame>mrts/foodbank-campaign
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-01 22:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('volunteers', '0010_shiftle... | StarcoderdataPython |
86215 | <gh_stars>1-10
# Copyright 2021 MosaicML. All Rights Reserved.
from composer.models.unet.unet import UNet as UNet
from composer.models.unet.unet_hparams import UnetHparams as UnetHparams
_task = 'Image Segmentation'
_dataset = 'BRATS'
_name = 'UNet'
_quality = '69.1'
_metric = 'Dice'
_ttt = '21m'
_hparams = 'unet.yam... | StarcoderdataPython |
154959 | <reponame>RyanShaw98/WFLOP_Genetic_Algorithm
from API.misc import *
from API.WindFlo import simplified_gaussian_wake
turb_coords = np.asarray([[1270.5, 2194.5, 346.5, 1732.5, 2425.5, 346.5, 2194.5, 2425.5,
115.5, 346.5, 808.5, 1039.5, 577.5, 1501.5, 1732.5, 1963.5,
... | StarcoderdataPython |
1785182 | """ Optional Questions for Lab 11 """
from lab11 import *
# Q5
def hailstone(n):
"""
>>> for num in hailstone(10):
... print(num)
...
10
5
16
8
4
2
1
"""
while n is not 1:
yield n
if n % 2 == 0:
n //= 2
else:
n = ... | StarcoderdataPython |
189586 | # Copyright 2019 <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 required by applicable law or agreed to in writin... | StarcoderdataPython |
3271865 | <reponame>rihbyne/comp590assign3endpoint
from flask import Flask
from flask import jsonify
from flask import request
import json
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
welcome = {'project': 'comp590, android HTTP loopers/handlers, assign3'}
return jsonify(welcome), 200
@app.rou... | StarcoderdataPython |
177820 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | StarcoderdataPython |
123028 | #!/usr/bin/env python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import fnmatch
import glob
import optparse
import os
import shutil
import sys
import time
def IncludeFiles(filters, files):
... | StarcoderdataPython |
189839 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2021 CERN.
# Copyright (C) 2021 Graz University of Technology.
#
# Invenio-RDM-Records is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""OAI ID PID Provider."""
from flask import current_app
... | StarcoderdataPython |
3312588 | """An example of training PPO against OpenAI Gym Atari Envs.
This script is an example of training a PPO agent on Atari envs.
To train PPO for 10M timesteps on Breakout, run:
python train_ppo_ale.py
To train PPO using a recurrent model on a flickering Atari env, run:
python train_ppo_ale.py --recurrent --fli... | StarcoderdataPython |
1604361 | <gh_stars>1-10
#! /usr/bin/env python
"""Helper functions for processing Dakota parameter and results files."""
import os
import subprocess
import re
import yaml
import numpy as np
import collections
def is_dakota_installed():
"""Check whether Dakota is installed and in the execution path.
Returns
-----... | StarcoderdataPython |
4834082 | <gh_stars>1000+
# pylint: disable=missing-docstring
from fava.util.sets import add_to_set
def test_add_to_set_basic() -> None:
assert add_to_set(None, "test") == {"test"}
assert add_to_set({}, "test") == {"test"}
assert add_to_set({"test"}, "test") == {"test"}
def test_add_to_set_no_mutation() -> None:
... | StarcoderdataPython |
1762597 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:jingtongyu
# datetime:2020/6/7 10:14 下午
# software: PyCharm
from flask import g
from flask_restful import Resource, inputs
from flask_restful.reqparse import RequestParser
from sqlalchemy.exc import SQLAlchemyError
from app import hash_ids
from common.utils import g... | StarcoderdataPython |
132605 | <reponame>coblee/rotki
import contextlib
from contextlib import ExitStack
from http import HTTPStatus
from unittest.mock import patch
import pytest
import requests
from rotkehlchen.balances.manual import ManuallyTrackedBalance
from rotkehlchen.constants.assets import A_EUR
from rotkehlchen.fval import FVal
from rotke... | StarcoderdataPython |
119337 | <reponame>Shakil776/project-porzo<gh_stars>0
from rest_framework import serializers
from porzotokApp import models
from django.db.models import Q
# hotel details serializer
class HotelDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = models.HotelDetails
fields = "__all__"
de... | StarcoderdataPython |
110634 | <filename>101. Symmetric Tree/solution.py
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def compare(self, lleft, rright):
if (not lleft) and (not rright):
return ... | StarcoderdataPython |
116738 | from django import forms
class TodoForm(forms.Form):
text = forms.CharField(
max_length=100,
widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Todo',
'aria-label': 'Todo',
'aria-describedby': 'add-btn'
})
) | StarcoderdataPython |
95826 | <filename>server/main.py<gh_stars>0
import tornado.ioloop
import tornado.web
import json
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "x-requested-with")
class Conda... | StarcoderdataPython |
124390 | <filename>segrete.py
#!/usr/bin/env python
"""
Pull together the NCES data and the Segregation calculator to produce
general reports on segregation in the USA.
"""
import sys
import argparse
import operator
from segcalc import SegCalc
from nces_parser import NCESParser
from fips import fips_to_st
from xlwt import Wor... | StarcoderdataPython |
1699984 | <filename>pygcam/maptest.py
'''
.. Created on: 12/1/16
Map-generation API
.. Copyright (c) 2016 <NAME> and University of California
See the https://opensource.org/licenses/MIT for license details.
'''
from pygcam.diff import readCsv
from pygcam.map import drawMap
filename = '../tests/data/ws/corn-0/queryResult... | StarcoderdataPython |
162242 | from nose.tools import *
import pyexp
def setup():
print("Setup.")
def teardown():
print("Tear down.")
def test_basic():
print("Ran.")
| StarcoderdataPython |
84774 | # -*- coding: UTF-8 -*-
"""
@author: hhyo
@license: Apache Licence
@file: pt_archiver.py
@time: 2020/01/10
"""
from common.config import SysConfig
from sql.plugins.plugin import Plugin
__author__ = 'hhyo'
class PtArchiver(Plugin):
"""
pt-archiver归档数据
"""
def __init__(self):
self.path = 'pt-... | StarcoderdataPython |
191599 | termo = int(input('Primeiro Termo: '))
razao = int(input('Razão: '))
contador = 0
acumulador = termo
continuar = 1
while contador != 10:
print(acumulador, '→ ', end='')
acumulador += razao
contador += 1
print('PAUSA')
while continuar != 0:
continuar = int(input('Quer mostrar mais quantos termos?: '))
... | StarcoderdataPython |
69235 | <reponame>nobodxbodon/pyefun
# -*- coding:utf-8 -*-
import traceback, datetime
异常显示信息 = True
def 设置_异常处理_显示信息(显示信息=2):
"""
:param 显示信息: 0 不显示 1显示简单的 2显示详细的
:return:
"""
global 异常显示信息
异常显示信息 = 显示信息
def 异常处理返回类型逻辑型(function):
'装饰器'
def box(*args, **kwargs):
try:
... | StarcoderdataPython |
113286 | import os
import time
import sys
import paho.mqtt.client as mqtt
import json
from subprocess import check_output
from re import findall
def get_temp():
temp = check_output(["vcgencmd","measure_temp"]).decode("UTF-8")
return(findall("\d+\.\d+",temp)[0])
THINGSBOARD_HOST = '192.168.1.2'
ACCESS_TOKEN = '<KEY>'
... | StarcoderdataPython |
1617679 | <reponame>pzarabadip/thermof
"""
Thermof command line interface.
"""
| StarcoderdataPython |
119620 | import socket
import sys
import threading
import base64
import pytesseract as ocr
import numpy as np
import cv2
import struct
from PIL import Image
hostname = "redesb.space"
HOST = socket.gethostbyname(hostName) # Symbolic name meaning all available interfaces
PORT = 9666 # Arbitrary non-privileged port
H... | StarcoderdataPython |
3301569 | import copy
import enum
from typing import Optional, List, NoReturn
import toml
from . import config
from .enums import ContentType
class PredefinedMessage:
__slots__ = (
'name', 'envelope_from', 'address_from', 'envelope_to', 'address_to', 'address_cc', 'address_bcc', 'reply_to',
'subject', 'bo... | StarcoderdataPython |
1792903 | """Заглушки, фальшивки и т.п. для тестирования"""
from __future__ import annotations
from configs import Config
from processing import Generator
class GeneratorMock(Generator):
"""Заглушка генератора миссий"""
def __init__(self, config: Config):
super().__init__(config)
self.generations = [... | StarcoderdataPython |
1789339 | <filename>slabot/tasks.py
"""Define task to run with celery"""
import os
import json
from random import choice, randint
from bson.json_util import dumps
from celery import Celery
from dotenv import load_dotenv
from pymongo import MongoClient
# Load environment variables
load_dotenv()
# Celery settings
CELERY_BROKER_U... | StarcoderdataPython |
1729055 | from typing import Hashable
import dask.array as da
import numpy as np
from xarray import Dataset
from sgkit import variables
from sgkit.stats.aggregation import call_allele_frequencies
from sgkit.utils import (
conditional_merge_datasets,
create_dataset,
define_variable_if_absent,
)
def identity_by_sta... | StarcoderdataPython |
140277 | import os
from pathlib import Path
from PIL import Image
from skimage import io
SUFFIX = "_saliency.png"
def save_saliency_output(saliency_image, filename, output_dir):
predict = saliency_image
predict = predict.squeeze()
predict_np = predict.cpu().data.numpy()
im = Image.fromarray(predict_np * 255... | StarcoderdataPython |
40876 | <reponame>JannikHamperETH/conda
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 21 16:21:14 2019
@author: martinhe
"""
import numpy as np
import pandas as pd
from sklearn.neighbors.kd_tree import KDTree
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from shapely.geometry import Poin... | StarcoderdataPython |
3200810 | <filename>dymos/transcriptions/explicit_shooting/test/explicit_benchmark.py
import openmdao.api as om
import dymos as dm
from dymos.examples.brachistochrone.brachistochrone_ode import BrachistochroneODE
prob = om.Problem()
prob.driver = om.pyOptSparseDriver(optimizer='SLSQP')
tx = dm.transcriptions.ExplicitShootin... | StarcoderdataPython |
3383518 | <filename>warrior/plugins/robot_wrapper_plugin/bin/utils/robot_wrapper_utils.py
'''
Copyright 2017, Fujitsu Network Communications, 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.apa... | StarcoderdataPython |
112755 | <filename>docs/Tutorials/NetlistParser/bookshelf_parser.py
import re
from collections import namedtuple
from collections import OrderedDict
import json
# Token specification
COMMENT = r'(?P<COMMENT>\#.*\n)'
EOLN = r'(?P<EOLN>\n)'
NUM = r'(?P<NUM>-?\d*\.\d+|-?\d+\.?)'
SEMI = r'(?P<SEMI>;)'
LPAREN = r'(?P<LPAREN>\()'... | StarcoderdataPython |
4816296 | # -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Cyphon En... | StarcoderdataPython |
3217113 | # -*-encode=utf-8-*-
import codecs
import numpy as np
x, y = [], []
px, py = [], []
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_matrix(x, theta):
d = []
for i, e in enumerate(x):
d.append([sigmoid(float(np.mat(e) * np.mat(theta)))])
return np.mat(d)
def read(path='./data1.txt'):... | StarcoderdataPython |
14584 | import unittest
import numpy as np
import openjij as oj
import cxxjij as cj
def calculate_ising_energy(h, J, spins):
energy = 0.0
for (i, j), Jij in J.items():
energy += Jij*spins[i]*spins[j]
for i, hi in h.items():
energy += hi * spins[i]
return energy
def calculate_qubo_energy(Q, ... | StarcoderdataPython |
3202147 | <reponame>ronguest/Reaction-Game<gh_stars>0
# CircuitPlaygroundExpress_ReactionGame
# Author: <NAME>
import board
import neopixel
import time
import random
from analogio import AnalogIn
from adafruit_circuitplayground.express import cpx
RED = (0x10, 0, 0) # 0x100000 also works
YELLOW=(0x10, 0x10, 0)
GREEN = (0, 0x10,... | StarcoderdataPython |
3284776 | ###############################################
# <NAME> - PG Applied AI - Programming
# Unit tests, for the minimum edit distance
###############################################
import unittest # unit testing ftw
from excercise import Excercise # importing the actual code
class TestMethods(un... | StarcoderdataPython |
1660967 | <filename>meeting_tool_backend/note/migrations/0006_auto_20190529_1816.py
# Generated by Django 2.1.8 on 2019-05-29 18:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('note', '0005_auto_20190528_1518'),
]
operations = [
migrations.Rem... | StarcoderdataPython |
3369012 | <reponame>BruntonUWBio/cross-modal-ssl-htnet<filename>convert_data/convert_eeg_perturbations_xarray.py
import os
from data_load_utils import compute_xr_eeg_bal
lp = '/data1/users/stepeter/eeg_test/'
sp = '.../eeg_balance_perturbations_xarray/'
tlims = [-2, 2] # seconds
chans_sel1 = 'eeg' # 'eeg', 'emg', 'mocap', ... | StarcoderdataPython |
135667 | # Generated by Django 3.2.9 on 2022-01-09 16:47
import cloudinary.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
(... | StarcoderdataPython |
123772 | <reponame>zauberzeug/bacs<filename>input_output.py
import numpy as np
import os
def read_input(dataset: str):
def load(filename: str):
return np.loadtxt(os.path.join('input', dataset, filename), delimiter=',')
l = load('rays.dat').T
Sll = np.array([[
[line[0], line[3], line[5]],
[... | StarcoderdataPython |
147857 | """Group Model"""
class CBWGroup:
"""Group Model"""
def __init__(self,
id="", # pylint: disable=redefined-builtin
color="",
name="",
description="",
**kwargs): # pylint: disable=unused-argument
self.id = id # pylin... | StarcoderdataPython |
1699481 | <gh_stars>0
import random
import numpy as np
from LspAlgorithms.GeneticAlgorithms import Chromosome
class SelectionOperator:
"""
"""
def __init__(self, population) -> None:
"""
"""
self.population = population
self.chromosomeIndex = 0
self.setRouletteProba... | StarcoderdataPython |
3268544 | #!/usr/bin/env python
"""rssify.py: Generate an RSS XML file from all files in a directory.
https://github.com/tonyborries/YtChannelRss
"""
__author__ = "tonyborries"
__copyright__ = "Copyright 2015, tonyborries"
__credits__ = ["tonyborries"]
__license__ = "MIT"
__maintainer__ = "tonyborries"
__email__ = "<EMAIL>"
... | StarcoderdataPython |
1646785 | """formatting data for Regatta Platform"""
def format_data(header_ts, data):
data_string_list = []
for variable in VARIABLE_NAMES:
data_string = '{\n'
data_string += '"\tnames": ["{}"]\n'.format(variable)
data_string += '"\tvalueRows": [\n'
data_string_list.append(data_string)
... | StarcoderdataPython |
120999 | from gitpandas import Repository
import time
__author__ = 'willmcginnis'
if __name__ == '__main__':
g = Repository(working_dir='..')
st = time.time()
blame = g.cumulative_blame(branch='master', include_globs=['*.py', '*.html', '*.sql', '*.md'], limit=None, skip=None)
print(blame.head())
print(ti... | StarcoderdataPython |
3226456 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
# Copyright 2019 The GraphicsFuzz Project Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2... | StarcoderdataPython |
1703661 | <gh_stars>1-10
import copy
import json
import datetime
import typing
from functools import partial
from typing import Callable, Dict, Any, TypeVar, Type, Union
from dataclasses import ( # noqa: F401: needed for the __all__
field,
Field,
FrozenInstanceError,
InitVar,
MISSING,
asdict,
astuple... | StarcoderdataPython |
1689898 | <filename>Challenges-4/every3Num.py
# Challenge 1 : Create a function called every_three_nums that has one parameter named start.
# The function should return a list of every third number between start and 100 (inclusive).
# Date : Fri 05 Jun 2020 06:20:22 AM IST
def every_three_nums(start):
l... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.