id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1668575 | <reponame>suesuhyoonjin/kkp
from rest_framework import generics, serializers
from rest_framework.response import Response
from .models import Summary
class SummaryListSerializer(serializers.ModelSerializer):
class Meta:
model = Summary
fields = ('thumbnail', 'id', 'author', 'section_name', 'cate... | StarcoderdataPython |
1789765 | <reponame>sigurdsa/angelika-api
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('motivation_text', '0002_auto_20141015_1552'),
]
operations = [
migrations.AlterField(
... | StarcoderdataPython |
1618892 | import sys
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class AppWindow(Gtk.ApplicationWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
label = Gtk.Label.new("Hello World")
self.add(label)
class Application(Gtk.Application):
... | StarcoderdataPython |
1692187 | a = 257
b = 11
quoziente = a / b
resto = a % b
prodotto = b * quoziente
print "a = %d b = %d" % (a, b)
print "a / b= %d con resto %d" % (quoziente, resto)
print "b * quoziente = ", prodotto
print "prodotto + resto = ", prodotto + resto
| StarcoderdataPython |
1792561 | ################################## 2222222222222222222 #####################################
#!/usr/bin/python3
import os
import json
import logging
import requests
logger = logging.Logger('catch_all')
def query_az(query):
json_cis=os.popen(query).read()
return json.loads(json_cis)
def check21... | StarcoderdataPython |
1775056 | <reponame>Muck-Man/muck.gg-api
import datetime
from server.rest.endpoint import Endpoint
from server.rest.invalidusage import InvalidUsage
from server.rest.response import Response
from server.utils import ContextTypes, PerspectiveAttributes
class RestEndpoint(Endpoint):
def __init__(self, server):
super().__init... | StarcoderdataPython |
3394362 | from datetime import timedelta
from django.db.models import signals
from django.utils import timezone
import factory
import pytest
from app.common.enums import AdminGroup, GroupType, MembershipType
from app.content.factories import EventFactory
from app.forms.enums import EventFormType
from app.forms.tests.form_fact... | StarcoderdataPython |
1691535 | import pandas as pd
import torch
from torch.utils.data import Dataset
from tqdm import tqdm
from evaluation.tasks.auto_task import AutoTask
class CrowSPairsDataset(Dataset):
def __init__(self):
super().__init__()
# TODO: maybe implement using HuggingFace Datasets
# https://huggingface.co... | StarcoderdataPython |
3316034 | #!/usr/bin/python
##
# Description: Implements 2d bimodal gaussian
##
import numpy as np
from scipy.stats import multivariate_normal
import matplotlib.pyplot as plt
class BimodeGauss_2D(object):
def __init__(self, mu_g1=[0, 0], mu_g2=[2, 2], sigma_g1=[0.25, 0.25], sigma_g2=[0.25, 0.25],
rho_g1=0.... | StarcoderdataPython |
82991 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ============================================================================ #
from matplotlib.ticker import ScalarFormatter
import numpy as np
import matplotlib.pyplot as plt
# ============================================================================ #
# prepare figu... | StarcoderdataPython |
20775 | <reponame>druids/django-fperms-iscore<filename>fperms_iscore/main.py<gh_stars>1-10
from is_core.main import DjangoUiRestCore
from fperms_iscore.mixins import PermCoreMixin
class PermDjangoUiRestCore(PermCoreMixin, DjangoUiRestCore):
abstract = True
| StarcoderdataPython |
1608242 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from .. import ... | StarcoderdataPython |
4813193 | # Binary Searh Tree node
class BSTNode:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def min(self):
root = self
while root and root.left:
root = root.left
return root
def insert(self, key):
... | StarcoderdataPython |
3364596 | from __future__ import absolute_import, division, print_function
import tensorflow as tf
import numpy as np
from datetime import datetime
start = datetime.now()
# Parameters.
learning_rate = 0.01
training_steps = 1000
display_step = 100
# Training Data.
X = np.array([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.1... | StarcoderdataPython |
1731317 | SMALL_NUMBER = 1e-7 | StarcoderdataPython |
50326 | <reponame>arijitsdrush/python<filename>concept/generator-function.py
#!/usr/bin/python3
bridgera = ['Arijit','Soumya','Gunjan','Arptia','Bishwa','Rintu','Satya','Lelin']
# Generator Function iterarates through all items of array
def gen_func(data):
for i in range(len(data)):
yield data[i]
da... | StarcoderdataPython |
1697734 | <reponame>jmacgrillen/perspective
#! /usr/bin/env python -*- coding: utf-8 -*-
"""
Name:
main_window.py
Desscription:
The main window for image_tools. This uses Tkinter to
make the GUI.
Version:
1 - Initial release
Author:
J.MacGrillen <<EMAIL>>
Copyright:
... | StarcoderdataPython |
3243917 | <reponame>xuychen/Leetcode<filename>401-500/431-440/437-pathSum3/pathSum3-naive.py
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum, path=[]):... | StarcoderdataPython |
4840080 | <filename>get_started.py
# -*- coding=utf-8 -*-
import mxnet as mx
import numpy as np
import cv2
class RTSbtl(object):
pass
| StarcoderdataPython |
173420 | <filename>sql_athame/escape.py
import math
import uuid
from typing import Any, Sequence
def escape(value: Any) -> str:
if isinstance(value, str):
return f"E{repr(value)}"
elif isinstance(value, float) or isinstance(value, int):
if math.isnan(value):
raise ValueError("Can't escape N... | StarcoderdataPython |
3257458 | import numpy as np
from PIL import Image
import os
from sys import exit, argv
import csv
import torch
import torchgeometry as tgm
from torch.utils.data import Dataset
from lib.utils import preprocess_image, grid_positions, upscale_positions
import cv2
from tqdm import tqdm
np.random.seed(0)
class PhotoTourism(Datase... | StarcoderdataPython |
1663389 | import pytest
import torch
import numpy as np
import pickle
from perf_gan.data.preprocess import Identity, PitchTransform, LoudnessTransform
from perf_gan.data.contours_dataset import ContoursDataset
def read_from_pickle(path):
with open(path, 'rb') as file:
try:
while True:
y... | StarcoderdataPython |
4816711 | <gh_stars>0
"""
* GTDynamics Copyright 2020, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* See LICENSE for the license information
*
* @file test_jumping_robot.py
* @brief Unit test for jumping robot.
* @author <NAME>
"""
import os,sys,inspect
currentdir = os.path.di... | StarcoderdataPython |
3225302 | <filename>application/config.py<gh_stars>0
#!/usr/bin/env python3
################################
# config.py #
# environment vars/backend #
# Modified by: #
# <NAME>(Nov 10,2019)#
################################
import os
from flask import Flask
basedir = os.path... | StarcoderdataPython |
1778953 | from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from batchmanager import BatchManager
from joblib import Parallel, delayed
import scipy
import numpy as np
def n_labeled_data(x_set, y_set, sample_size, dataset_names):
me... | StarcoderdataPython |
3355243 | from houdini import IWaddle
class CardJitsuWaterLogic(IWaddle):
room_id = 995
def __init__(self, waddle):
super().__init__(waddle)
class WaterSenseiLogic(CardJitsuWaterLogic):
def __init__(self, waddle):
super().__init__(waddle)
| StarcoderdataPython |
549 | import os
from tempfile import TemporaryDirectory
from quickbase_client.utils.pywriting_utils import BasicPyFileWriter
from quickbase_client.utils.pywriting_utils import PyPackageWriter
class TestBasicFileWriter:
def test_outputs_lines(self):
w = BasicPyFileWriter()
w.add_line('import abc')
... | StarcoderdataPython |
1790704 | """Test for Connect view utilities"""
from django.test import TestCase
from open_connect.connect_core.utils.views import JSONResponseMixin
class JSONResponseMixinTest(TestCase):
"""Test the JSONResponse Mixin"""
def test_render_to_response(self):
"""Test the render_to_response method on the JSON Mixi... | StarcoderdataPython |
146980 | """
helper of plyer.battery
"""
__all__ = [
'battery_status'
]
import ctypes
from package_making_practice.platforms.windows.libs import win_api_defs
def battery_status():
"""
implementation of windows API
:return:
"""
status = win_api_defs.SYSTEM_POWER_STATUS()
if not win_api_defs.GetSys... | StarcoderdataPython |
3361281 | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01_discovery.ipynb (unless otherwise specified).
__all__ = ['parse_dataflows', 'all_available', 'search_dataset', 'DataSet']
# Cell
from .base import ISTAT
from .utils import make_tree, strip_ns
import pandas as pd
from fastcore.test import *
# Cell
def parse_dataflows... | StarcoderdataPython |
1751801 | <filename>problems_0_99/problem_3/missing_posint.py
testcase1 = [3, 4, -1, 1]
testcase2 = [1, 2, 0]
testcase3 = [3, 5, 6]
expected1 = 2
expected2 = 3
expected3 = 1
def find_missing_pos_int(arr):
lowest_pos_int = 1
for i in arr:
if (int_is_pos(i)):
if (i < lowest_pos_int+1):
... | StarcoderdataPython |
3228151 | <reponame>hmaarrfk/vispy<filename>vispy/visuals/transforms/interactive.py
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from __future__ import division
import numpy as np
from .linear import STTransform
c... | StarcoderdataPython |
3397371 | begin_unit
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# http://www.apache.org/licenses/L... | StarcoderdataPython |
1616543 | <reponame>alexandrwang/hackmit<filename>server.py
from flask import Flask, request, redirect
import twilio.twiml
import subprocess
import json
import sklearn
import random
import datetime
from sklearn.feature_extraction import DictVectorizer
from sklearn import svm
import re
import nltk
import datetime
import traceback... | StarcoderdataPython |
1628562 | <filename>elsie/render/render.py
import os
from ..render.backends.svg.utils import svg_begin, svg_end
from ..utils.sxml import Xml
from .inkscape import export_by_inkscape
class RenderUnit:
"""
A single presentation page that can render itself using a backend.
"""
def __init__(self, slide, step):
... | StarcoderdataPython |
1782849 | from dataknead import Knead
# Read data from file
Knead("input/entity.json")
# Pass data directly
Knead([1,2,3])
# Parse data from string
Knead("[1,2,3]", parse_as="csv")
# Read data from file without a file extension, give the file format
Knead("input/entity", read_as="json") | StarcoderdataPython |
3314442 | from jivago.lang.annotations import Inject
from jivago.wsgi.annotations import Resource
from jivago.wsgi.invocation.parameters import OptionalQueryParam
from jivago.wsgi.methods import POST
from jivago.wsgi.request.request import Request
from jivago.wsgi.request.response import Response
from pdfinvert.wsgi.application... | StarcoderdataPython |
1656762 | <reponame>jaraco/pmxbot.webhooks<gh_stars>0
import json
import textwrap
from unittest import mock
import cherrypy
from cherrypy.test import helper
from pmxbot.webhooks import Server
class ServerTest(helper.CPWebCase):
def setUp(self):
Server.queue.clear()
def tearDown(self):
Server.queue.cl... | StarcoderdataPython |
1612250 | <filename>test.py
#!/usr/bin/env python3
import os
import time
import sys
import json
import subprocess
from enum import unique
from multiprocessing.pool import Pool
from pathlib import Path
from datetime import datetime
from collections import defaultdict
import requests
sys.path.extend(["./python-client"])
from swag... | StarcoderdataPython |
1690023 | <gh_stars>0
__version__ = '1.0.0'
__author__ = '<NAME>'
__email__ = '<EMAIL>'
from flask_login import current_user, login_required
from .datastore import UserDatastore
from .security_manager import SecurityManager
from .decorators import role_required, roles_required, roles_optional
| StarcoderdataPython |
4806155 | #!/usr/bin/env python
# stdlib imports
import shutil
import os.path
import datetime
# local imports
from .sender import Sender
class CopySender(Sender):
'''
Class for sending and deleting files and directories via system copy
and delete.
CopySender creates a remote directory if one does not already... | StarcoderdataPython |
1625363 | <gh_stars>1-10
import requests
class CurrencyConverter():
def __init__(self, url):
self.data = requests.get(url).json()
self.currencies = self.data['rates']
def convert(self, from_currency, to_currency, amount):
initial_amount = amount
if from_currency != 'USD':
am... | StarcoderdataPython |
3254622 | <filename>subway_spider/__init__.py
"""
@author: <NAME>
@license: MIT license
@contact: <EMAIL>
@file: __init__.py.py
@time: 2021/3/3 10:52 上午
@desc:
"""
import requests
| StarcoderdataPython |
59418 | # -*- coding: utf-8 -*-
__all__ = ['MySqlConnectionResolver', 'MySqlConnection']
from .MySqlConnection import MySqlConnection
from .MySqlConnectionResolver import MySqlConnectionResolver
| StarcoderdataPython |
1672943 | <reponame>Stonehaven-Campaigns/uk-politics-module
"""Functions for importing data."""
import os
import csv
from typing import Dict, Tuple
import pandas as pd
from . import exceptions
def data_path(filename: str) -> str:
"""Get full path to a file in the data folder.
Args:
filename (str)... | StarcoderdataPython |
1660680 | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-22 19:10
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import ticker
def to_scores(text):
return [float(x) for x in text.split()]
giis = to_scores('80.2 80.2 80 80 77.5')
merge = to_scores('80 80.1 80 79.7 78.4')
levi = to_scores('80 8... | StarcoderdataPython |
1682437 | <filename>gestao/contrato/views/remove_despesa_contrato.py
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404, redirect
from gestao.contrato.models.financeiro.ContratoDespesas import ContratoDespesas
def remove_despesa_contrato( request, id_despesa_contrato):
despesa_contrato = get_o... | StarcoderdataPython |
4816593 | from soundEnvelope import SoundEnvelope, Envelope
import time
def test1():
print "test1()"
for i in range(0,2):
e3=Envelope(2,1,-1,0,4,4,0,20,-1,0,-1,126,110)
se.play([[24,200,e3]])
time.sleep(1)
e3=Envelope(4,48,-48,0,1,1,0,127,0,0,-127,127,8)
se.play([[0,25,e3],[2,25... | StarcoderdataPython |
1629759 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | StarcoderdataPython |
24763 | """
Tests for the reference loader for Buyback Authorizations.
"""
from functools import partial
from unittest import TestCase
import blaze as bz
from blaze.compute.core import swap_resources_into_scope
from contextlib2 import ExitStack
import pandas as pd
from six import iteritems
from zipline.pipeline.common import... | StarcoderdataPython |
111427 | <reponame>boris-42/notify
# Copyright 2016: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... | StarcoderdataPython |
1655411 | # -*- coding: utf-8 -*-
"""
Class for handling tenhou logs
@author: ApplySci
"""
#%% imports
# standard libraries
from collections import OrderedDict
from itertools import chain
import json
import lzma
import pickle
from types import SimpleNamespace
import urllib
from lxml import etree
import portalocker
imp... | StarcoderdataPython |
19144 | #!/usr/bin/env python
u"""
radial_basis.py
Written by <NAME> (01/2022)
Interpolates data using radial basis functions
CALLING SEQUENCE:
ZI = radial_basis(xs, ys, zs, XI, YI, polynomial=0,
smooth=smooth, epsilon=epsilon, method='inverse')
INPUTS:
xs: scaled input X data
ys: scaled input Y data
... | StarcoderdataPython |
1797285 | from django.urls import path
from . import views
app_name = 'todo'
urlpatterns = [
path('create/', views.create_group, name='create_group'),
path('update/', views.update_group, name='update_group'),
path('delete/', views.delete_group, name='delete_group'),
path('<int:group_id>/', views.todolist, name=... | StarcoderdataPython |
3262383 | <gh_stars>1-10
def bubble_swap(swapstring):
for desc in range(len(swapstring) -1, 0, -1):
for x in range(desc):
if swapstring[x] > swapstring[x+1]:
(swapstring[x], swapstring[x+1]) = (swapstring[x+1], swapstring[x])
return swapstring
swapstring = bubble_swap([8,4,2,9,5,6,7,6... | StarcoderdataPython |
1761582 | from typing import List, Union
import pandas
from pandas.core.series import Series
from ..model.node_classification_model import NCModel
from ..pipeline.classification_training_pipeline import ClassificationTrainingPipeline
from ..query_runner.query_runner import QueryRunner
class NCTrainingPipeline(ClassificationT... | StarcoderdataPython |
1609256 | <reponame>acc-cosc-1336/cosc-1336-fall-2017-alfonsosalinas2
class Course:
def __init__(self, course_id, title, credit_hour, professor):
self.course_id = course_id
self.title = title
self.credit_hour = credit_hour
self.professor = professor
| StarcoderdataPython |
3359322 | # -*- coding: utf-8 -*-
import click
import logging
from dotenv import find_dotenv, load_dotenv
import os
import sqlite3
from sqlite3 import Error
import pandas as pd
TABLE_NAME = "LONDON"
CSV_COL_NAMES = ["Month", "Latitude", "Longitude", "Location", "Crime type"]
DB_COL_NAMES = ["MONTH", "LATITUDE", "LONGITUDE",... | StarcoderdataPython |
7893 | class Solution:
# dictionary keys are tuples, storing results
# structure of the tuple:
# (level, prev_sum, val_to_include)
# value is number of successful tuples
def fourSumCount(self, A, B, C, D, prev_sum=0, level=0, sums={}):
"""
:type A: List[int]
:type B: List[int]
... | StarcoderdataPython |
4832916 | import ast
import astunparse
import black
def ast_name(name):
return ast.Name(id=name)
def ast_module(*body):
return ast.Module(body=ast_body(body))
def ast_body(body):
return [item for item in body if item]
def ast_import(module, name=None, alias=None):
if name:
if isinstance(name, dict... | StarcoderdataPython |
1749926 | <reponame>wilsonify/euler
#
#
import heapq
from euler_python.utils import eulerlib
# Finding all the relatives of 2 can be seen as a single-source shortest path problem,
# which we solve here using Dijkstra's algorithm. The key insight is that at each node (prime number),
# we consider the connection path from 2 to ... | StarcoderdataPython |
3274656 | #Modelo de regresion logistica
import pandas as pd
import re
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
import pickle
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn import metrics
from uni... | StarcoderdataPython |
1677704 | # DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml.
from flask import Blueprint
from . import handlers
api_api = Blueprint('api_api', __name__)
@api_api.route('/api/nodes', methods=['GET'])
def ListCapacity():
"""
List all the nodes capacity
It is handler for GET /api/nodes
... | StarcoderdataPython |
3247891 | """
Messages API.
url: https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api
"""
import json
from mailgun_sdk.base import ApiDomainResource
class Messages(ApiDomainResource):
"""
Mailing list resource.
"""
api_endpoint = "messages"
require_tls = False
"""
data exam... | StarcoderdataPython |
3237080 | # -*- coding: utf-8 -*-
# vim: set ai sm sw=4 sts=4 ts=8 syntax=python
# vim: set filetype=python fileencoding=utf-8:
import hashlib
import os
class DirFileHash(object):
def __init__(self, path):
if not os.path.isdir(path):
raise ValueError("Path is not a directory: '%'" % path)
else:... | StarcoderdataPython |
3318638 | <reponame>markbasham/boolsi<filename>tests/simulate_tests.py
import ZODB
from boolsi.constants import NodeStateRange
from boolsi.testing_tools import build_predecessor_nodes_lists_and_truth_tables, \
count_simulation_problems, configure_encode_and_simulate, generate_test_description, \
UPDATE_RULES_A, UPDATE_R... | StarcoderdataPython |
3321857 | # test
# Created by JKChang
# 27/01/2020, 15:58
# Tag:
# Description:
from numpy import *
import operator
from os import listdir
import matplotlib.pyplot as plt
# simulating a pandas df['type'] column
types = ['apple', 'orange', 'apple', 'pear', 'apple', 'orange', 'apple', 'pear']
x_coords = [10, 10, 5, 4, 3, 20, ... | StarcoderdataPython |
1782156 | <filename>test/tests/dict_setting_old_dict.py
# Funny case: if we get the attrwrapper of an object, then change it to be dict-backed,
# the original attrwrapper should remain valid but no longer connected to that object.
class C(object):
pass
c1 = C()
aw = c1.__dict__
c1.a = 1
print aw.items()
c1.__dict__ = d = {... | StarcoderdataPython |
3239306 | <reponame>kelp404/Victory
from base_form import *
from wtforms import TextField, validators
class ProfileForm(BaseForm):
name = TextField('Name',
validators=[validators.length(min=1, max=50)],
filters=[lambda x: x.strip() if isinstance(x, basestring) else None])
| StarcoderdataPython |
1720 | import requests
import aiohttp
from constants import API_KEY
class User(object):
def __init__(self, author_info):
# "author": {
# "about": "",
# "avatar": {
# "cache": "//a.disquscdn.com/1519942534/images/noavatar92.png",
# ... | StarcoderdataPython |
1611386 | from aces import Aces
#the origin BP structure is optimized and we use it directly
class sub(Aces):
def submit(self):
opt=dict(
units="metal",
species="Bi4I4_computed",
method="greenkubo",
nodes=1,
procs=1,
queue="q1.4",
runTime=10000000
,runner="shengbte"
)
app=dict(th=True... | StarcoderdataPython |
18875 | from src.main.common.model import endpoint
class TableEndpoint(endpoint.Endpoint):
@classmethod
def do_get(cls, *args, **kwargs):
from src.main.admin_api.utils.descriptor_utils import DescriptorUtils
db_system_name = kwargs.get("db_system_name")
tb_system_name = kwargs.get(... | StarcoderdataPython |
133239 | <reponame>Serkan-devel/m.css<filename>pelican-plugins/m/dot.py
#
# This file is part of m.css.
#
# Copyright © 2017, 2018, 2019 <NAME> <<EMAIL>>
#
# 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... | StarcoderdataPython |
142694 | <reponame>chickenPopcorn/food-truck-inc<filename>src/server/data_access/user_data_access.py
import bcrypt
from forms import LoginForm, ChangePasswordForm, UpdateProfileForm, DeleteForm, VendorRegisterForm, CustomerRegisterForm
class UserDataAccess:
def __init__(self, users):
self.users = users
... | StarcoderdataPython |
1707356 | from flask import Flask
from sys import platform
app = Flask(__name__) # the main flask object
from PhotoZPE import views # the site views, defined in views.py
app.config['SPECTRA_FOLDER'] = app.root_path+'/static/spectra/'
app.config['SECRET_KEY'] = 'random!modnar'
| StarcoderdataPython |
3309194 | <gh_stars>0
# Generated by Django 3.2.11 on 2022-01-13 10:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalogue', '0023_auto_20210824_1414'),
]
operations = [
migrations.AddField(
model_name='option',
name... | StarcoderdataPython |
4809276 | <reponame>brunnergino/JamBot
shifted = True
shift_folder = ''
if shifted:
shift_folder = 'shifted/'
# If you only want to process a subfolder like '/A' or '/A/A' for tests
subfolder = '/'
source_folder = 'data/original' + subfolder
tempo_folder1 = 'data/' + 'tempo' + subfolder
histo_folder1 = 'data/' + 'hist... | StarcoderdataPython |
3330554 | from absl import app
from absl import flags
from bark_ml.experiment.experiment_runner import ExperimentRunner
FLAGS = flags.FLAGS
flags.DEFINE_enum("mode",
"visualize",
["train", "visualize", "evaluate", "print", "save"],
"Mode the configuration should be executed... | StarcoderdataPython |
166226 | """cascade delete for period stars
Revision ID: dbf1daf55faf
Revises: <KEY>
Create Date: 2016-10-08 10:14:03.852963
"""
revision = '<KEY>'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
from alembic import op
def upgrade():
op.drop_constraint('report_all_daily_ibfk_1', 'report_all_daily', type... | StarcoderdataPython |
111084 | {1: 'one', 2: 'two'}
{a: 2, b:4}
| StarcoderdataPython |
52495 | <gh_stars>1-10
from .approx_max_iou_assigner import ApproxMaxIoUAssigner
from .assign_result import AssignResult
from .base_assigner import BaseAssigner
from .max_iou_assigner import MaxIoUAssigner
from .point_assigner import PointAssigner
from .max_iou_assigner_coeff import MaxIoUAssigner_coeff
from .max_iou_ud_assign... | StarcoderdataPython |
21850 | <filename>src/baskerville/models/model_interface.py
# Copyright (c) 2020, eQualit.ie inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import inspect
import logging
class ModelInterface(object):
def __i... | StarcoderdataPython |
3295993 | <reponame>wusimo/NILM<gh_stars>1-10
import numpy as np
import scipy as sp
import scipy.misc
import pandas as pd
from os import path
import datetime
def rel_change(y):
"""
return relative change comparing to the closer neighbouring points
"""
return np.min([np.abs(y[1] - y[0]), np.abs(y[1] - y[2])]) / f... | StarcoderdataPython |
1696816 | <filename>app/main.py
import os
import boto3
import configparser
import argparse
import sys
from typing import Any, Tuple
from app.dynamodb import csv_import, csv_export, truncate
__version__ = "1.3.4"
config_file = "config.ini"
def main() -> None:
"""Main routine
"""
(message, code) = execute()
pri... | StarcoderdataPython |
1647261 | # -*- coding: utf-8 -*-
"""
heroku.core
~~~~~~~~~~~
This module provides the base entrypoint for heroku.py.
"""
from .api import Heroku
def from_key(api_key, **kwargs):
"""Returns an authenticated Heroku instance, via API Key."""
h = Heroku(**kwargs)
# Login.
h.authenticate(api_key)
return h
... | StarcoderdataPython |
4834869 | <gh_stars>1-10
import cv2, functools, glob, keras, random, maskutils, math, os
from keras.utils.np_utils import to_categorical
from keras.preprocessing import image
import slidingwindow as sw
import numpy as np
# From <https://github.com/keras-team/keras-preprocessing/blob/1.0.2/keras_preprocessing/image.py#L341>
# Du... | StarcoderdataPython |
1710171 | # @lc app=leetcode id=65 lang=python3
#
# [65] Valid Number
#
# https://leetcode.com/problems/valid-number/description/
#
# algorithms
# Hard (16.04%)
# Likes: 906
# Dislikes: 5589
# Total Accepted: 200.3K
# Total Submissions: 1.2M
# Testcase Example: '"0"'
#
# A valid number can be split up into these component... | StarcoderdataPython |
163028 | <gh_stars>0
#!/usr/bin/python
"""
__version__ = "$Revision: 1.14 $"
__date__ = "$Date: 2004/08/12 19:19:01 $"
"""
from PythonCard import dialog, model
import wx
class SimpleBrowser(model.Background):
def on_initialize(self, event):
filename = self.application.applicationDirectory + '/index.html'
... | StarcoderdataPython |
1780088 | <filename>toolsconf.py
'''
Configuration parameters for SimSem.
Author: <NAME> <<NAME> se>
Version: 2010-02-09
'''
# TODO: This really belongs under tools/config.py
# Which should be a package
from os.path import dirname, join
from sys import path
### SimString variables
# Path to the SimString Python Swi... | StarcoderdataPython |
3235907 | from .config import PixivAPITestCase, tape
from pixiv import AppCursor
class AppCursorTests(PixivAPITestCase):
@tape.use_cassette('testcursoritems.json')
def testcursoritems(self):
items = list(AppCursor(self.api.search_illust, word='original').items(5))
self.assertEqual(len(items), 5)
@... | StarcoderdataPython |
4811814 | from functools import wraps
def get_list(function):
"""
列表页面 获取 搜索
:param function: self.model
:return:
"""
@wraps(function)
def wrapped(self):
# user = self.request.user
# groups = [x['name'] for x in self.request.user.groups.values()]
# request_type = self.reque... | StarcoderdataPython |
3250051 | <filename>Calibration.py
import numpy as np
import cv2
import math
import Preprocess as pp
import Main
import os
import imutils
import DetectChars
import DetectPlates
import PossiblePlate
def nothing(x):
pass
def calibration (image):
WindowName1 = "Calibrating Position of image"
WindowName2 = "Color Thres... | StarcoderdataPython |
3372729 | <gh_stars>0
#!/usr/bin/env python3
""" Compiles the ipsys source code.
Usage:
{this_script} [options]
Options:
-h --help Prints this docstring.
-l --launch Executes the bin if compiled, with what follows as args.
-d --debug Standard debuging build, defines DEBUG, launches with -d.
--us... | StarcoderdataPython |
91599 | <filename>tools/build/get_header_directory.py
#!/usr/bin/env python3
import pathlib
import sys
import os
def main():
argv = sys.argv
if len(argv) != 3:
raise RuntimeError(
f"Usage: {argv[0]} <header install directory> <absolute path of current header directory>"
)
anchor = 'sou... | StarcoderdataPython |
3337367 | <reponame>Gustavo-Martins/learning<gh_stars>0
# Factorial calculator
n = int(input('Digite um número para calcular seu fatorial: '))
counter = n
f = 1 # Prevents multiplication by zero
print('Calculando {}! = '.format(n), end='')
while counter > 0:
print('{}'.format(counter), end='')
print(' x ' if counter > 1 else... | StarcoderdataPython |
1675522 | from pymongo import ReturnDocument
from past.builtins import basestring
from collections import OrderedDict
from plynx.db.node import Node
from plynx.constants import NodeRunningStatus, Collections, NodeStatus
from plynx.utils.common import to_object_id, parse_search_string
from plynx.utils.db_connector import get_db_c... | StarcoderdataPython |
1634581 | import datetime
from django.test import TestCase
from freezegun import freeze_time
from .views import AboutChasView, AboutEvanView, HomePageView
class TestAboutChasViewGetContextData(TestCase):
def test_context_contains_age(self):
view = AboutChasView()
context = view.get_context_data()
... | StarcoderdataPython |
167529 | """Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada."""
n = int(input('Digite um número inteiro para ver sua tabuada: '))
#print(' {} \n {} \n {} \n {} \n {} \n {} \n {} \n {} \n {} \n {}'.format(n * 1, n * 2, n * 3, n * 4, n * 5, n * 6, n * 7, n * 8, n * 9, n * 10))
print('-'*12)
pr... | StarcoderdataPython |
43783 | #!/usr/bin/env python
""" MultiQC submodule to parse output from Roary """
import logging
import statistics
from multiqc.modules.base_module import BaseMultiqcModule
from multiqc import config
from multiqc.plots import bargraph, heatmap, linegraph
log = logging.getLogger('multiqc')
class MultiqcModule(BaseMultiqcMo... | StarcoderdataPython |
1779102 | #!/usr/bin/env python3
import sys, os
from threading import Thread
import gym
import threading
import numpy as np
import tensorflow as tf
from a3c import A3C_Worker, A3C_Net
def main():
#training vars
worker_num = 4
global_train_steps = 1000 #50000 = 1 million steps
test = True
env_name = '... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.