id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
3495217
#!/usr/bin/python # a timing script for FFTs and convolutions using OpenMP import sys, getopt import numpy as np from math import * from subprocess import * # for popen, running processes import os import re # regexp package import shutil def mvals_from_file(filename): mvals = [] if os.path.isfile(filename)...
StarcoderdataPython
3283254
<reponame>ndkruif/8dm40-machine-learning10 import numpy as np def lsq(X, y): """ Least squares linear regression :param X: Input data matrix :param y: Target vector :return: Estimated coefficient vector for the linear regression """ # add column of ones for the intercept ones = np.ones...
StarcoderdataPython
12845598
<filename>paprika/actions/files/Pipe.py from paprika.repositories.FileRepository import FileRepository from paprika.repositories.ProcessPropertyRepository import ProcessPropertyRepository from paprika.repositories.ProcessRepository import ProcessRepository from paprika.system.logger.Logger import Logger from paprika.ac...
StarcoderdataPython
158568
<gh_stars>0 import utility from sklearn.model_selection import train_test_split from sklearn.neighbors import NearestNeighbors import static_sim_functions as smf # import ts_preprocessing as ts_data import numpy as np import os from pathlib import Path import ast ''' This class is created to simulate models for UI for ...
StarcoderdataPython
6641437
############################################################################## # Copyright 2016-2019 Rigetti Computing # # 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...
StarcoderdataPython
12828348
#!/usr/bin/env python3 import json import logging import os import traceback import git import requests import yaml root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) root_logger.addHandler(logging.StreamHandler()) def post(path: str, data: dict, params=None): if params is None: para...
StarcoderdataPython
3373397
<reponame>eherr/vis_utils #!/usr/bin/env python # # Copyright 2019 DFKI GmbH. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights ...
StarcoderdataPython
9608210
<gh_stars>1-10 #!/usr/bin/env python3 from datetime import datetime as dt2 from dateutil.relativedelta import * from dateutil.rrule import * import os, sys, re, traceback, calendar, datetime import json, unicodedata from bpaTools import Logger def isInteger(s:str) -> bool: try: n:int = int(s) ...
StarcoderdataPython
4863446
import os import pickle import sys from typing import List import numpy as np import pandas as pd os.environ["OPENBLAS_NUM_THREADS"] = "1" sys.path.append("../../") from advertising.data_structure.Campaign import Campaign from advertising.optimizers.CampaignOptimizer import CampaignOptimizer from environments.Settin...
StarcoderdataPython
3311101
<filename>datamessage.py<gh_stars>1-10 import json import telegram import sys def notify_ending(message): token = 'XXXX' chat_id = 'XXXX' bot = telegram.Bot(token=token) bot.sendMessage(chat_id=chat_id, text=message) f = open('data_file.json') data = json.load(f) length = l...
StarcoderdataPython
3584350
""" utils.py Contains helper functions. """ import math import os import numpy as np import torch import torch.nn.functional as F EPSILON_DOUBLE = torch.tensor(2.220446049250313e-16, dtype=torch.float64) EPSILON_SINGLE = torch.tensor(1.19209290E-07, dtype=torch.float32) SQRT_TWO_DOUBLE = torch.tensor(math.sqrt(2),...
StarcoderdataPython
1872914
<gh_stars>0 N, K, Q = [int(x) for x in input().split()] seikai = [0] * N for _ in range(Q): a = int(input()) seikai[a-1] += 1 for i in range(N): if K - (Q - seikai[i]) > 0: print("Yes") else: print("No")
StarcoderdataPython
4847300
def build_array_from_tree(root): "Convert a tree into an array (flatten a tree)" current_stack = [] output = [] next_queue = Queue() current_stack.append(root) while len(current_stack) > 0 and \ len(next_queue) > 0: output.append([]) while len(current_stack) > 0: ...
StarcoderdataPython
11284926
''' Name: time_tracker.py Author: <NAME> Date: 28/05/2020 Version: 0.0 DESCRIPTION --------------- Simple time tracker script to track your time ''' import argparse import datetime import json import os import time from PySide2.QtWidgets import * import psutil import win32gui import win32process class TimeTracker: ...
StarcoderdataPython
11316266
<reponame>RileyWClarke/flarubin import numpy as np import pandas as pd from .baseSlicer import BaseSlicer from rubin_sim.maf.plots.moPlotters import MetricVsH, MetricVsOrbit from .orbits import Orbits __all__ = ['MoObjSlicer'] class MoObjSlicer(BaseSlicer): """ Slice moving object _observations_, per object an...
StarcoderdataPython
5043371
from .loadxml import battleStart, battleWrite from .interpret import importModule, importFunction from .utilities import * from .errors import * from .instance import Instance
StarcoderdataPython
6419829
<reponame>rbarzic/ALIGN-public import json import pathlib import re from pprint import pformat from align.cell_fabric import transformation from Intel.Intel_P1222p2_PDK.IntelP1222p2Canvas import IntelP1222p2Canvas if __name__ == "__main__": with open("comparator.json", "rt") as fp: d = json.load(fp) ...
StarcoderdataPython
9670361
''' Your task is to write a function maskify, which changes all but the last four characters into '#'. Examples maskify("4556364607935616") == "############5616" maskify( "64607935616") == "#######5616" maskify( "1") == "1" maskify( "") == "" # "Wha...
StarcoderdataPython
9712552
import datetime def size_format(size_b): if(size_b < 1024): return "%.2f"%(size_b) + 'B' elif(size_b < 1024 * 1024): return "%.2f"%(size_b / 1024) + 'KB' elif(size_b < 1024 * 1024 * 1024): return "%.2f"%(size_b / 1024 / 1024) + 'MB' elif(size_b > 1024 * 1024 * 1024 * 1024): ...
StarcoderdataPython
5063413
# Module that cast a decimal number to fraction notation # Input: # number: number to cast # return: # tuple[0]: is the error, None is returned when the process has no error # otherwise a string with message of error is returned # tuple[1]: is number in fraction notation from fractions import Fr...
StarcoderdataPython
11359806
<filename>flask_qiniustorage.py # -*- coding: utf-8 -*- try: from urlparse import urljoin except ImportError: from urllib.parse import urljoin import qiniu as QiniuClass class Qiniu(object): def __init__(self, app=None): self.app = app if app is not None: self.ini...
StarcoderdataPython
3404314
"""empty message Revision ID: 1c306b9d32 Revises: <PASSWORD> Create Date: 2015-09-15 12:14:05.356636 """ # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '<PASSWORD>' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust...
StarcoderdataPython
1923265
<filename>rsvqa/grad_cam.py import argparse from utils import seed_everything, load_data, LabelSmoothing,encode_text #,Model import wandb import pandas as pd import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader, Dataset import torch.optim as optim import torch.optim.lr_scheduler...
StarcoderdataPython
3535210
import time import torch from torch.backends import cudnn from backbone import HybridNetsBackbone import cv2 import numpy as np from glob import glob from utils.utils import letterbox, scale_coords, postprocess, BBoxTransform, ClipBoxes, restricted_float, boolean_string from utils.plot import STANDARD_COLORS, standard_...
StarcoderdataPython
1703498
#!/router/bin/python from .trex_general_test import CTRexGeneral_Test, CTRexScenario from .trex_nbar_test import CTRexNbarBase from CPlatform import CStaticRouteConfig from .tests_exceptions import * #import sys import time from nose.tools import nottest # Testing client cfg ARP resolve. Actually, just need to check t...
StarcoderdataPython
77444
#!/usr/bin/env python # Tested with both Python 2.7.6 and Python 3.4.3 # # This Python code collects the source code for testing acados # on microcontrollers, putting all the necessary C files in # one directory, and header files in the sub-directory include. # # The idea is that when compiling the testing code of aca...
StarcoderdataPython
12810706
count=1000 total=0 while count > 0: if count %3==0 or count %5==0: total=total+count count=count-1 print(total)
StarcoderdataPython
1649373
<gh_stars>0 import pymongo import os from pymongo import MongoClient from dotenv import load_dotenv CLUSTER = os.getenv('DB_CLUSTER') DATABASE = os.getenv('DB_NAME') COLLECTION = os.getenv('DB_COLLECTION') cluster = MongoClient(CLUSTER) db = cluster[DATABASE] collection = db[COLLECTION] def sort_by_points(): ret...
StarcoderdataPython
4921159
# Practice XGBoost model for Pima Indians dataset import pandas as pd from numpy import loadtxt from xgboost import XGBClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # load data dataset = loadtxt('pima-indians-diabetes.csv', delimiter=",") # split data into ...
StarcoderdataPython
333157
<gh_stars>0 # SPDX-License-Identifier: MIT # Copyright (c) 2022 <NAME> <https://github.com/AndrielFR> import asyncio import time import feedparser from bs4 import BeautifulSoup from mews.monitor.sources import BaseRSS from mews.utils import http from mews.utils.database import exists_post class AnimeNew(BaseRSS): ...
StarcoderdataPython
4954175
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutClasses(Koan): class Dog: "Dogs need regular walkies. Never, ever let them drive." def test_instances_of_classes_can_be_created_adding_parentheses(self): # NOTE: The .__name__ attribute will convert the class ...
StarcoderdataPython
12803100
<reponame>uibcdf/MolSysMT<filename>molsysmt/protonation.py from molsysmt._private_tools.exceptions import * def has_hydrogens(molecular_system): from molsysmt.multitool import get output = False n_hydrogens = get(molecular_system, target='atom', selection='atom_type=="H"', n_atoms=True) if n_hydrog...
StarcoderdataPython
11379742
def convert_distance(miles): km = miles * 1.6 result = "{} miles equals {:.1f} km".format(miles, km) return result print(convert_distance(13.1))
StarcoderdataPython
6672243
<filename>fashion-mnist/fashion-keras/src/neural_network.py """Neural network class.""" import tensorflow as tf class NeuralNetwork(tf.keras.Model): """Neural network that classifies Fashion MNIST-style images.""" def __init__(self): super().__init__() self.sequence = tf.keras.Sequential([ ...
StarcoderdataPython
1882550
<reponame>markhankins/podannotator __version__ = '0.1' #!/usr/local/bin/python3 from kubernetes import client, config from kubernetes.client.rest import ApiException import sys from prettytable import PrettyTable config.load_kube_config() def print_help(): print('I need the namespace(s) as an argument') if len(s...
StarcoderdataPython
1751038
<reponame>brad90four/bradbot<filename>src/exts/trail_status.py<gh_stars>0 import feedparser from loguru import logger from nextcord import Embed from nextcord.ext import commands class TrailStatus(commands.Cog): "Send an embed about the bot's ping." def __init__(self, bot: commands.Bot): self.bot = b...
StarcoderdataPython
8144377
<reponame>Anancha/Programming-Techniques-using-Python from random import choice from time import time my_names = ['Suman','Mohan','Divya','Sugandh'] my_subjects = ['Chemistry','Biology','Maths'] def my_list(num_students): mylist = [] for loop in range(num_students): mystudents = { ...
StarcoderdataPython
1610068
from break_ import Break_ class Instruction: player_actions = iter([action.rstrip('\n') for action in open('C:\\Users\\<NAME>\\Documents\\Synacor Challenge\\auto_player.txt')]) def __init__(self, memory, registers): self.memory = memory self.registers = registers self.stack = [] ...
StarcoderdataPython
9798075
<filename>server/galaxyls/services/xml/scanner.py """ This code is based on the Eclipse/Lemminx XML language server implementation: https://github.com/eclipse/lemminx/tree/master/org.eclipse.lemminx/src/main/java/org/eclipse/lemminx/dom Only the minimum subset of the XML dialect used by Galaxy tool wrappers is support...
StarcoderdataPython
3431596
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
StarcoderdataPython
3314970
# coding: utf-8 import csv # I want to import the csv library. from pathlib import Path # I want the Path function from the pathlib library. """Part 1: Automate the Calculations. Automate the calculations for the loan portfolio summaries. First, let's start with some calculations on a list of prices for 5 loans. ...
StarcoderdataPython
6522057
import numpy as np import pytest from pizza_cutter.slice_utils.locate import build_slice_locations from ..masks import ( in_unique_coadd_tile_region, get_slice_bounds, _mask_one_slice_for_gaia_stars, _mask_one_slice_for_missing_data, MASK_INTILE, MASK_GAIA_STAR, MASK_NOSLICE, _wrap_ra,...
StarcoderdataPython
8076789
"""Module constituting the commandscript pylint rated 10.0/10 """ MENU_DICTIONARY = {} HELP_DICTIONARY = {} COMMANDSCRIPT = [] HEADERS = ['COMMANDS', 'DEFAULTKEYS', 'NAVIGATION', 'DISPLAY', 'SEARCHING', 'ORGANIZING NOTES', 'DEFAULTS', ...
StarcoderdataPython
3550049
import pandas as pd import numpy as np from sklearn import datasets from sklearn.svm import SVC from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split # method to plot confusion matrices def plot_con...
StarcoderdataPython
1667067
<filename>dataStoreExceptions.py # data store custom exceptions and error response classes class dataStoreException(Exception): # base class for other custom exceptions pass class FileNotFound(dataStoreException): def __init__(self, message="File does not exist. Requires valid file path."): ...
StarcoderdataPython
8111442
<gh_stars>0 ''' TMC, XTI, tsproj parsing utilities ''' import collections import logging import os import pathlib import re import types import lxml import lxml.etree from .code import (get_pou_call_blocks, program_name_from_declaration, variables_from_declaration, determine_block_type) # Registr...
StarcoderdataPython
1784733
from collections import OrderedDict TARGETS = OrderedDict([('2.7', (2, 7)), ('3.0', (3, 0)), ('3.1', (3, 1)), ('3.2', (3, 2)), ('3.3', (3, 3)), ('3.4', (3, 4)), ('3.5', (3, 5)), ...
StarcoderdataPython
1978077
<reponame>euroledger/aries-cloudagent-python<gh_stars>1-10 """Basic message admin routes.""" from aiohttp import web from aiohttp_apispec import docs, request_schema from marshmallow import fields, Schema from ...connections.models.connection_record import ConnectionRecord from ...storage.error import StorageNotFoun...
StarcoderdataPython
1691676
import json import pytest from verity_sdk.utils import unpack_forward_message from verity_sdk.utils.Context import Context from verity_sdk.protocols.Protocol import Protocol from ..test_utils import get_test_config, cleanup @pytest.mark.asyncio async def test_get_message(): message = {'hello': 'world'} conte...
StarcoderdataPython
390807
import os from datetime import datetime, timedelta from django.test import TestCase from django.test.client import Client from django.contrib.auth.models import User from django.conf import settings from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.db import c...
StarcoderdataPython
1749688
<filename>tests/components/fronius/test_sensor.py """Tests for the Fronius sensor platform.""" from homeassistant.components.fronius.coordinator import ( FroniusInverterUpdateCoordinator, FroniusMeterUpdateCoordinator, FroniusPowerFlowUpdateCoordinator, ) from homeassistant.components.sensor import DOMAIN a...
StarcoderdataPython
92870
from odoo import _, api, fields, models class Quotations(models.Model): _inherit = "sale.order" note_on_customer = fields.Text("Note on Customer", help="Add Notes on Customers!")
StarcoderdataPython
8118091
<gh_stars>0 #!/usr/bin/env python # ---------------------------------------------------------------------- # Copyright (C) 2014 Numenta # # 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
124887
<filename>explorecourses/classes.py """ This module contains classes representing various academic elements for use in storing and manipulating information from Explore Courses. Includes: - School - Department - Course - Section - Schedule - Instructor - LearningObjective - Attribute ...
StarcoderdataPython
1952533
""" Test batch gradient computation of conv2d layer. The example is taken from Chellapilla: High Performance Convolutional Neural Networks for Document Processing (2007). """ from random import choice, randint import pytest from torch import Tensor, allclose, randn from torch.nn import Conv2d import backpack...
StarcoderdataPython
6505396
<reponame>1byte2bytes/cpython """cmtest - List all components in the system""" import Cm import Res import sys def getstr255(r): """Get string from str255 resource""" if not r.data: return '' len = ord(r.data[0]) return r.data[1:1+len] def getinfo(c): """Return (type, subtype, creator, fl1, fl2, name, descripti...
StarcoderdataPython
337100
<gh_stars>1-10 #!/usr/bin/env python3 # Copyright (c) <NAME> # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from argparse import ArgumentParser import re import sys def main(args): f = '{}.{}'.format(args.corpus, args.l1) e = '{}....
StarcoderdataPython
11239622
import json import mtprof import numpy as np import circuits as cir import ngspice import optimizers as opt def test_folded_corners_sim(): process = ["SS", "FF", "SNFP", "FNSP"] voltage_tempt = ["VDD_MAX_TEMP_MAX", "VDD_MAX_TEMP_MIN", "VDD_MIN_TEMP_MAX", "VDD_MIN_TEMP_MIN"] corner_set = set(["TT"] + [...
StarcoderdataPython
12838917
<reponame>vluk/baymaxBot<gh_stars>0 import discord from discord.ext import commands import random import asyncio cards = ["villager", "werewolf", "minion", "mason", "seer", "robber", "troublemaker", "drunk", "insomniac", "tanner", "hunter"] aesthetics = { "werewolf" : { "color" : 0x25d0ff, "thumbn...
StarcoderdataPython
11226556
from simpleai.search import ( SearchProblem, breadth_first, depth_first, uniform_cost, greedy, astar ) from simpleai.search.viewers import WebViewer, BaseViewer, ConsoleViewer from itertools import combinations GRID = [(r,c) for r in range(7) for c in range(6)] ROADS = [] RACKS = [(0,0),(1,0),(...
StarcoderdataPython
11300199
import serial import numpy as np from time import sleep import sys import json class EIS(): adc_np_type_map = {1:np.int16,2:np.uint16,3:np.uint16} def __init__(self, COM, BAUD = 115200, timeout = .1): self.serial = serial.Serial(COM, BAUD, timeout = .1) def get_and_print_responses(self, ...
StarcoderdataPython
1756484
<reponame>pauliyobo/mapJSON import json import os class MapObj: def __init__(self, minx=0, maxx=0, miny=0, maxy=0, minz=0, maxz=0, type=None, value=None): self.minx = minx self.maxx = maxx self.miny = miny self.maxy = maxy self.minz = minz self.maxz = maxz se...
StarcoderdataPython
6666900
# Author: <NAME> # email: <EMAIL> from PIL import Image import numpy as np import init_paths from image_processing import hwc2chw from xinshuo_visualization import visualize_image def test_hwc2chw(): print('test same channel image, should be the same') image_path = '../lena.jpg' img = np.array(Image.open(image_pat...
StarcoderdataPython
6476017
<filename>building_clean_tweets.py import pandas as pd from clean_text import get_clean import os import json path = 'Data/Tweets/' users = os.listdir(path) cnt = 1 x = pd.DataFrame(columns=['users', 'locations', 'tweets']) x.to_csv('Data/twitter_data.csv', index=False) for user in users: print(cnt, " => ", use...
StarcoderdataPython
6493728
<gh_stars>0 from setuptools import setup, find_packages from pip.req import parse_requirements import sys, os def run_setup(): here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'Readme.md')).read() version = '0.1' install_reqs = parse_requirements(os.path.join(here, 'requirem...
StarcoderdataPython
3523329
# -*- coding: utf-8 -*- from ._common import * class YinYueTai(Extractor): name = '音悦台 (YinYueTai)' def prepare(self): info = MediaInfo(self.name) info.extra.referer = 'https://www.yinyuetai.com/' if not self.vid: self.vid = match1(self.url,'\Wid=(\d+)') data = g...
StarcoderdataPython
8179859
import os from tqdm import tqdm import pandas as pd import numpy as np if __name__ == "__main__": df = pd.read_csv('./IMDB Dataset.csv').values train_df = df[:int(len(df) * 0.9)] val_df = df[int(len(df) * 0.9):] with open('imdb-train.txt', 'w') as f: for i in tqdm(range(len(train_df))): ...
StarcoderdataPython
1746251
from pydc import DDC def main(): ddc = DDC("example_ddc_hmm.pl", 500) prob_s0 = ddc.query( "current(weather(brussels))~=sunny") ddc.step(observations="observation(activity(tintin))~=clean") prob_s1 = ddc.query("(current(temperature(brussels))~=X, X>20)") # prob_s1 = ddc.query("(current(we...
StarcoderdataPython
3482100
<gh_stars>1-10 """ For organizing the post-data. It's basically a django project with some modifications. So you can uses it to save your texts and then use the gateway to post it on different social networks. """
StarcoderdataPython
12843783
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Update : 2020-09-05 09:46:01 # @Author : <NAME> (<EMAIL>) """Sequence taggers.""" from old_fashioned_nlp.tagging.token import CharTfidfTagger __all__ = ['CharTfidfTagger']
StarcoderdataPython
4956697
#!/usr/bin/python # coding=utf-8 import sys, time #Allows for controlling system functions (interrupt) and sleep times. import os import RPi.GPIO as GPIO #Tells python to use GPIO libraries from lifxlan import LifxLAN, Light #Make sure 'pip install lifxlan' was run to enable lifx controls from signal import pause #Not...
StarcoderdataPython
3486361
import asyncio import sys import pytest from HABApp.rule import Rule from ..rule_runner import SimpleRuleRunner class ProcRule(Rule): def __init__(self): super().__init__() self.ret = None def set_ret(self, value): self.ret = value @pytest.fixture(scope="function") def rule(): ...
StarcoderdataPython
3341301
<reponame>thermokarst-forks/library from django.apps import AppConfig class PluginsConfig(AppConfig): name = 'library.plugins' def ready(self): # register the decorated signals from . import signals # noqa: F401
StarcoderdataPython
6632865
<reponame>ryoma-jp/009_Benchmark<filename>benchmark_tensorflow.py #! -*- coding: utf-8 -*- """ [tensorflow] python benchmark_tensorflow.py --help python benchmark_tensorflow.py --param_csv benchmark.csv """ #--------------------------------- # モジュールのインポート #--------------------------------- import os im...
StarcoderdataPython
5098646
<filename>dag_bakery/callbacks/slack_callback.py from datetime import datetime from typing import Callable, Optional, List from airflow.hooks.base_hook import BaseHook from airflow.models import TaskInstance from airflow.operators.slack_operator import SlackAPIPostOperator from dag_bakery.callbacks.context_callback i...
StarcoderdataPython
6686942
class ListSecrets(): pass
StarcoderdataPython
3386440
# -*- coding: utf-8 -*- # # # oeis/generators/__init__.py # # # MIT License # # Copyright (c) 2019 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including with...
StarcoderdataPython
5188999
<reponame>cdunn6754/cdunnSite from django.db import models from django.utils import timezone from django.urls.base import reverse # Create your models here. class ContentTopic(models.Model): name = models.CharField(max_length = 100) description = models.CharField(max_length = 500) def __str__(self): ...
StarcoderdataPython
9681612
# These classes represent the query expressions from section 2.6 of the paper # Dichotomy of Probabilistic Inference for Unions of Conjunctive Queries # by <NAME> 2012 from collections import defaultdict import itertools import nltk from symbolic_slimshot import algorithm class Graph(object): def __init__(self, ...
StarcoderdataPython
4980082
<reponame>Muflhi01/zorya<filename>gcp/gae.py<gh_stars>100-1000 """Interactions with compute engine.""" import logging import backoff from googleapiclient import discovery from googleapiclient.errors import HttpError from util import utils CREDENTIALS = None class Gae(object): """App Engine actions.""" def ...
StarcoderdataPython
1670084
# -*- coding: utf-8 -*- u""" Test of cymel.utils.operation """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import unittest import maya.cmds as cmds from cymel.utils.operation import ( docmd, undoChunk, undoTransaction, nonUndoable, P...
StarcoderdataPython
1607595
"""isort:skip_file""" from docs_snippets.concepts.partitions_schedules_sensors.partitioned_job import ( do_stuff_partitioned, ) # start def test_do_stuff_partitioned(): assert do_stuff_partitioned.execute_in_process(partition_key="2020-01-01").success # end
StarcoderdataPython
6557513
#!/usr/bin/env python3 # 必要なライブラリをインポート import rospy from std_msgs.msg import Float64 import pyaudio import audioop import numpy as np import math class OtoNode(): def __init__(self): # パブリッシャーを定義 self.sound_pub = rospy.Publisher("/sound", Float64, queue_size=1) # データ保存用の変数 self....
StarcoderdataPython
8053346
# !/usr/bin/env python # -*- coding: utf-8 -*- """Dataverse data-types data model.""" from __future__ import absolute_import from pyDataverse.utils import dict_to_json from pyDataverse.utils import read_file_json from pyDataverse.utils import write_file_json """ Data-structure to work with data and metadata of Datave...
StarcoderdataPython
11365409
C = raw_input() C = C.upper() vowels = ['A','E','I','O','U'] if C in vowels: print("Vowel") else: print("Consonant")
StarcoderdataPython
6490016
from random import random # ---------------------- Observable -------------------------- class IObservable: def __init__(self): self.__observers = [] def attach(self, observer): self.__observers.append(observer) def detach(self, observer): self.__observers = [obs for obs in self...
StarcoderdataPython
5198256
<reponame>yakky/microservice-talk<filename>book_search/models/response.py from typing import List from pydantic import BaseModel class Author(BaseModel): name: str class Tag(BaseModel): title: str slug: str class Book(BaseModel): book_id: int title: str isbn13: str authors: List[Autho...
StarcoderdataPython
8129558
<reponame>fga-gpp-mds/2018.1-Cris-Down<filename>drdown/forum/views/view_post.py from ..models.model_post import Post from ..models.model_category import Category from .view_base import BaseViewTemplate from django.views.generic import ListView from django.views.generic import CreateView from django.views.generic import...
StarcoderdataPython
5078157
import os import pathlib from dotenv import load_dotenv load_dotenv() # env vars PREFIX = os.getenv("PREFIX") or "!" TOKEN = os.getenv("TOKEN") # paths EXTENSIONS = pathlib.Path("bot/exts/")
StarcoderdataPython
6669328
<reponame>LihaoR/tensorflow-rl<gh_stars>100-1000 # -*- encoding: utf-8 -*- import time import cPickle import numpy as np import utils.logger import tensorflow as tf from skimage.transform import resize from collections import deque from utils import checkpoint_utils from actor_learner import ONE_LIFE_GAMES from utils....
StarcoderdataPython
3276679
import re from django.contrib.postgres.aggregates import StringAgg from django.forms import CheckboxSelectMultiple from django.urls import reverse_lazy from additional_codes import models from common.filters import ActiveStateMixin from common.filters import LazyMultipleChoiceFilter from common.filters import StartYe...
StarcoderdataPython
237083
<gh_stars>1-10 import random class RandomList(list): def get_random_element(self): """ Returns and removes a random element from the list """ element_to_remove = random.choice(self) self.remove(element_to_remove) return element_to_remove ll = Random...
StarcoderdataPython
6607767
#!/usr/bin/env python3 import sys from testrunner import run def testfunc(child): child.sendline("ifconfig") child.expect(r"Iface\s+(\d+)\s+HWaddr:") if __name__ == "__main__": sys.exit(run(testfunc, timeout=1, echo=False))
StarcoderdataPython
8106648
<reponame>ashimgiyanani/ProjectTemplate_python<filename>src/s_MetMast_Gill_plots.py # -*- coding: utf-8 -*- """ Created on Wed Sep 16 15:11:00 2020 @author: papalk """ import sys import datetime as dt import matplotlib.pyplot as plt import matplotlib.pylab as pylab from matplotlib.dates import DateFormatter from mat...
StarcoderdataPython
6536988
<filename>misc/explore.py import json import os import subprocess import pathlib import numpy as np import pandas as pd import matplotlib.pyplot as plt import itertools simulator_path = "/home/jm1417/Simulator/cmake-build-release/bin/simulator" config_path = "/home/jm1417/Simulator/examples/multiplex/config.json" prog...
StarcoderdataPython
5065592
<gh_stars>0 import unittest from pygraph.prim import min_span_tree import pygraph class TestPrimMST(unittest.TestCase): def test_fixed(self): g = pygraph.Graph() # --- vertices g.AddVertex('a') g.AddVertex('b') g.AddVertex('c') g.AddVertex('d') ...
StarcoderdataPython
178275
"""Definitions for the base Cranelift language."""
StarcoderdataPython
6479257
"""Module used to build consistent UI for Colorium's tools using maya.cmds.""" import maya.cmds as cmds import colorium.data_binding as data_binding class CUI(object): """Base class for a Colorium UI.""" @property def name(self): """The name of the UI.""" return self._name @name.se...
StarcoderdataPython
1726135
#!/usr/bin/env python import boto3 import datetime import dateutil.parser as dp import sys import argparse ec2 = boto3.resource('ec2') def image_deregister(imageid): try: image = ec2.Image(imageid) image_date = image.creation_date except: print "ImageId not found, or you do not have ...
StarcoderdataPython
283537
<gh_stars>1-10 #!/usr/bin/env python3 import warnings warnings.filterwarnings("ignore", category=FutureWarning) warnings.filterwarnings("ignore", category=UserWarning) from http.server import BaseHTTPRequestHandler, HTTPServer import socketserver import sys import dill sys.path.append('../') from SimulationEnviromen...
StarcoderdataPython