id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1738098 | import numpy as np
__all__ = ['cal_pdf']
def cal_pdf(data, bins=60, save_to=None):
"""Calculate probability density function.
Parameters
----------
data : array-like
Input data. The histogram is computed over the flattened array.
bins : int or sequence of scalars, optional
If `bi... | StarcoderdataPython |
1728062 | from python_framework import Validator, ValidatorMethod, GlobalException, HttpStatus
from config import WhatsAppWebConfig
@Validator()
class WhatsAppWebValidator :
@ValidatorMethod()
def isAvailable(self) :
self.validator.authentication.isAuthenticated()
if self.service.whatsAppWeb.isNotAvail... | StarcoderdataPython |
78421 | <gh_stars>0
# 2. Write Python code to find the cost of the minimum-energy seam in a list of lists.
energies = [[24, 22, 30, 15, 18, 19],
[12, 23, 15, 23, 10, 15],
[11, 13, 22, 13, 21, 14],
[13, 15, 1... | StarcoderdataPython |
20306 | '''
Contains the extended FastAPI router, for simplified CRUD from a model
'''
from typing import Any, List, Optional, Sequence, Set, Type, Union
import fastapi
from fastapi import Depends, params
from pydantic import BaseModel, create_model
from odim import Odim, OkResponse, SearchResponse
from odim.dependencies imp... | StarcoderdataPython |
184646 | # IxCode - app for code spelunking :: block diagram
# AST from C code.
# Do this unsafe import to inject this code
from src.ast import *
class Include(Node):
"""
An include declaration, holds the included filename (assumed to be
correct).
"""
def __init__(self, fname):
self._fname = fname
... | StarcoderdataPython |
1739721 | # -*- coding: utf-8 -*-
"""Parser for utmpx files."""
from dfdatetime import posix_time as dfdatetime_posix_time
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import errors
from plaso.lib import definitions
from plaso.lib import specification
from plaso.parsers import dtf... | StarcoderdataPython |
3257709 | <gh_stars>0
class BaseQueryResult:
def __init__(self):
self.bases = {}
self.results = 0
| StarcoderdataPython |
3394064 | #!/usr/bin/python
#-*-coding:utf-8-*-
class Component(object):
'''This is the component in the game.'''
_name = 'Component'
def __init__(self,position,num,region_size):
self.position = position
self.num = num
self._region_size = region_size
return super(Component, self).__in... | StarcoderdataPython |
3213891 | #!/usr/bin/env python3
# Write a program that prints out the position, frame, and letter of the DNA
# Try coding this with a single loop
# Try coding this with nested loops
dna = 'ATGGCCTTT'
frame = [0,1,2]
n = 3
for i in range(0, len(dna)):
j = frame*n
print(i, j[i], dna[i])
i+=1
"""
dna = 'ATGGCCTTT'
frame= (... | StarcoderdataPython |
1621992 | from django.urls import path, include
app_name = "basebone_common"
urlpatterns = [
# 通用管理端
path(
"basebone/<str:app>__<str:model>/",
include(
("lightning_plus.api_basebone.restful.manage.urls", app_name),
namespace="manage.common.basebone",
),
),
# 通用客户端... | StarcoderdataPython |
64085 | <reponame>nikosNalmpantis/examples
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import os
import sys
import click
import random
from jina import Flow, Document, DocumentArray
from jina.logging.predefined import default_logger as logger
MAX_DOCS = int(os.environ... | StarcoderdataPython |
30779 | <filename>sort_file.py
import pandas as pd
from fuzzywuzzy import process
import Levenshtein as lev
import numpy as np
import openpyxl
# -----------------------code for first csv file-------------------------------------------
buyer_df = pd.read_csv("./results/CD_21_05/final2.csv", usecols=['PRODUCTS','UNITS', 'BATCHE... | StarcoderdataPython |
1676978 | <reponame>hamk-automation/matrixprofile-ts<gh_stars>0
from matrixprofile.utils import *
import numpy as np
import pytest
class TestClass(object):
def test_zNormalize_zero_error(self):
with pytest.raises(ValueError):
zNormalize(np.array([2.0,2.0,2.0]))
def test_zNormalize(self):
ou... | StarcoderdataPython |
4816107 | <reponame>vinihcrosa/osint_python
import sqlite3
from pathlib import Path
from modules import logs
database_path = Path('./database/database.sql').resolve()
create_spiderfoot_table_query = """
CREATE TABLE IF NOT EXISTS results(
guid INTEGER PRIMARY KEY,
name TEXT NOT NULL,
target TEXT NOT NU... | StarcoderdataPython |
1725109 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import sys
import operator
from multiprocessing import Process, Lock
import argparse
import nltk
import common
import fileio
import nltk_analyze
import make_wordcloud
import tokenizer
import dialogues
import sentiments
import translations
# TODO-list
# TODO:
# Topics. Maybe LD... | StarcoderdataPython |
1888 | #!/usr/bin/env python
#
# Python Serial Port Extension for Win32, Linux, BSD, Jython
# module for serial IO for POSIX compatible systems, like Linux
# see __init__.py
#
# (C) 2001-2010 <NAME> <<EMAIL>>
# this is distributed under a free software license, see license.txt
#
# parts based on code from <NAME> <<EMAIL>>:
#... | StarcoderdataPython |
168132 | <filename>utilidades/Potencia_Eolica.py<gh_stars>0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from math import log, exp
import random
def potencia_eolica():
# Distribuição de Weibull
U = random.random()
Vmin = 0.14
Vmax = 14.27
intervalo_confianca = 99.0
Finf = ((100.0 - interv... | StarcoderdataPython |
82084 | <filename>lang/py/pylib/code/exceptions/exceptions_SystemExit.py
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 <NAME> All rights reserved.
#
"""
"""
__version__ = "$Id$"
#end_pymotw_header
import sys
try:
sys.exit(1)
except SystemExit, err:
print 'Tried to exit with code', err.code
| StarcoderdataPython |
3274925 | """ Combines catalogs of Analia and Maddox to get IDs. """
import os
import numpy as np
import astropy.units as u
from astropy.table import Table
from astropy.coordinates import SkyCoord
import matplotlib.pyplot as plt
import context
if __name__ == "__main__":
fname = os.path.join(context.tables_dir,
"... | StarcoderdataPython |
3360584 | #!/usr/bin/env python3
# @brief: Get a 3D point cloud from a given range image projection
# @author <NAME> [<EMAIL>]
import torch
import torch.nn as nn
import numpy as np
class projection:
"""Projection class for getting a 3D point cloud from range images"""
def __init__(self, cfg):
"""Init
... | StarcoderdataPython |
1678391 | import time
import torch
from PIL import Image
from comparisons import *
from depth_img_from_mat import *
from model import *
# from resize_test import *
from torch.autograd import Variable
from torchvision.utils import save_image
from utils import *
from weights import *
class DepthPrediction:
def __init__(self, we... | StarcoderdataPython |
28901 | <reponame>lhuett/insights-core<gh_stars>100-1000
"""
ceph_insights - command ``ceph insights``
=========================================
"""
import json
import re
from .. import CommandParser, parser
from insights.specs import Specs
@parser(Specs.ceph_insights)
class CephInsights(CommandParser):
"""
Parse the... | StarcoderdataPython |
12346 | <reponame>rehmanis/shopyo2
version_info = (4, 0, 1)
__version__ = ".".join([str(v) for v in version_info])
| StarcoderdataPython |
1757231 | # ------------------------------------------------------------------------------
# CodeHawk Java Analyzer
# Author: <NAME>
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
#
# Permission is hereby granted, free of... | StarcoderdataPython |
1751577 | <filename>utils/SpectralUtils.py<gh_stars>1-10
import os
import cv2 as cv
import numpy as np
from scipy.io import savemat
# from PIL import Image
JPG_QUALITY = 80
PNG_COMPRESSION = 9 # Prioritize small file size over speed (lossless compression)
# Bit-depth constants
BIT_16 = 65535
BIT_8 = 255
def imTo8bit(im):
... | StarcoderdataPython |
3243927 | #-*- coding: utf-8 -*-
#
# This file belongs to Gyrid Server.
#
# Copyright (C) 2011-2012 <NAME>
# All rights reserved.
"""
Plugin that handles on-disk logging of received scanner data.
"""
import os
import time
import olof.configuration
import olof.core
import olof.tools.validation
class Logger(object):
"""
... | StarcoderdataPython |
3367718 | <reponame>sonesuke/my-portfolio
# flake8: noqa
from mypo.evacuator.base_evacuator import BaseEvacuator
from mypo.evacuator.calendar_evacuator import CalendarEvacuator
from mypo.evacuator.covariance_evacuator import CovarianceEvacuator
from mypo.evacuator.fixed_evacuator import FixedEvacuator
from mypo.evacuator.moving... | StarcoderdataPython |
4801708 | <gh_stars>10-100
import autograd.numpy as np
from autograd import elementwise_grad as egrad
from scipy import linalg
import matplotlib.pyplot as plt
from functools import partial
from athena.active import ActiveSubspaces
from athena.utils import Normalizer
# custom 2d outputs of interest
from numpy_functions import c... | StarcoderdataPython |
3328057 | import csv
import numpy as np
from pylab import *
from scipy import linalg
from scipy.stats import norm
from sklearn import svm
from sklearn.model_selection import GridSearchCV
import time
import logging
from model import Model
logging.basicConfig(format='%(asctime)s %(name)s %(levelname)-8s %(message)s',
... | StarcoderdataPython |
3356129 | SQLALCHEMY_DATABASE_URI = 'postgresql://USERNAME:PASS@SERVER/DB_NAME'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_POOL_RECYCLE = 60
SQLALCHEMY_POOL_TIMEOUT = 10
SLACK_ACCESS_TOKEN = 'SLACK_ACCESS_TOKEN'
SLACK_BOT_ACCESS_TOKEN = 'SLACK_BOT_ACCESS_TOKEN'
SLACK_VERIFICATION_TOKEN = 'SLACK_VERIFICATION_TOKEN'
LOGS_PA... | StarcoderdataPython |
86008 | <reponame>Ferlern/Arctic-Tundra
import json
import logging
import discord_components
from discord.ext import commands
from discord_components.component import Select, SelectOption
from main import SEBot
from utils.utils import DefaultEmbed
from ..utils import Interaction_inspect
from ..utils.build import update_messa... | StarcoderdataPython |
3393144 | from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import AsyncImage
from kivy.uix.popup import Popup
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.core.window import Window
from DAO.conexao import db
from te... | StarcoderdataPython |
1647810 | class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
stack = [(0, 0)]
res = 0
for i, h in enumerate(heights):
index = i
# update won't improving rectangle
w... | StarcoderdataPython |
1731271 | <filename>const/sub_categories/service/media.py
from typing import Dict
from ..base_category import BaseCategory
# CD錄音帶 cd-and-tape
class CdAndTape(object):
def cd_and_tape() -> Dict[str, Dict[str, str]]:
list = {}
list['name'] = 'CD錄音帶'
list['id'] = 'cd-and-tape'
cd_and_tape = {}
cd... | StarcoderdataPython |
24339 | import os
import json
from github3.pulls import PullFile
from github3.repos.commit import RepoCommit
def load_fixture(filename):
path = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(path, 'fixtures', filename)
fh = open(filename, 'r')
return fh.read()
def create_pull_files(data)... | StarcoderdataPython |
53852 | <gh_stars>1-10
from abc import ABC, abstractmethod
from argparse import Action, Namespace
class Command(ABC):
@abstractmethod
def exec(self, args: Namespace) -> None:
pass
@staticmethod
@abstractmethod
def define_signature(parser: Action):
pass
| StarcoderdataPython |
3307749 | # Copyright (c) 2013, igrekus and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
columns = get_columns()
data = get_data()
return columns, data
def get_columns():
return [
{
"fieldname": ... | StarcoderdataPython |
1670535 | <reponame>dedean16/proba-v-dataset-tools<gh_stars>1-10
#!/usr/bin/env python3
"""Configuration for collect script."""
# Initialise cfg dictionary
cfg = {}
# Define date of interest
cfg['year'] = 2017 # Year of interest
cfg['months'] = [7, 8, 9] # Month of interest
# Define Region of Intere... | StarcoderdataPython |
3289139 | <reponame>ertogrul/ArgMining
class THFSentenceExport:
def __init__(self, uniqueID, label, text, tokens, dependencies, textdepth):
self.uniqueID = uniqueID
self.label = label
self.text = text
self.tokens = tokens
self.dependencies = dependencies
self.textdepth = textde... | StarcoderdataPython |
1727099 | #!/usr/bin/env python
__author__ = "<NAME>"
__credits__ = ["<NAME>"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"
#"LDB Stocked Product Expected for Delivery"
#"Third Party Warehouse Stocked Product Currently Unavailable"
#end at "Subtotal:"
impo... | StarcoderdataPython |
1642742 | <reponame>lcsgrlch/oap
"""
Bits & Pieces
"""
__version__ = "0.0.1"
from oap.bnp.clamp import clamp
from oap.bnp.progress import progress
from oap.bnp.loading import Loading
from oap.bnp.runtime import Runtime
| StarcoderdataPython |
3284537 | import unittest
import sys
import os
sys.path.insert(0, os.path.abspath(
os.path.join(os.path.dirname(__file__), "..")))
import cogito
class CogitoCheck(unittest.TestCase):
def setUp(self):
self.base_path = os.path.dirname(__file__)
self.iam_file = "{}/files/test.iam".format(self.base_path)... | StarcoderdataPython |
6417 | <reponame>fgitmichael/SelfSupevisedSkillDiscovery<gh_stars>0
from __future__ import print_function
import argparse
import torch
import torch.utils.data
import matplotlib.pyplot as plt
from torch import nn, optim
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils imp... | StarcoderdataPython |
65345 | # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from dongguan.items import DongguanItem
import time
class SunSpider(CrawlSpider):
name = 'crawl'
allowed_domains = ['wz.sun0769.com']
start_urls = ['http://wz.sun0769.com/inde... | StarcoderdataPython |
3310522 | import os
from PIL import Image, ImageFont, ImageDraw
import matplotlib.pyplot as plt
import numpy as np
directory = 'input'
def watermark():
image = Image.open(os.path.join(directory, filename))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", 50)
width, height = image.size
... | StarcoderdataPython |
3242257 | <reponame>henjin0/HolePlateMaker
import numpy as np
from stl import mesh
from mpl_toolkits import mplot3d
from matplotlib import pyplot
from HolePlateMaker import mesh_scale as ms
from HolePlateMaker import mesh_scale as ms
from HolePlateMaker import mesh_scale as ms
from HolePlateMaker import mesh_update as mu
from Ho... | StarcoderdataPython |
15657 | """Datatest main program"""
import sys as _sys
from unittest import TestProgram as _TestProgram
from unittest import defaultTestLoader as _defaultTestLoader
try:
from unittest.signals import installHandler
except ImportError:
installHandler = None
from datatest import DataTestRunner
__unittest = True
__datat... | StarcoderdataPython |
3307250 | #!/usr/bin/env python3.6
#
# require: git+https://github.com/nathants/slackbot
# require: requests
# policy: CloudWatchLogsFullAccess
# allow: lambda:InvokeFunction *
# trigger: api
# trigger: cloudwatch rate(15 minutes) # keep lambda warm for fast responses
#
import time
import json
import requests
import slackbot
im... | StarcoderdataPython |
37064 | <gh_stars>1-10
from django.contrib import admin
from apps.wiki.models import Article, Tag, ExternalLink, ArticleFile
admin.site.register(Article)
admin.site.register(Tag)
admin.site.register(ExternalLink)
admin.site.register(ArticleFile)
| StarcoderdataPython |
1792629 | # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def test_codecommit_provider():
# setup
from . import bootstrap
puppet_version = "0.10.0"
all_regions = [
"us-east-1",
"us-east-2",
]
repo_name = "TestRepoName"
... | StarcoderdataPython |
3289485 | <reponame>btrekkie/graphql<filename>src/graphql/document/operation.py<gh_stars>0
class GraphQlOperation(object):
"""Abstract base class for GraphQL operations (queries and mutations).
Public attributes:
list<GraphQlDirective> directives - The directives for the
operation.
basestring name - The... | StarcoderdataPython |
116136 | <filename>mogwai/models/multilayer_attention.py
from argparse import ArgumentParser, Namespace
from typing import Optional
import math
import torch
import torch.nn as nn
from apex.optimizers import FusedLAMB
from .base_model import BaseModel
from ..utils import symmetrize_matrix_
from ..utils.init import init_potts_b... | StarcoderdataPython |
101764 | <filename>src/common/env.py
'''
Created on Feb 20, 2017
@author: sarvi
@copyright: 2017 Cisco Inc. All rights reserved.
'''
# pylint: disable=locally-disabled, too-many-lines
from __future__ import print_function
import base64
import collections
import datetime
import hashlib
import logging.handlers
import os
impo... | StarcoderdataPython |
1701171 | <filename>app/jobs_scraper.py
import urllib
import requests
from bs4 import BeautifulSoup
import selenium
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import pandas as pd
import os
def find_jobs_from(website, job_title, location, desired_characs, filename="results.xls"): ... | StarcoderdataPython |
3364813 | def height(root):
if root:
return 1 + max(height(root.left), height(root.right))
else:
return -1
| StarcoderdataPython |
45508 | <filename>1/7/Project/utils/iloc.py
def iloc(records, rows=':', cols=':') -> list:
"""A Pandas .iloc-like function.
Args:
records (list): A 2-D list.
rows (str or int): The indices of rows. Default is ':'.
cols (str or int): The indices of columns. Default is ':'.
Returns:
... | StarcoderdataPython |
1770598 | # coding: utf-8
import scipy
import json
import re
import allennlp
from allennlp.predictors.predictor import Predictor
from spacy.lang.en import English
import numpy as np
# import tensorflow as tf
import os
import sys
import torch
from hyperpara import *
import dgl
from utils import *
from tqdm import tqdm
nlp ... | StarcoderdataPython |
3340103 | import tensorflow as tf
import os
import time
import logging
from util.config import LOG_DIR
TF_LOG_DIR = os.path.join(LOG_DIR, 'tensorboard')
loggers = {}
class TensorboardLogger:
"""
Logs variables visibly to the tensorboard interface.
"""
_is_in_setup_phase = True
_writer = None
_sess = ... | StarcoderdataPython |
3287293 | <reponame>datha88/kbqa-ar-smcnn
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Mostly from https://github.com/OpenNMT/OpenNMT-py
# Most Code in load/save word2vec format refer to Gensim
import torch
import torch.nn as nn
from utils import load_word2vec_format, aeq
class Embeddings(nn.Module):
def __init__(self,
... | StarcoderdataPython |
3300767 | <gh_stars>10-100
#!/usr/bin/env python3
# Copyright (c) 2019, <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:
#
# * Redistributions of source code must retain the above copyright notic... | StarcoderdataPython |
3218814 | import os.path
import requests
from bs4 import BeautifulSoup
import sys
if sys.version_info[0] != 3:
print('''\t--------------------------------------\n\t\tREQUIRED PYTHON 3.x\n\t\tinstall and try: python3
fb.py\n\t--------------------------------------''')
sys.exit()
PASSWORD_FILE = "<PASSWORD... | StarcoderdataPython |
148675 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import roc_auc_score, roc_curve, classification_report
from xgboost import XGBClassifier
from time import time
idx = pd.IndexSlice
# COMMAND ----------
# MAGIC %md General
# COMMAND ----------
def coun... | StarcoderdataPython |
1719719 | from .init import init
from .new import new
from .mv import mv
from .edit import edit
from .tree import tree
from .history import history
from .cat import cat
from .git import git
from .config import config
from .mkdir import mkdir
from .rm import rm
from .fsck import fsck
__all__ = [
'init', 'new', 'mv', 'edit', ... | StarcoderdataPython |
3247587 | my_friends = ["dzj","wwb","ljx","zz","gyj","zke","yxd"]
zz_friend = my_friends[:]
print(my_friends)
print(zz_friend)
| StarcoderdataPython |
1718152 | """
MIT License
Copyright (c) 2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... | StarcoderdataPython |
1736236 | <gh_stars>1-10
from ._patient import DigitalPatient
from .conformal import cp, base, evaluation, icp
from ._version import __version__
__all__ = [
'DigitalPatient',
'cp', 'base', 'evaluation', 'icp',
'__version__'
]
| StarcoderdataPython |
3214645 | <filename>arcface.py
import math
import timm
import torch
import torch.nn as nn
from torch.nn import functional as F
from config import CFG
import albumentations
from albumentations.pytorch.transforms import ToTensorV2
class ArcFaceModule(nn.Module):
def __init__(self, in_features, out_features, scale, margin, ea... | StarcoderdataPython |
3209076 | # -*- coding:utf-8 -*-
from PIL import ImageFont
from EPUIKit import QuadrantsLayout, VirtualPaper
from EPUIKit.widget import Label
def font():
return ImageFont.load_default()
layout = QuadrantsLayout(border=1)
layout.add(Label('LEFT_BOTTOM', font=font()), QuadrantsLayout.LEFT_TOP)
layout.add(Label('LEFT_BOTTO... | StarcoderdataPython |
1700270 | #!/usr/bin/env python2
import mimetypes
mimetypes.init()
OUTPUT = "output.txt"
fout = open(OUTPUT,"w")
for extension, mimetype in mimetypes.types_map.iteritems():
fout.write("\t".join([extension, "A", "", "", "", "", "", "", "", "", "", "The MIME type for the extension "+extension+" is "+mimetype+".", "http://en.wikip... | StarcoderdataPython |
1733528 | <filename>pggan_cifar10.py
""" TensorMONK's :: Progressing growth of GANs on CIFAR10 """
from __future__ import print_function, division
import os
import sys
import timeit
import argparse
import numpy as np
import core
import torch
from core.NeuralEssentials import DataSets, MakeModel, VisPlots, Save... | StarcoderdataPython |
3290085 | import numpy as np
import seaborn as sns
from keras.utils.vis_utils import plot_model
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def plot_keras_model(model, path):
full_path = path + 'keras-model.png'
plot_model(model, to_file=full_path, show_shapes=True, show_layer_names=Tru... | StarcoderdataPython |
1674797 | # Generated by Django 3.2.2 on 2021-06-08 05:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0008_cart'),
]
operations = [
migrations.CreateModel(
name='Payment',
fields=[
('id', models... | StarcoderdataPython |
1732023 | <reponame>HEATlab/DREAM
import json
from libheat.stntools.stn import STN
NO_AGENT = 0
def mit2stn(fp: str, add_z=False, connect_origin=False, cap=True) -> list:
"""Convert MIT JSON file to a PSTN via the STN class.
Args:
fp: File path for the JSON file.
add_z (boolean, optional): Add an ex... | StarcoderdataPython |
85684 | <reponame>inclusive-design/tock
from django import forms
from django.contrib import admin
from hours.admin import TimecardPrefillDataInline
from .models import EmployeeGrade, UserData
class UserDataForm(forms.ModelForm):
class Meta:
model = UserData
exclude = []
def clean(self):
try:
... | StarcoderdataPython |
1646698 | # general components of every sensor, unique to every sensor:
# - identification credentals
# - location of deployment
class Sensor:
def __init__(self, sensorID, location = "33 48\' 58\" S 18 28\' 22\" E"):
self.__sensorID = sensorID
self.__location = location
# record sensor id
def setSensorID... | StarcoderdataPython |
3360646 | # author: <NAME>
# website: http://www.pyimagesearch.com
# USAGE
# BE SURE TO INSTALL 'imutils' PRIOR TO EXECUTING THIS COMMAND
# python temp_file.py --image ../demo_images/bridge.jpg
# import the necessary packages
from __future__ import print_function
from imutils.io import TempFile
import argparse
import cv2... | StarcoderdataPython |
16924 | #!/usr/bin/env python
# Manipulate sys.path to be able to import converscript from this local git
# repository.
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))
from converscript import RiveScript
import json
bot = RiveScript()
bot.load_file("example.rive")
dep = bot.deparse... | StarcoderdataPython |
1747459 | <filename>__main__.py
import sys
from zacoby.management import execute_command_inline
if __name__ == '__main__':
execute_command_inline(sys.argv)
| StarcoderdataPython |
89963 | """
create user, log in, and get information back
"""
import requests
import json
headers = {'content-type': 'application/json'}
url = 'http://127.0.0.1:5000'
create_user_route='/user/createaccount'
login_user_route='/user/login'
get_user_data_route='/user'
create_user_data = {'username': 'Alice Test',
'emai... | StarcoderdataPython |
1711598 | <reponame>RimorRes/MDRS_Rover<filename>raspberrypi/serialComm.py
# INSTALL PYSERIAL: python -m pip install pyserial
# LIST OF AVAILABLE PORTS: python -m serial.tools.list_ports
import serial
import time
port= serial.Serial('dev/ttyUSB0', 9600, timeout=1000) # modifiable
def lectureBus():
dureeAttente = 1000
rece... | StarcoderdataPython |
4812044 | <reponame>dmitriykel/friends_surprise<gh_stars>1-10
"""add img_url and open_date to gifts
Revision ID: 47f1d728ec56
Revises: <PASSWORD>
Create Date: 2019-06-19 10:20:57.787300
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '47f1d728ec56'
down_revision = '3<PAS... | StarcoderdataPython |
1666319 | <filename>src/code3.8.py
import numpy as np
from numpy.core.fromnumeric import transpose
def batch_kron(A, B):
if np.shape(A)[:-2] != np.shape(B)[:-2]:
print("error")
return None
else:
return(np.reshape(np.einsum("...mn,...ij->...minj", A, B), np.shape(A)[:-2]+(np.shape(A)[-2]*np.shape... | StarcoderdataPython |
4801966 | <reponame>tony92151/pedestrian_generator
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import numpy as np
import cv2
import random
#from google.colab.patches import cv2_imshow
# import some common detectron2 utilities
from detectron2 import model_zoo
... | StarcoderdataPython |
1796419 | # -*- coding: utf-8 -*-
# (c) YashDK [yash-dk@github]
from datetime import datetime,timedelta
def human_readable_bytes(value, digits= 2, delim= "", postfix=""):
"""Return a human-readable file size.
"""
if value is None:
return None
chosen_unit = "B"
for unit in ("KiB", "MiB", "GiB", "TiB"... | StarcoderdataPython |
1621528 | <gh_stars>0
import setuptools
import os
with open("README.md", "r", encoding='utf-8') as f:
long_description = f.read()
dirname = os.path.dirname(__file__)
with open('pysg/version.py', 'r') as f:
exec(f.read())
setuptools.setup(
name="pysg",
version=__version__,
author="<NAME>",
author_email... | StarcoderdataPython |
3324618 | <reponame>ettoremessina/integral-calculus
import scipy.integrate as spi
import numpy as np
print('Double integral computed by SciPy nquad')
print('Example 2-01 nquad')
print('Integral of 2xye^-xy from y=1 to y=5 and from x=y-1 to x=y+1')
integrand = lambda x, y : 2 * x * y * np.exp(-x * y)
bounds_y = lambda : [1., 5... | StarcoderdataPython |
91748 | from django.urls import path
from . import views
urlpatterns = [
path('ground', views.battle_ground, name='Ground Battle'),
path('naval', views.battle_naval, name='Naval Battle'),
]
| StarcoderdataPython |
1762551 | # -*- coding: utf-8 -*-
from wpg.generators import build_gauss_wavefront_xy as construct_gaussian
from felpy.model.wavefront import Wavefront
from wpg.wpg_uti_wf import plot_intensity_map
from .examples.NFS.cylinder_phase_mask import phase, cylinder_thickness
import numpy as np
from felpy.utils.opt_utils import ekev... | StarcoderdataPython |
4835822 | <filename>Tr4PrFnPredLib/tokenizer/tokenizer_config.py
from ..common.constants import MODEL_DEEPGO, MODEL_DEEPRED, MODEL_GOLABELER, MODEL_XBERT, MODEL_PROTBERT
from .DeepGoPlusTokenizer import DeepGoPlusTokenizer
from .ProtBERTTokenizer import ProtBERTTokenizer
TOKENIZER = {
MODEL_DEEPGO: DeepGoPlusTokenizer(),
... | StarcoderdataPython |
40475 | """Testing handling with CoreState."""
from supervisor.const import CoreState
from supervisor.coresys import CoreSys
def test_write_state(run_dir, coresys: CoreSys):
"""Test write corestate to /run/supervisor."""
coresys.core.state = CoreState.RUNNING
assert run_dir.read_text() == CoreState.RUNNING.val... | StarcoderdataPython |
3277974 | from django.test import TestCase
from django.contrib.auth.models import User
from django.db import IntegrityError, DatabaseError
from survey.models.users import UserProfile
class UserProfileTest(TestCase):
def test_fields(self):
user = UserProfile()
fields = [str(item.attname) for item in user._... | StarcoderdataPython |
3385115 | from dippy.core.enums import OverwriteType
from dippy.core.models.model import DippyCoreModel
from dippy.core.snowflake import Snowflake
class OverwriteModel(DippyCoreModel):
id: Snowflake
type: OverwriteType
deny_new: int
deny: int
allow_new: int
allow: int
| StarcoderdataPython |
11088 | #!/bin/python3
import os
def getTotalX(a, b):
c = 0
for i in range(max(a), min(b) + 1):
if all([i % d == 0 for d in a]) and all([d % i == 0 for d in b]):
c += 1
return c
if __name__ == "__main__":
f = open(os.environ["OUTPUT_PATH"], "w")
nm = input().spl... | StarcoderdataPython |
3392703 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask
from flask import abort, jsonify, Response, render_template, request
app = Flask(__name__)
# app.config['JSON_AS_ASCII'] = False
# @app.route('/')
# def hello():
# return 'Hello world!'
@app.route('/')
def home():
return render_template('ind... | StarcoderdataPython |
1789638 | '''
Copyright (c) 2011, <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:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclai... | StarcoderdataPython |
3358214 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 01 14:15:26 2014
@author: TEuser
TO DO:
compile new input time series
calculate Jarvis equations based on daily data
calculate Jarvis coefficient for soil moisture based on hourly data
calculate daily reference open water
calculate daily potential evaporation
donwscale... | StarcoderdataPython |
1746591 | from rest_framework import serializers
class VerifyOTPSerializer(serializers.Serializer):
otp_code = serializers.CharField(max_length=6)
email = serializers.EmailField(max_length=200)
| StarcoderdataPython |
1791302 | <gh_stars>1-10
from src.world_entities.entity import SimulatedEntity
import numpy as np
class Target(SimulatedEntity):
def __init__(self, identifier, coords, maximum_tolerated_idleness, simulator):
SimulatedEntity.__init__(self, identifier, coords, simulator)
self.maximum_tolerated_idleness = ma... | StarcoderdataPython |
3368602 | import errno
import functools
import logging
from os import devnull, mkdir
from os.path import splitext, basename, isdir
import sys
import warnings
import webbrowser
from urllib.parse import urlparse
import click
from server.app.app import Server
from server.app.util.errors import ScanpyFileError
from server.app.util... | StarcoderdataPython |
3335095 | # -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["get_compile_args"]
import sys
def get_compile_args(compiler):
opts = ["-std=c++11", "-O2", "-DNDEBUG"]
if sys.platform == "darwin":
opts += ["-stdlib=libc++", "-mmacosx-version-min=10.7"]
return opts
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.