id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3207573 | <reponame>gatsby-sahani/svGPFA<filename>scripts/demoUtils.py
import sys
import os
import torch
sys.path.append(os.path.expanduser("../src"))
import myMath.utils
def getLegQuadPointsAndWeights(nQuad, trialsLengths, dtype=torch.double):
nTrials = len(trialsLengths)
legQuadPoints = torch.empty((nTrials, nQuad, 1... | StarcoderdataPython |
3396000 | <reponame>robert-giaquinto/survae_flows
import math
import torch
from torch import nn
class Distribution(nn.Module):
"""Distribution base class."""
def log_prob(self, x):
"""Calculate log probability under the distribution.
Args:
x: Tensor, shape (batch_size, ...)
Return... | StarcoderdataPython |
38267 | <filename>mainpages/views.py<gh_stars>0
from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponseRedirect
from .forms import RegisterForm, LoginForm
from django.urls import reverse
from .datebase_func import make_bd, check_car_wash, add_car_wash, time_by_id, update_t... | StarcoderdataPython |
1715040 | <reponame>evestidor/svc-stock-manager<filename>src/operations/update_stock_price.py
from src import interfaces
from src.domain import Stock
class UpdateStockPriceOperation(interfaces.Operation):
def __init__(self, storage: interfaces.StockStorage):
self._storage = storage
def execute(self, symbol: s... | StarcoderdataPython |
3229340 | <reponame>imaginal/openprocurement.storage.files
from openprocurement.storage.files.storage import FilesStorage
def includeme(config):
settings = config.registry.settings
config.registry.storage = FilesStorage(settings)
| StarcoderdataPython |
174686 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
if sys.version_info >= (3, 0, 0):
from urllib.parse import urlparse
else:
from urlparse import urlparse
if sys.version_info >= (3, 5, 0):
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * ma... | StarcoderdataPython |
3245409 | import re
import string
from nltk.tokenize import word_tokenize
from nltk.stem.porter import PorterStemmer
from nltk.corpus import stopwords
import itertools
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
class FeatureFinder:
def __init__(self):
self.featureVec... | StarcoderdataPython |
1786717 | # 源程序文件名
SOURCE_FILE = "{filename}.hs"
# 输出程序文件名
OUTPUT_FILE = "{filename}.out"
# 编译命令行
COMPILE = "ghc {source} -o {output} {extra}"
# 运行命令行
RUN = 'sh -c "./{program} {redirect}"'
# 显示名
DISPLAY = "Haskell"
# 版本
VERSION = "GHC 8.0.2"
# Ace.js模式
ACE_MODE = "haskell"
| StarcoderdataPython |
1732575 | import random
a1 = str(input('Digite o nome do aluno 1:'))
a2 = str(input('Digite o nome do aluno 2:'))
a3 = str(input('Digite o nome do aluno 3:'))
al = [a1, a2, a3]
print(f'O sorteado para o ir ao quadro foi {random.choice(al)}')
| StarcoderdataPython |
1782972 | <reponame>rsmonteiro2021/execicios_python<gh_stars>1-10
"""
Upgrade de bateria: User a última versão de Electric.car.py desta seção. Acrescente
um método chamado upgrade_battery() na classe Battery. Esse método deve verificar
a capacidade da bateria e defini-la como 85 se o valor for diferente. Crie um carr... | StarcoderdataPython |
1785095 | <reponame>ceddlyburge/unit-testing-calculations<filename>tests/test_construction_margin_calculator_isolate_partial_values.py
from tests.construction_margin_calculator_mockable_abstraction_builder import ConstructionMarginCalculatorMockableAbstractionBuilder
from tests.cash_flow_step_builder import CashFlowStepBuilder
... | StarcoderdataPython |
1636438 | import yaml
import six
script_out = """all:
children:
ungrouped:
hosts:
foobar:
should_be_artemis_here: !vault |
$ANSIBLE_VAULT;1.2;AES256;alan
30386264646430643536336230313232653130643332356531633437363837323430663031356364
383631393564303830626361363... | StarcoderdataPython |
136557 | # -*- coding: utf-8 -*-
u"""
Levenshtein Distance
The Levenshtein distance between two words is the minimal number of
edits that turn one word into the other. Here, "edit" means a
single-letter addition, single-letter deletion, or exchange of a
letter with another letter.
http://en.wikipedia.org/wiki/Levenshtein_dist... | StarcoderdataPython |
3247384 | <gh_stars>1-10
from get_current_pose_joints import get_current_pose_joints
from get_current_pose_cartesian import get_current_pose_cartesian
from stop import stop
| StarcoderdataPython |
3262570 | <filename>Code/Python/RiskyContrib.py
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# notebook_metadata_filter: all
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.0
# kernelspec:
#... | StarcoderdataPython |
3380289 | <reponame>JakeGinnivan/pulumi-aws
# 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 json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. impo... | StarcoderdataPython |
112989 | <gh_stars>0
import os
import sys
from numpy.lib import utils
sys.path.append(".")
import json
from http import HTTPStatus
from fastapi import FastAPI, Path
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
from dogapp import dogconfig, predict, models, utils
app = FastAPI(
title="Do... | StarcoderdataPython |
19564 | <gh_stars>0
from netsuitesdk.internal.utils import PaginatedSearch
from .base import ApiBase
import logging
logger = logging.getLogger(__name__)
class CustomRecords(ApiBase):
def __init__(self, ns_client):
ApiBase.__init__(self, ns_client=ns_client, type_name='CustomRecordType')
def get_all_by_id(s... | StarcoderdataPython |
3350422 | <gh_stars>0
from datetime import datetime
from elasticsearch import Elasticsearch
class Searcher(object):
"""
Class for searching results using parameters
:param location: location string
:param start_date: start date calendar
:param end_date: end date calendar
:param k: total num of docu... | StarcoderdataPython |
3206035 | import unittest
from main import *
class StringsTests(unittest.TestCase):
def test_main(self):
self.assertIsInstance(fccSet, set)
self.assertEqual(len(fccSet), 14)
| StarcoderdataPython |
44915 | import datetime
import functools
import io
import os
import zipfile
import httpx
import pytest
from coverage_comment import coverage as coverage_module
from coverage_comment import github_client, settings
@pytest.fixture
def base_config():
def _(**kwargs):
defaults = {
# GitHub stuff
... | StarcoderdataPython |
139971 | from django.db import models
'''
activity
datetime
user (FK)
type
'''
class Log(models.Model):
activity = models.CharField(max_length=50, null=False, default='')
datetime = models.DateTimeField(auto_now=True)
user = models.ForeignKey(
to='users.User'
,on_delete=models.CASCAD... | StarcoderdataPython |
5802 | <filename>orrinjelo/aoc2021/day_11.py
from orrinjelo.utils.decorators import timeit
import numpy as np
def parse(lines):
return np.array([[int(c) for c in line.strip()] for line in lines])
visited = []
def flash(a, x, y):
global visited
if (x,y) in visited:
return
for dx in range(-1,2):
... | StarcoderdataPython |
3234055 | <reponame>MIklgr500/bowl
TRAIN_PATH = 'input/train'
TEST_PATH = 'input/test2'
FILE_PATH = 'output/'
RANDOM_STATE = 31
IMG_HEIGHT = 128
IMG_WIDTH = 128
IMG_CHAN = 3
MERG_RATION = 1
NU = 1.
MU = 0.
BATCH_SIZE = 32
EPOCHS = 20
| StarcoderdataPython |
71183 |
################################ A Library of Functions ##################################
##################################################################################################
#simple function which displays a matrix
def matrixDisplay(M):
for i in range(len(M)):
for j in range(len... | StarcoderdataPython |
1713656 |
import rospy
class BaseDataModule:
def __init__(self):
pass
def get(self):
raise NotImplementedError
def get_time(self):
return rospy.Time.now()
class LocalDataModule(BaseDataModule):
def __init__(self, rospy,
msg_topic, msg_type):
self.msg_topic = ms... | StarcoderdataPython |
98999 | <gh_stars>0
import platform
from dataclasses import dataclass
from modulefinder import ModuleFinder
from pathlib import Path
from pkgutil import ModuleInfo
from types import ModuleType
from unittest import mock
from cucumber_tag_expressions import parse
from tests.utilities import make_project
from ward import fixtur... | StarcoderdataPython |
5171 | from xagents import a2c, acer, ddpg, dqn, ppo, td3, trpo
from xagents.a2c.agent import A2C
from xagents.acer.agent import ACER
from xagents.base import OffPolicy
from xagents.ddpg.agent import DDPG
from xagents.dqn.agent import DQN
from xagents.ppo.agent import PPO
from xagents.td3.agent import TD3
from xagents.trpo.ag... | StarcoderdataPython |
3354632 | import numpy as np
import theano
import theano.tensor as T
try:
import cPickle as pickle
except:
import pickle
import sys
#list for converting index to character
dic = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',\
'A','B','C','D','E','F','G','H',... | StarcoderdataPython |
68105 | <gh_stars>10-100
#!/usr/bin/python
# BSD LICENSE
#
# Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistr... | StarcoderdataPython |
3215735 | <reponame>rekhabiswal/sage<gh_stars>0
"""
Root system data for dual Cartan types
"""
#*****************************************************************************
# Copyright (C) 2008-2009 <NAME> <anne at math.ucdavis.edu>
# Copyright (C) 2008-2013 <NAME> <nthiery at users.sf.net>
#
# Distributed under th... | StarcoderdataPython |
3289558 | <reponame>gschivley/GenX-helpers
"Calculate region-specific costs from imports/exports/RPS/CES"
import os
from pathlib import Path
import pandas as pd
import yaml
def find_results_folders(year):
cwd = Path.cwd()
results_folders = list((cwd / f"{year}").rglob("Results"))
results_folders.sort()
retu... | StarcoderdataPython |
156493 | <reponame>yaogdu/xiaozu_spider
DB={'address':'127.0.0.1:27017','db':'douban','col':'posts','replicaSet':'dmmongo'}
skip = [',','.',':',';','<','>','/','&','#']
url = 'https://www.douban.com/group/fangzi/discussion?start=100'
print url.split('=').pop(0) | StarcoderdataPython |
3290352 | <gh_stars>1-10
import cv2
from imagepy.core.engine import Simple
import numpy as np
class MatchTemplate(Simple):
title = 'Match Template'
note = ['all']
para = {'mat':'cv2.TM_CCOEFF','img':None}
view = [(list, 'mat', ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2... | StarcoderdataPython |
152825 | <filename>hap-monitor-cron.py
#!/usr/bin/env python
# Copyright European Organization for Nuclear Research (CERN) 2013
#
# 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/li... | StarcoderdataPython |
46995 | def pct_inc(p1, p2) :
return ((p2-p1)/p1)*100
| StarcoderdataPython |
1690093 | <filename>show_architecture.py<gh_stars>0
from resnet_imagenet import resnet18
from resnet import resnet20
# model = resnet18()
# print(model)
model = resnet20().cpu()
import copy
import torch
fused_model = copy.deepcopy(model)
# print(fused_model)
# fuse the layers in the frontend
fused_model = torch.quantization.... | StarcoderdataPython |
167166 | <filename>server/stylegan2_hypotheses_explorer/logic/model_loader/model_loader.py
from ...models import ModelsArray
from ..evaluator import Evaluator
from ..generator import Generator
from ..paths import MODELS_PATH, MODELS_SCHEMA_PATH
from ..util import load_and_validate
from .evaluator_loader import EvaluatorLoader
f... | StarcoderdataPython |
1659013 | <filename>venv/Lib/site-packages/PyQt4/examples/designer/plugins/widgets/counterlabel.pyw
#!/usr/bin/env python
"""
counterlabel.py
A PyQt custom widget example for Qt Designer.
Copyright (C) 2006 <NAME> <<EMAIL>>
Copyright (C) 2005-2006 Trolltech ASA. All rights reserved.
This program is free software; you can red... | StarcoderdataPython |
1672194 | <filename>examples/geomopt/01-pyberny.py
#!/usr/bin/env python
'''
Use pyberny to get the molecular equilibrium geometry.
'''
from pyscf import gto, scf
from pyscf.geomopt.berny_solver import optimize
mol = gto.M(atom='N 0 0 0; N 0 0 1.2', basis='ccpvdz')
mf = scf.RHF(mol)
#
# geometry optimization for HF. There a... | StarcoderdataPython |
3392683 | ## Count characters in your string
## 6 kyu
## https://www.codewars.com/kata/52efefcbcdf57161d4000091
def count(string):
list1 = {}
for item in string:
if item not in list1:
list1[item] = 0
list1[item] += 1
return list1 | StarcoderdataPython |
3329922 | <filename>orttrainer/huggingface-gpt2/ort_addon/ort_supplement/src/transformers/trainer_ort.py
import json
import time
import logging
import os
import random
import re
import shutil
from contextlib import contextmanager
from pathlib import Path
from typing import Callable, Dict, List, NamedTuple, Optional, Tuple
impor... | StarcoderdataPython |
1730592 | from rl.featurizer.featurizer import DiscreteFeaturizer
| StarcoderdataPython |
3321185 | from influxdb import InfluxDBClient, DataFrameClient
import numpy as np
import pandas as pd
import requests
import datetime
import time
import json
import os
import sys
import logging
def readOutput():
# Set some boolean success variables for timer
success = False
## Go up one directory and to the output folder u... | StarcoderdataPython |
3301410 | <reponame>rolker/project11_navigation
#!/usr/bin/python3
'''
Written by <NAME> with contributions from <NAME>
'''
import rospy
import tf2_ros
import tf2_geometry_msgs
from nav_msgs.msg import OccupancyGrid
from geographic_visualization_msgs.msg import GeoVizItem, GeoVizPointList, GeoVizPolygon
from geometry_msgs.msg... | StarcoderdataPython |
3331561 | <filename>src/ui/views/paragraphs.py
import Tkinter as tk
from . import ViewBase, ViewWithUpdate
from decorators import register_view
from functools import partial
from lxml import etree
@register_view('paragraph', 'interpParagraph')
class ParagraphView(ViewBase, ViewWithUpdate):
def __init__(self, *args, **kwar... | StarcoderdataPython |
131437 | <reponame>Ramossvitor/PYTHON
import math
num1 = float(input('Digite um numero: '))
print('O numero {} tem a parte inteira {:.0f}'.format(num1, math.trunc(num1))) | StarcoderdataPython |
1749353 | from neupy import layers
from neupy.exceptions import LayerConnectionError
from base import BaseTestCase
class InputTestCase(BaseTestCase):
def test_input_exceptions(self):
layer = layers.Input(10)
error_message = "Input layer got unexpected input"
with self.assertRaisesRegexp(LayerConne... | StarcoderdataPython |
52346 | import _init_paths
import tensorflow as tf
from fast_rcnn.config import cfg
from fast_rcnn.test import im_detect
from fast_rcnn.nms_wrapper import nms
from utils.timer import Timer
#import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os, sys, cv2
import argparse
from netwo... | StarcoderdataPython |
1728194 | <gh_stars>100-1000
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from collections import deque, namedtuple
import warnings
import random
from utils.helpers import Experience
def sample_batch_indexes(low, high, size):
if high - low >... | StarcoderdataPython |
3349809 | from __future__ import print_function
#%matplotlib inline
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as tran... | StarcoderdataPython |
192869 | <reponame>franklinzhanggis/model-interoperable-engine
from .utils import HttpHelper
class Service:
def __init__(self, ip, port):
self.ip = ip
self.port = port
def getBaseURL(self):
return "http://" + self.ip + ":" + str(self.port) + "/"
def connect(self):
strData = Htt... | StarcoderdataPython |
3276863 | <filename>8-recursion-and-dynamic-programming/2-robot-in-grid/dp_solution.py
"""
Problem:
8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns.
The robot can only move in two directions, right and down, but certain cells are "off limits" such that
the robot cannot ste... | StarcoderdataPython |
3356866 | """
Functions for saving experiment data
"""
from os.path import join
import torch
from torch.nn import Module
from src.metrics.metric_recollector import MetricRecollector
DATA_PROCESSED_FOLDER = 'data/processed'
MODELS_FOLDER = 'models'
def save_experiment_data(
experiment: str,
model: Module,
metrics: ... | StarcoderdataPython |
1669442 | from collections import deque
class Solution:
def findOrder(self, numCourses: int, prerq: list) -> list:
# build an adjcaent list
graph = {}
for e in prerq:
if e[1] in graph:
graph[e[1]].append(e[0])
else:
graph[e[1]]... | StarcoderdataPython |
4818323 | #!/usr/bin/env python
from __future__ import print_function
import os
import ecflow
# When no arguments specified uses ECF_HOST and/or ECF_PORT,
# Explicitly set host and port using the same client
# For alternative argument list see ecflow.Client.set_host_port()
HOST = os.getenv("ECF_HOST", "localhost")
PORT = int(os.... | StarcoderdataPython |
79264 | <filename>src/loadbalancer/job.py
"""The job class represents a job on the cluster."""
from datetime import datetime
class Job:
def __init__(self, job_id, requested_queue, assigned_queue, owner, state, predecessors, submit_timestamp):
"""Constructor
Args:
job_id (int) - The job ID.
... | StarcoderdataPython |
3348434 | <filename>tests/api/test_webapplication.py<gh_stars>1-10
import pytest
from bromine import WebApplication
@pytest.fixture(name='app')
def app_fixture():
app = WebApplication('https://www.example.com', object())
return app
def test_base_url(app):
assert app.base_url == 'https://www.example.com'
def te... | StarcoderdataPython |
3354931 | """ PyTest Configuration """
import mongoengine
def pytest_configure(config):
"""setup configuration"""
import sys
sys._called_from_test = True
from settings import settings
mongoengine.connect(host=settings.MONGODB_URI)
def pytest_unconfigure(config):
"""teardown configuration"""
conn =... | StarcoderdataPython |
139049 | <reponame>FarhanAliRaza/django-sockpuppet
from sockpuppet.reflex import Reflex
class ExampleReflex(Reflex):
def increment(self, step=1):
self.session['count'] = int(self.element.dataset['count']) + step
class DecrementReflex(Reflex):
def decrement(self, step=1):
self.session['otherCount'] = ... | StarcoderdataPython |
1629440 | <gh_stars>0
#!/usr/bin/env python
from collections import deque
import numpy as np
from numpy.random import choice, randint
import matplotlib.pyplot as plt
def maze(cells=(25, 25), start=(0, 0), exit=(-1, -1)):
"""Generates a binary numpy array that represents a maze.
Values of 1 are colored and are ... | StarcoderdataPython |
67856 | """ Miscellaneous utility functions """
import logging
import os
import pandas as pd
logger = logging.getLogger(__name__)
def load_df_from_dataset(file_name: str) -> pd.DataFrame:
""" Loads cleaned dataframe from csv
Fields with extra records get logged and dropped.
"""
df = pd.read_csv(file_name)
... | StarcoderdataPython |
1658355 | <filename>pytype/tests/test_recovery.py<gh_stars>10-100
"""Tests for recovering after errors."""
from pytype.tests import test_inference
class RecoveryTests(test_inference.InferenceTest):
"""Tests for recovering after errors.
The type inferencer can warn about bad code, but it should never blow up.
These tes... | StarcoderdataPython |
1782630 | # Generated by Django 2.2.1 on 2019-07-26 20:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0019_auto_20190617_0141'),
]
operations = [
migrations.CreateModel(
name='ClassTemp',
fields=[
... | StarcoderdataPython |
53163 | <filename>Util.py
# -*- coding:utf-8 -*-
import random
import string
import base64
import hmac
import hashlib
import logging
import sys
import time
import os
TIME_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
ISO8601 = '%Y%m%dT%H%M%SZ'
ISO8601_MS = '%Y-%m-%dT%H:%M:%S.%fZ'
RFC1123 = '%a, %d %b %Y %H:%M:%S %Z'
class InitSSHRem... | StarcoderdataPython |
1782083 | <filename>src/curt/curt/modules/vision/image_classification.py
"""
Copyright (C) Cortic Technology Corp. - All Rights Reserved
Written by <NAME> <<EMAIL>>, 2021
"""
import tvm
from tvm.contrib import graph_runtime
import numpy as np
import time
from scipy.special import expit, logit
import cv2
import math
import os
... | StarcoderdataPython |
67653 | <gh_stars>1000+
# Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Subprocess utilities.
"""
from subprocess import PIPE, STDOUT, CalledProcessError, Popen
from eliot import Message, start_action
from pyrsistent import PClass, field
class _CalledProcessError(CalledProcessError):
"""
Just like ``C... | StarcoderdataPython |
111823 | #!/bin/env python
import os
import itk
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from glob import glob
from FemurSegmentation.IOManager import ImageReader
from FemurSegmentation.IOManager import VolumeWriter
from FemurSegmentation.filters import execute_pipeline
from Femu... | StarcoderdataPython |
4810125 | <gh_stars>1-10
# Generated by Django 3.1.5 on 2021-05-02 10:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('hospital', '0015_remove_admin_status'),
]
operations = [
migrations.RemoveField(
... | StarcoderdataPython |
53418 | """Load the Tatoeba dataset."""
import sys
import os
import csv
import subprocess
import time
from multiprocessing import Pool, Lock, cpu_count
from tqdm import tqdm
from scipy.io import wavfile
from python.params import MIN_EXAMPLE_LENGTH, MAX_EXAMPLE_LENGTH
from python.dataset.config import CACHE_DIR, CORPUS_DIR
f... | StarcoderdataPython |
3247250 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 4 10:48:58 2018
@author: <NAME>
"""
import numpy as np
import pandas as pd
from HelperFuncs import ppLFER, vant_conv, arr_conv, make_ppLFER
from FugModel import FugModel
class ppLFERMUM(FugModel):
""" ppLFER based Multimedia Urban Model fugacity model object. ... | StarcoderdataPython |
50531 | """Model: A python model of RFC 5545.
=====================================
"""
__author__ = 'Jason'
import datetime
from icalendar import Calendar
from icalendar import Event
ARG_TYPE_INCORRECT = 'Argument should be of type {0}'
REQ_PROP_MISSING = 'Required property {0} is missing'
class CalendarModel():
"""R... | StarcoderdataPython |
1761941 | <gh_stars>1-10
"""
** 2 columns
we visualize live stock market data and also get live news
1. live market data (stock list)
2. live news data
"""
#### IMPORTING REQUIRED MODULES
from dash_bootstrap_components.themes import YETI
try:
#data analysis modules
import pandas as pd
import numpy as np
#d... | StarcoderdataPython |
120463 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# author : ysoftman
# title : beautifulsoup test
# python version : 2.x
import sys
# http://docs.python-requests.org/en/master/
import requests
# https://www.crummy.com/software/BeautifulSoup/
# pip install beautifulsoup4
from bs4 import BeautifulSoup
def parse_html():
pri... | StarcoderdataPython |
1607838 | <filename>scripts/mark_orphaned_guids.py
"""A number of GUIDs with invalid or missing referents
were found during the mongo -> postgres migration.
These GUIDS were parsed from the migration logs and written to scripts/orphaned_guids.json.
This script adds a field, `is_orphaned` to these GUIDS and sets it to True so th... | StarcoderdataPython |
3347437 | <reponame>sagar30051991/helpdesk<gh_stars>1-10
from __future__ import unicode_literals
import json
import frappe
hierarchy = {
1: {
"time":2,
"role": "Administrator",
"is_dept_escalation": 0
},
2: {
"time":2,
"role": "Department Head",
"is_dept_escalation": 0
}
}
roles_priority = ["Administrator","Dep... | StarcoderdataPython |
11341 | <filename>Package/CONFIG.py
import ops
import iopc
TARBALL_FILE="samba-4.8.4.tar.gz"
TARBALL_DIR="samba-4.8.4"
INSTALL_DIR="samba-bin"
pkg_path = ""
output_dir = ""
tarball_pkg = ""
tarball_dir = ""
install_dir = ""
install_tmp_dir = ""
cc_host = ""
tmp_include_dir = ""
dst_include_dir = ""
dst_lib_dir = ""
dst_usr_lo... | StarcoderdataPython |
55538 | <filename>ownblock/ownblock/apps/storage/models.py
import uuid
import os
import mimetypes
from django.conf import settings
from django.db import models
from sorl.thumbnail import get_thumbnail, delete
from ..buildings.models import Building
class Place(models.Model):
name = models.CharField(max_length=60)
... | StarcoderdataPython |
3261778 | """
Betty365 - Unofficial Bet365 WebSocket Stream Data Processor
Author: @ElJaviLuki
"""
# DEPENDENCIES
from random import random
import websockets
from readit import StandardProtocolConstants, ReaditMessage
# Generate URIs
def generate_uid():
return str(random())[2:]
def generate_premws_uri():
retu... | StarcoderdataPython |
45642 | from collections import namedtuple
from itertools import chain
from os import makedirs, rename, scandir, listdir
from os.path import (join as p, exists, relpath, isdir, isfile,
expanduser, expandvars, realpath)
from struct import pack
import errno
import hashlib
import json
import logging
import re
import shuti... | StarcoderdataPython |
1746339 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | StarcoderdataPython |
3266869 | <gh_stars>0
from typing import Union, List, Tuple
import numpy as np
import pandas as pd
from scipy import optimize
from matplotlib import pyplot as plt
from pyquil.api import QuantumComputer
from pyquil.gates import RX, RZ, CZ, MEASURE
from pyquil.quil import Program
from pyquil.quilbase import Pragma
MILLISECOND =... | StarcoderdataPython |
4800847 | # vim: fileencoding=utf-8
import fnmatch
import os
import werkzeug
from docutils import nodes
from docutils.core import publish_parts
from docutils.parsers.rst import Directive, directives
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import LEXERS, guess_lexer_for... | StarcoderdataPython |
3253940 | <gh_stars>0
#!/usr/bin/env python
from multi_circle_2 import Multi_circle_2
if __name__ == '__main__':
multi_circle_2 = Multi_circle_2(
[
#x , y, z, yaw, sleep
[0.0 , 0.0, 1.0, 0, 8],
[0.0 , 0.0 ,1.0, 0, 3],
[-0.3 , -1.4, 0.0, 0, 0],
]
)
multi_c... | StarcoderdataPython |
1786055 | <filename>ThirdParty/incremental/vtkincremental/src/incremental/__init__.py<gh_stars>1-10
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Versions for Python packages.
See L{Version}.
"""
from __future__ import division, absolute_import
import os
import sys
import warnings
#
# Compat fu... | StarcoderdataPython |
3359 | def modify(y):
return y # returns same reference. No new object is created
x = [1, 2, 3]
y = modify(x)
print("x == y", x == y)
print("x == y", x is y) | StarcoderdataPython |
196575 | import re
from datetime import datetime
from moto.core import get_account_id, BaseBackend
from moto.core.utils import iso_8601_datetime_without_milliseconds, BackendDict
from .exceptions import (
InvalidInputException,
ResourceAlreadyExistsException,
ResourceNotFoundException,
ValidationException,
)
... | StarcoderdataPython |
1690005 | <filename>tests/api/controller/test_controller.py
# (c) Copyright 2015-2016 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017 SUSE LLC
from datetime import datetime
import json
import logging
import mock
import time
from bll import api
from bll.api.controllers import app_controller
from bll.api.controller... | StarcoderdataPython |
54741 | <reponame>Jimmy-INL/SKDMD<gh_stars>1-10
import sys
import numpy as np
sys.path.insert(0, '../../../')
from SKDMD.MODEL_SRC.kdmd import KDMD
from SKDMD.PREP_DATA_SRC.source_code.lib.utilities import timing
class CKDMD(KDMD):
"""
Class for Kernel DMD
with kernel as
* Gaussian kernel
* polynomial ... | StarcoderdataPython |
154705 | from .mobilenetv2 import QuantizableMobileNetV2, mobilenet_v2, __all__ as mv2_all
from .mobilenetv3 import QuantizableMobileNetV3, mobilenet_v3_large, mobilenet_v3_small, __all__ as mv3_all
__all__ = mv2_all + mv3_all
| StarcoderdataPython |
1701468 | <reponame>skurob/cgas
from .constants import DEFAULT_SUCCESS, SUCCESS_KEY, MESSAGE_KEY, DATA_KEY, DEFAULT_FAILURE
from telethon.tl.types import User
from typing import Any
class UserModels:
@staticmethod
def success(message: str = None, data: Any = None) -> dict:
if message != None and data != None:
... | StarcoderdataPython |
3318169 | <reponame>larsoner/beamformer_simulation
import warnings
import mne
import numpy as np
import pandas as pd
from mne.beamformer import make_dics, apply_dics_csd
from mne.forward.forward import _restrict_forward_to_src_sel
from mne.time_frequency import csd_morlet
import config
from config import fname, dics_settings
f... | StarcoderdataPython |
1633837 | <reponame>knuu/competitive-programming<filename>atcoder/arc/arc079_b.py
K = int(input())
L = 50
N = K // L + L - 1
res = K - (N - L + 1) * L
assert(res < 50)
ans = [N] * L
for i in range(res):
ans[i] += L - res + 1
for i in range(res, L):
ans[i] -= res
print(L)
print(*ans)
| StarcoderdataPython |
3385512 | from django.urls import path
from main import views
from django.db import connection
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('',views.index, name="index-1"),
path('services', views.services, name='services'),
path('contact-us', views.contact_us, n... | StarcoderdataPython |
1660004 | #
# Copyright (c) 2019, Neptune Labs Sp. z o.o.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | StarcoderdataPython |
1682213 | import torch
from torch.nn import Dropout
import torch.nn.functional as F
import math
class PositionalEncoding(torch.nn.Module):
def __init__(self,
d_model,
dropout=0.1,
max_len=500,
identical_sizes = True
):
super(Posi... | StarcoderdataPython |
102812 | <gh_stars>0
import pathlib
import random
from absl import app
from absl import flags
import tensorflow as tf
import tensorflow_federated as tff
from data_helpers import make_client_ids
from data_helpers import provide_client_data_fn
from model_helpers import build_vgg16
# Hyperparams
flags.DEFINE_integer("num_round... | StarcoderdataPython |
173823 | <reponame>CrazyAZ/BLSS-Input-Viewer
# This Pro Controller driver code is based on https://github.com/yvbbrjdr/procon/blob/master/src/procon.py
import math
import time
import hid
def to_int16(uint16):
return -((uint16 ^ 0xFFFF) + 1) if uint16 & 0x8000 else uint16
class ProCon:
VENDOR_ID = 0x057E
PRODUCT_... | StarcoderdataPython |
4807535 | <reponame>victoria-cds-sig/explore_mimiciv
import bqutils.auth as auth
import bqutils.ibis as iq
def main():
client = iq.get_client(*auth.get_gcreds())
db = client.database("bigquery-public-data.stackoverflow")
expression = db.table("posts_questions").projection(["creation_date", "answer_count"]).limit(5)... | StarcoderdataPython |
88261 | # Authors: <NAME> <<EMAIL>>
# License: BSD 3 clause
# functions shared across transformers
def _define_variables(variables):
# Check that variable names are passed in a list.
# Can take None as value
if not variables or isinstance(variables, list):
variables = variables
else:
variables... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.