id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
9765797 | <gh_stars>1-10
"""mp_notice
Revision ID: cf266bf19ef3
Revises: <PASSWORD>
Create Date: 2019-05-04 22:42:02.845137
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'cf266bf19ef3'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():... | StarcoderdataPython |
191726 | # Generated by Django 3.1.8 on 2021-04-14 06:57
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL)... | StarcoderdataPython |
8073188 | <gh_stars>1-10
import bisect
import collections
from datetime import timedelta
Update = collections.namedtuple("Update", ["timestamp", "value"])
class TimeSeries:
def __init__(self):
"""An object that manages TimeSeries that include a timestamp and value.
Attributes:
series (Update)... | StarcoderdataPython |
9702002 | '''
Collection of localised thin multipole maps.
For formulae see e.g. SIXTRACK:
SixTrack Physics Manual
<NAME> and <NAME>
August 18, 2015
or, likewise,
A Symplectic Six-Dimensional Thin-Lens Formalism for Tracking
<NAME>, <NAME>
April 5, 1995
@authors: <NAME>
@date: 23/03/2016
'''
from math import factorial
f... | StarcoderdataPython |
5060059 | <gh_stars>1-10
from util import time_it
@time_it
def linear_search(numbers_list, number_to_find):
for index, element in enumerate(numbers_list):
if element == number_to_find:
return index
return -1
if __name__ == '__main__':
numbers_list = [12, 15, 17, 19, 21, 24, 45, 67]
number_to_... | StarcoderdataPython |
9704362 | import pytest
import sqlite3
import os
@pytest.fixture(scope='module')
def sqlite_connection():
# TODO: setup test instance of db then destory after
dbname = 'data/test_data.db'
# TODO: check if db does not exist before continuing
db = sqlite3.connect(dbname)
sql_create_photos_table = """ CREATE... | StarcoderdataPython |
1603982 | from encargoapi import app
from encargoapi.auth import auth
from encargoapi.config import db
from encargoapi.user.model import User
from flask import (
abort,
g,
jsonify,
request,
url_for,
)
@app.route('/api/v1.0/users', methods = ['GET'])
def user():
return jsonify({'users': 'ok'})
@app.rout... | StarcoderdataPython |
8128434 | <gh_stars>1-10
# coding: utf-8
# ----------------------------------------------------------------------------
# <copyright company="Aspose" file="deconvolution_filter_properties.py">
# Copyright (c) 2018-2020 Aspose Pty Ltd. All rights reserved.
# </copyright>
# <summary>
# Permission is hereby granted, free... | StarcoderdataPython |
1858009 | <reponame>featureoverload/upgrade-marshmallow
from marshmallow import Schema
from marshmallow import fields
def NoneEmptyString(**kwargs): # noqa
return fields.String(**kwargs)
class FooSchema(Schema):
name = NoneEmptyString(title='foo name', description="foo name")
| StarcoderdataPython |
1928729 | <reponame>josephquang97/pymemapi
import sqlite3
from PyMemAPI import __version__
from PyMemAPI import Memrise, SQLite, Course
from PyMemAPI.exception import LoginError, InvalidSeperateElement, AddBulkError, AddLevelError, InputOutOfRange, LanguageError
import unittest
from pytest import MonkeyPatch
# Test version
def... | StarcoderdataPython |
8104775 | # Date Imports
from datetime import date
# AGAGD Models Imports
import agagd_core.models as agagd_models
# AGAGD Django Tables Imports
from agagd_core.tables.beta import (
GamesTable,
PlayersInformationTable,
PlayersOpponentTable,
PlayersTournamentTable,
)
# Django Imports
from django.core.exceptions... | StarcoderdataPython |
3473737 | from typing import List, Optional
from django.shortcuts import reverse
from iamheadless_publisher_site.pydantic_models import BaseItemContentsPydanticModel, BaseItemDataPydanticModel, BaseItemPydanticModel
from .conf import settings
from .urls import urlpatterns
class FlatPageContentPydanticModel(BaseItemContentsP... | StarcoderdataPython |
179327 | <gh_stars>1-10
from . import (control, demo, demographics, epi, interventions, timings,
matrices)
| StarcoderdataPython |
5056501 | """
Some helper functions for workspace stuff
"""
import logging
import re
import biokbase
import biokbase.workspace
from biokbase.workspace import client as WorkspaceClient
g_log = logging.getLogger(__name__)
# regex for parsing out workspace_id and object_id from
# a "ws.{workspace}.{object}" string
ws_regex = re.c... | StarcoderdataPython |
12802768 | import copy
from typing import Optional, Collection, Any, Dict, Tuple
from causalpy.bayesian_graphs.scm import (
SCM,
NoiseGenerator,
Assignment,
IdentityAssignment,
MaxAssignment,
SignSqrtAssignment,
SinAssignment,
)
import networkx as nx
import pandas as pd
import numpy as np
class SumA... | StarcoderdataPython |
1916449 | from unittest import result
from pytesseract import Output
import pytesseract
import cv2
image = cv2.imread("images_0.jpg")
x = 0
y = 0
w = 1080
h = 800
image = image[y: y+h,x: x+w]
rgb = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
results = pytesseract.image_to_data(rgb,output_type=Output.DICT,lang='chi_tra',config='--ps... | StarcoderdataPython |
3495041 |
class CAPostalCode:
__slots__ = ['postal_code', 'city', 'place_names', 'province']
def __init__(
self,
postal_code,
city,
place_names,
province
):
self.postal_code = postal_code
self.city = city
self.place_names = place_... | StarcoderdataPython |
1820263 | <filename>aioupbit/v1/__init__.py
from __future__ import annotations
from .aiohttp_client import *
from .client import *
from .constants import *
from .values import *
RestClient = AioHTTPRestClient
| StarcoderdataPython |
8092003 | <gh_stars>10-100
import hoomd
# Initialize the simulation.
device = hoomd.device.CPU()
sim = hoomd.Simulation(device=device)
sim.create_state_from_gsd(filename='random.gsd')
# Set the operations for a Lennard-Jones particle simulation.
integrator = hoomd.md.Integrator(dt=0.005)
cell = hoomd.md.nlist.Cell()
lj = hoomd... | StarcoderdataPython |
313159 | #! /usr/bin/env python
"""
Run this either with
$ python -m paderbox.utils.strip_solution name_template.ipynb name_solution.ipynb
or directly with
$ paderbox.strip_solution name_template.ipynb name_solution.ipynb
"""
import re
from pathlib import Path
import fire
import nbformat
CODE_MAGIC_WORD = '# REPLACE'
LATEX_M... | StarcoderdataPython |
4920451 | <reponame>kagemeka/atcoder-submissions
import sys
import typing
import numba as nb
import numpy as np
@nb.njit
def enumerate_fx() -> np.ndarray:
a = np.array([1])
for _ in range(12):
b = []
for x in a:
for i in range(10):
b.append(x * i)
a = np.unique(np.array(b))
retu... | StarcoderdataPython |
1928464 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 <NAME> <EMAIL>
#
import logging
log = logging.getLogger('view')
from PyQt4 import QtGui, QtCore, QtOpenGL
from PyQt4.Qt import Qt
from .. import model
LINE_SIZE = 512
PAGE_SIZE = 4096
# LINE_SIZE=512*4
# PAGE_SIZE=4096*16
class MemoryMappingSc... | StarcoderdataPython |
3431912 | <gh_stars>1-10
import os
import requests
import json
import threading
import copy
import common
from habitica import Habitica
from datetime import datetime, timezone, timedelta
import leancloud
from leancloud import LeanCloudError
from lc.api import LC
# 提供不背单词基本操作
class GitHub(object):
"""docstring for GitHub"""
# ... | StarcoderdataPython |
5034126 | from atgql.pyutils.did_you_mean import did_you_mean
def test_does_accept_an_empty_list():
assert did_you_mean([]) == ''
def test_handles_single_suggestion():
assert did_you_mean(['A']) == ' Did you mean "A"?'
def test_handles_two_suggestions():
assert did_you_mean(['A', 'B']) == ' Did you mean "A" or ... | StarcoderdataPython |
4934171 | #!/usr/bin/env python
import torch
class RobotModel(object):
def __init__(self, dofs, nlinks, wksp_dim, state_dim, sphere_radii = [], batch_size=1, num_traj_states=1, use_cuda=False):
self.use_cuda = torch.cuda.is_available() if use_cuda else False
self.device = torch.device('cuda') if self.use_cuda else tor... | StarcoderdataPython |
5190488 | <reponame>marcottelab/NuevoTx<gh_stars>0
#!/usr/bin/env python3
import gzip
import sys
#filename_fa = 'Karsenia_koreana.prot.select.2021_07.fa'
#filename_bp = 'Karsenia_koreana.prot.select.2021_07.MODtree_ens100_2021_05.dmnd_bp_tbl6.gz'
#sp_code = 'KARKO'
filename_fa = sys.argv[1]
filename_bp = sys.argv[2]
sp_code = ... | StarcoderdataPython |
1893925 | from ctypes import sizeof
# https://www.csie.ntu.edu.tw/~b03902082/codebrowser/pbrt/include/asm-generic/ioctl.h.html
# and
# https://stackoverflow.com/questions/20500947/what-is-the-equivalent-of-the-c-ior-function-in-python
_IOC_NRBITS = 8
_IOC_TYPEBITS = 8
_IOC_SIZEBITS = 14
_IOC_DIRBITS = 2
_IOC_NRSHIFT = 0
_IOC_T... | StarcoderdataPython |
4990382 | <reponame>DaerusX/jupyterlab-data-visualization<gh_stars>1-10
# Thisdataframes=Nonethon script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from datavalidator.handlers.statistics_handler import Statis... | StarcoderdataPython |
9722543 | # Copyright 2016, <NAME>, mailto:<EMAIL>
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# ... | StarcoderdataPython |
8057569 | import logging
import time
import requests
import six.moves.urllib.parse as urlparse
from .. import SSS_VERSION
from .. import SSS_FORMAT
from .. import ACTION_PREFIX
from .. import client
from ..common import constants
from ..common import exceptions
from ..common import serializer
from ..common import utils
from ..... | StarcoderdataPython |
4945236 | <gh_stars>1-10
#adata.pubsub
'''
Publisher Subscriber framework
'''
import wx
import traceback
from wx.lib.pubsub import pub
'''Send message alias
'''
publish = pub.sendMessage
def echo(text, color=None, lf=True, marker=None, icon=None): # no optional **kwargs
'''The Adata console print function sends a pubsu... | StarcoderdataPython |
8084979 | import sys
import json
version_list = sys.argv[1:]
if __name__ == '__main__':
version_list.sort(
key=lambda v: [int(u) for u in v.split('.')],
reverse=True
)
version_list = [f'v{version}' for version in version_list]
version_list.insert(0, 'latest')
print(json.dumps(version_list))
| StarcoderdataPython |
4830711 | import os
import cv2
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import argparse
import segmentation_models_v1 as sm
sm.set_framework('tf.keras')
from unet_std import unet # standard unet architecture
from helper_function import plot_deeply_history, plot_history, save_history
from helpe... | StarcoderdataPython |
1674895 | <reponame>fxjung/obsidian_tools
import typer
import logging
import asyncio
from pathlib import Path
from obsidian_tools.watch import main
formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s")
ch = logging.StreamHandler()
ch.setFormatter(formatter)
logging.getLogger("").setLevel(logging.... | StarcoderdataPython |
11335418 | <reponame>Izocel/PythonBookHero
import os
import sys
from typing import *
from mysql.connector.connection import *
from getpass import getpass
import hashlib
from datetime import datetime
# Variables globales
BD_CONNECTION = {}
BD_CONFIG = {}
CURSEUR = {}
BASETABLE = ''
def get_config(key:str = '') -> Any:
globa... | StarcoderdataPython |
11301832 | from random import randint
def get_random_hex_color():
"""Generates and returns a random hex color."""
color = '#' + ''.join(['{:02X}'.format(randint(0, 255)) for _ in range(3)])
return color
| StarcoderdataPython |
1756828 | <gh_stars>1-10
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from camera_calibration import calib, undistort
from threshold import get_combined_gradients, get_combined_hls, combine_grad_hls
from line import Line, get_perspective_transform, get_lane_lines_img, illustrate_... | StarcoderdataPython |
5100986 | import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger('coapUri')
log.setLevel(logging.ERROR)
log.addHandler(NullHandler())
import re
from . import coapUtils as u
from . import coapOption as o
from . import coapException as e
from . impo... | StarcoderdataPython |
11321702 | <reponame>sa-y-an/retro
from django.http.response import HttpResponse
from django.shortcuts import render
from .classifier import nn_predictions
def home(request) :
return render(request, 'home/home.html')
def about(request) :
return render(request, 'home/about.html')
# modalities
def eda(request):
i... | StarcoderdataPython |
3254750 | <reponame>Rogdham/bigxml<filename>src/bigxml/handle_mgr.py
from bigxml.handler_creator import create_handler
from bigxml.utils import last_item_or_none
class HandleMgr:
_handle = None
def iter_from(self, *handlers):
if not self._handle:
raise RuntimeError("No handle to use")
handl... | StarcoderdataPython |
3210926 | <filename>reconstrcut_tldrQ_highlights.py
import json
highlited_file = '/disk1/sajad/datasets/reddit/tldr-9+/highlights-test/'
with open('/disk1/sajad/datasets/reddit/tldr-9+/test.json') as fR:
for l in fR:
ent = json.loads(l.strip())
src = ent['document'].replace('</s><s> ', '')
summary = ... | StarcoderdataPython |
1736738 | # Copyright(C) 2011,2012,2013 by Abe developers.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is d... | StarcoderdataPython |
363604 | """The config show command."""
import sys
from putio_cli.commands.config import Config
class Show(Config):
"""
show command to print configuration file
Usage:
putio-cli config show
"""
def run(self):
try:
cfgfile = open(self.cfgfilename, 'r')
except IOError:
... | StarcoderdataPython |
391178 | """
DESCRIPTORS: local ang global descriptors for a rectangular (part of an) image.
"""
__autor__ = '<NAME>'
| StarcoderdataPython |
1764639 | import time
import numpy as np
import tensorflow as tf
from data import num_labels
def accuracy(predictions, labels):
return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
/ predictions.shape[0])
def train_model_in_batches(model, datasets, steps, dropout_keep_prob, load_model = False... | StarcoderdataPython |
11242793 | <gh_stars>0
#45 What color is square ?
# Asking for number and letter
x = input("Enter the letter : ")
y = int(input("Enter the number : "))
#Assuming a1 as black
if x == "a" or x == "c" or x == "e" or x == "g":
if y % 2 == 0:
z = "White"
else:
z = "Black"
if x == "b" or x == "d" or x ... | StarcoderdataPython |
1712801 | def find_record_dimension(d):
"""Find the record dimension (i.e. time) in a netCDF4 Dataset."""
for dim in d.dimensions:
if d.dimensions[dim].isunlimited():
return dim
return None
| StarcoderdataPython |
81692 | # Input: arr[] = {1, 20, 2, 10}
# Output: 72
def single_rotation(arr,l):
temp=arr[0]
for i in range(l-1):
arr[i]=arr[i+1]
arr[l-1]=temp
def sum_calculate(arr,l):
sum=0
for i in range(l):
sum=sum+arr[i]*(i)
return sum
def max_finder(arr,l):
max=arr[0]
for i in range(l):... | StarcoderdataPython |
11368550 | from .hyper import register_hyper_optlib
def convert_param_to_skopt(param, name):
from skopt.space import Real, Integer, Categorical
if param['type'] == 'BOOL':
return Categorical([False, True], name=name)
if param['type'] == 'INT':
return Integer(low=param['min'], high=param['max'], name... | StarcoderdataPython |
11368864 | from django.db import models
from questao.models import Questao
class Resposta(models.Model):
texto = models.TextField(max_length=255)
questao = models.ForeignKey(Questao,related_name="respostas" ,on_delete=models.CASCADE)
correta = models.BooleanField(default=False)
def __str__(self):
return... | StarcoderdataPython |
6462865 | import pytest
from dsp_be.logic.config import Config
from dsp_be.logic.factory import Factory
from dsp_be.logic.planet import Planet
from dsp_be.logic.stack import Stack
@pytest.fixture
def jupiter():
return Planet(
name="Earth",
resources={"fire_ice": 0.04, "hydrogen": 0.85},
exports=[],... | StarcoderdataPython |
4915839 | import torch.nn as nn
import torch
from detection.ResUnet import CRAFT
import detection.craft_utils as craft_utils
from recognition.model import TRBA
import data_utils
from config import config
from torch.autograd import Variable
class CRAFTS(nn.Module) :
def __init__(self, cfg, std_cfg, str_cfg, device) :
... | StarcoderdataPython |
62479 | <gh_stars>0
def print_num(n):
"""Print a number with proper formatting depending on int/float"""
if float(n).is_integer():
return print(int(n))
else:
return print(n)
| StarcoderdataPython |
1896767 | <reponame>paullewallencom/javascript-978-1-8495-1034-9
urlpatterns = patterns(u'',
(ur'^$', directory.views.homepage),
(ur'^accounts/login/$', u'django.contrib.auth.views.login'),
(ur'^admin/', include(admin.site.urls)),
(ur'^ajax/check_login', directory.views.ajax_check_login),
(ur'^ajax/delete', d... | StarcoderdataPython |
8085733 | <gh_stars>1-10
from tensorflow.keras.layers import Dense, Conv2D, BatchNormalization, LeakyReLU, Add, AveragePooling2D, ReLU, MaxPool2D
from Model.layers import SpectralNormalization
import tensorflow as tf
#via https://github.com/manicman1999/Keras-BiGAN/blob/master/bigan.py
def up_res_block(input, filters, gen_kern... | StarcoderdataPython |
269326 | # -*- coding: utf-8 -*-
# @Author: <NAME>
# @Date: 2016-03-17 17:06:04
# @Last Modified by: <NAME>
# @Last Modified time: 2016-04-07 07:21:56
import os
import json
import numpy as np
import networkx as nx
from .SecondaryStructure import SecondaryStructure as SS
from .Form import Form
from .FormMotif import FormMot... | StarcoderdataPython |
1933358 | <reponame>radiusoss/constructor<filename>constructor/conda_interface.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import json
from os.path import join
import sys
try:
from conda import __version__ as CONDA_INTERFACE_VERSION
conda_interface_type ... | StarcoderdataPython |
82924 | <filename>third_party/OpenFace/model_training/ce-clm_training/cen_training/train_cen.py
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax
from keras.constraints import max_norm, non_neg
from keras.callbacks... | StarcoderdataPython |
3498640 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 27 21:07:59 2018
@author: JSen
"""
import numpy as np
import matplotlib.pyplot as plt
from numpy import loadtxt, load
import os
from scipy import optimize
from scipy.optimize import minimize
from sklearn import linear_model
import scipy.io as spio
... | StarcoderdataPython |
11390747 | <reponame>tefra/xsdata-w3c-tests<gh_stars>1-10
from output.models.nist_data.list_pkg.float_pkg.schema_instance.nistschema_sv_iv_list_float_max_length_5_xsd.nistschema_sv_iv_list_float_max_length_5 import NistschemaSvIvListFloatMaxLength5
__all__ = [
"NistschemaSvIvListFloatMaxLength5",
]
| StarcoderdataPython |
114423 | <reponame>haru-works/Resize_image<filename>resize_images.py
import os
from glob import glob
from PIL import Image
import argparse
import datetime
#現在時間取得用
dt_now = datetime.datetime.now()
#------------------------------------------------------------------------
# 画像リサイズ処理
#--------------------------------------------... | StarcoderdataPython |
1702664 | <reponame>mbaak/Eskapade-Spark
"""Project: Eskapade - A python-based package for data analysis.
Class: SparkHistogrammarFiller
Created: 2017/06/09
Description:
Algorithm to fill histogrammar sparse-bin histograms from a Spark
dataframe. It is possible to do cleaning of these histograms by
rejecting certa... | StarcoderdataPython |
6417557 | #!/usr/bin/env python
#
# Example pipeline to run Fastqc on one or more Fastq files
# but ignoring any with zero reads
import os
import argparse
from bcftbx.FASTQFile import nreads
from auto_process_ngs.pipeliner import PipelineTask
from auto_process_ngs.pipeliner import PipelineFunctionTask
from auto_process_ngs.pipe... | StarcoderdataPython |
188981 | <gh_stars>0
import os
import transform as trans
import numpy as np
from glob import glob
import argparse
def transformObj(inputFile, R, T, outSuffix='-aligned'):
parDir, filename = os.path.split(inputFile)
name, ext = os.path.splitext(filename)
outFile = os.path.join(parDir, name + outSuffix + ext... | StarcoderdataPython |
1896456 | <gh_stars>0
from dotenv import load_dotenv, find_dotenv
from libs.google_auth_utils import get_credentials
load_dotenv(find_dotenv())
def main():
# Set the access scopes (Docs: https://developers.google.com/identity/protocols/oauth2/scopes)
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
... | StarcoderdataPython |
9771137 | <filename>dijkstra.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def dijkstra(weights):
num_nodes = len(weights)
# 重みの合計の暫定値と確定値
sum_tmp = [math.inf for _ in range(num_nodes)]
sum_fixed = [0 for _ in range(num_nodes)]
# 仮のルートと確定のルート
route_tmp = [[] for _ in range(num_nodes)]
... | StarcoderdataPython |
6615242 | <filename>websubsub/views.py
import json
import logging
from collections import defaultdict
from datetime import timedelta
from django.conf import settings
from django.http import HttpResponse
from django.utils.decorators import classonlymethod
from django.utils.timezone import now
from rest_framework.views import API... | StarcoderdataPython |
9628712 | import math
r1 = 2.49/2
r2 = 2.15/2
r3 = 0.32/2
r4 = 0.263/2
r5 = 0.077/2
r6 = 0.691/2
chang1 = 0.926821
kuan1 = 0.540230
chang2 = 0.507058
kuan2 = 0.224489
chang3 = 0.829926
kuan3 = 0.106065
chang4 = 0.587294
kuan4 = 0.602596
chang_daa = 0.476477
kuan_daa = 1.015017
chang_da = 1.015017
kuan_da = 0.182756
height1 = 0.4... | StarcoderdataPython |
1627099 | <gh_stars>0
from flask import render_template, request, redirect, url_for, abort, flash, session, g, send_from_directory
from flask.globals import session as session_obj
from flask_login import login_user, login_required, logout_user, current_user
from sqlalchemy.orm import exc
from sqlalchemy import and_
import json, ... | StarcoderdataPython |
6602002 | import os
from office365.sharepoint.client_context import ClientContext
from settings import settings
cert_settings = {
'client_id': '51d03106-4726-442c-86db-70b32fa7547f',
'thumbprint': "6B36FBFC86FB1C019EB6496494B9195E6D179DDB",
'certificate_path': '{0}/selfsigncert.pem'.format(os.path.dirname(__file__))... | StarcoderdataPython |
6460002 | # coding=utf-8
from flask import Flask, g, render_template, current_app, request, redirect, abort, url_for
from jinja2.utils import Markup
from werkzeug.routing import BaseConverter, ValidationError
from werkzeug.datastructures import MultiDict
from contextlib import contextmanager
from collections import namedtuple, O... | StarcoderdataPython |
12836395 | <filename>dmlab2d/random_agent.py
# Copyright 2019 The DMLab2D Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | StarcoderdataPython |
6543189 | #!/usr/bin/env python
# encoding: utf-8
# <NAME>, 2016
'''Uses Fypp as Fortran preprocessor (.F90 -> .f90).'''
import re
import os.path
from waflib import Configure, Logs, Task, TaskGen, Tools
try:
import fypp
except ImportError:
fypp = None
Tools.ccroot.USELIB_VARS['fypp'] = set([ 'DEFINES', 'INCLUDES' ])
FYPP_... | StarcoderdataPython |
8196845 | import os
from dotenv import load_dotenv
import psycopg2
load_dotenv()
DB_NAME = os.getenv("DB_NAME", default="OH_NO!")
DB_USER = os.getenv("DB_USER", default="OH_NO!")
DB_PW = os.getenv("DB_PW", default="<PASSWORD>!")
DB_HOST = os.getenv("DB_HOST", default="OH_NO!")
CSV_FILEPATH = "titanic.csv"
conn = psycopg2.co... | StarcoderdataPython |
4984283 | #!/usr/bin/env python
#-*- coding: utf-8 -*
#
# Copyright 2012 msx.com
# by <EMAIL>
# 2012-4-14
#
# Sputnik DBObject Cache
#
# ToDoList:
#
import redis
class VectorCache:
def __init__(self):
pass
class ViewCache:
def __init__(self):
pass
class ViewMetadataTable:
def __init__(self):
... | StarcoderdataPython |
6598190 | from __future__ import annotations
import itertools
import threading
import traceback
from datetime import datetime, timedelta
from time import sleep
import keyboard as kb
# functions to be run, you can change these!
from waiting import wait
import foe_desktops
from foe_bot_army import processArmy
from foe_bot_gold ... | StarcoderdataPython |
11274463 | <filename>app/migration.py
from datetime import datetime
import requests
import pandas as pd
import pandas_gbq
from config import config_eu, config_us
from google.cloud import bigquery
from typing import List
def operation_refine_city_data_appendbq(project_id:str, destination_tableid:str, newly_arrived: pd.DataFrame... | StarcoderdataPython |
1847642 | return "the end"
x = 2 + 2
| StarcoderdataPython |
3538161 | <reponame>starkyller/dissertacao<filename>backend/hmobiweb/apps/monitoring_solutions/api/views.py
from rest_framework import generics
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from ..models import (
MonitoringCategory,
SolutionObjective... | StarcoderdataPython |
4879699 | import fileinput
from collections import defaultdict
from utils import parse_nums, memoize
@memoize
def resolve(r):
if type(rules[r]) == str:
return [rules[r]]
matches = []
for subrule in rules[r]:
submatches = ['']
for n in subrule:
new = []
for m in resolv... | StarcoderdataPython |
8155308 | <reponame>yvanlvA/Possible_Web_Server_Frame<filename>WebServer/possible/Context/Cookie.py
#_*_ coding:utf-8 _*_
import http.cookies
class Cookie(object):
def __init__(self):
self.sCookie = http.cookies.SimpleCookie()
self.reqCookieDic = {}
def CookieLoad(self, rewdata):
if rewdata == "... | StarcoderdataPython |
9618698 | # -*- coding: utf-8 -*-
# Copyright (C) 2020 - KMEE
import os
import sys
from os import path
from xmldiff import main
from lxml import etree as etree_
sys.path.append(path.join(path.dirname(__file__), '..', 'nfselib'))
from nfselib.ginfes.v3_01 import (
servico_enviar_lote_rps_envio,
servico_consultar_nfse_rps... | StarcoderdataPython |
5169063 | # -*-coding:utf-8-*-
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
def int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def image2example... | StarcoderdataPython |
1663609 | <reponame>AABur/python-project-lvl2
# -*- coding:utf-8 -*-
import pytest
from gendiff.loader import GendiffFileError, collect_data
@pytest.mark.parametrize(
'file_path',
[
('tests/fixtures/wrong_ext.ttt'),
('tests/fixtures/wrong_json.json'),
('tests/fixtures/wrong_yaml.yaml'),
... | StarcoderdataPython |
6017 | # @Time : 2022/1/26 23:07
# @Author : zhaoyu
# @Site :
# @File : __init__.py.py
# @Software: PyCharm
# @Note : xx | StarcoderdataPython |
1616350 | <filename>classify.py<gh_stars>0
import spacy
import pandas as pd
import numpy as np
import math
# import random
from collections import Counter, defaultdict
import sys
import re
import os
import dataManagment as dm
nlp = spacy.load('en')
import spacy.parts_of_speech as pos_t
VERB = 'VERB'
nsubj = 'nsubj'
dobj = 'do... | StarcoderdataPython |
11200448 | <gh_stars>0
import logging
from common.asserts import assert_overflowing
from common.components.hero import assert_h1_spacing, assert_subtext_spacing
from common.components.para_blocks import *
from . import mobile_browser as browser
logger = logging.getLogger(__name__)
def test_hero_section(browser):
section_c... | StarcoderdataPython |
5181209 | import pickle as pkl
import numpy as np
import numpy.linalg as linalg
# import scipy.linalg as linalg
import scipy.stats as stats
import pandas as pd
import copy as cp
def getPeaksAndBWs(strf,dt=5,df=1/6, discard_thresh=0.05):
original_strf= strf
strf=np.maximum(original_strf,0)
l2_norm_pos = np.sum(str... | StarcoderdataPython |
3587458 | import requests
import json
def test_healthcheck():
# Setup
url = 'http://localhost:5000'
headers = {'Content-Type': 'application/json' }
# Action
resp = requests.get(url, headers=headers)
# Check
assert resp.status_code == 200
resp_body = resp.json()
assert resp_body['cod... | StarcoderdataPython |
3406530 | <filename>resnet/data_loader.py
import numpy as np
from os.path import join
class Loader:
X_train = None
y_train = None
X_valid = None
y_valid = None
X_test = None
y_test = None
X_seq_train = None
y_seq_train = None
X_seq_valid = None
y_seq_valid = None
X_seq... | StarcoderdataPython |
6626342 | <gh_stars>10-100
#!/usr/bin/env python
import unittest
import sys
import shutil
import os
import io
import re
import gzip
import numpy
if "DEBUG" in sys.argv:
sys.path.insert(0, "..")
sys.path.insert(0, "../../")
sys.path.insert(0, ".")
sys.argv.remove("DEBUG")
import metax.Formats as Formats
from M0... | StarcoderdataPython |
1780446 | <gh_stars>1-10
import sys
def printc(*s, color="grey", hl=None, bg=None, file=sys.stderr):
"""
Prints some text with some color, using Terminal escape sequences
>>> printc("Hello world", color="blue")
\033[1;34mHello world\033[1;m
>>> printc("Hello world", color="blue", hl=True)
\033[1;44mHel... | StarcoderdataPython |
308801 | import sqlite3
import subprocess as sp
"""
database code
"""
def create_table():
conn = sqlite3.connect('testdb.sqlite')
cursor = conn.cursor()
query = '''
CREATE TABLE IF NOT EXISTS student(
id INTEGER PRIMARY KEY,
roll INTEGER,
name TEXT,
phone TEXT
)
'''
cursor.exec... | StarcoderdataPython |
1741468 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
182297 | import numpy as np
from mlxtend.feature_selection import SequentialFeatureSelector as SFS
from sklearn.model_selection import KFold
from sklearn.feature_selection import SelectPercentile, mutual_info_classif
import sys
from pathlib import Path
sys.path[0] = str(Path(sys.path[0]).parent)
from metrics import metrics, m... | StarcoderdataPython |
1602325 | <filename>bazel/rules/library_rule.bzl
# Copyright 2018-present Open Networking Foundation
# SPDX-License-Identifier: Apache-2.0
def stratum_cc_library(name, deps = None, srcs = None, data = None,
hdrs = None, copts = None, defines = None,
include_prefix = None, includes =... | StarcoderdataPython |
8105984 | #!/usr/bin/python3
class mppt(object):
def __init__(self):
self.__panelVoltage = 0
self.__panelCurrent = 0
self.__batteryVoltage = 48
self.__batteryInputCurrent = 0
@property
def panelVoltage(self):
return self.__panelVoltage
@property
def panelCurrent(self... | StarcoderdataPython |
3520629 | import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import math
import numpy as np
from Simple_FISs import split_vector_given
def get_plot_points(fuzzy_system):
def to_x_y_vectors(centers, widths):
x_values = []
y_values = []
for center, width in zip(centers, widths):
... | StarcoderdataPython |
3220315 | from enum import IntFlag
from typing import cast, List, Tuple, Iterable, TextIO
from itertools import takewhile
from qcodes import VisaInstrument, InstrumentChannel, ChannelList
from qcodes.utils.validators import Enum, Numbers
from qcodes.instrument.group_parameter import GroupParameter, Group
def read_curve_file(c... | StarcoderdataPython |
9641261 | <filename>EmergencyServices/migrations/0004_unsafeareas.py
# Generated by Django 3.1.1 on 2020-12-07 19:10
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_d... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.