id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3209713 | import subprocess
from pathlib import Path
from typing import List, Optional, Sequence
import shutil
import os
from flacmirror.options import Options
# We need this so that the child processes do not catch the signals ...
def preexec_function():
os.setpgrp()
def check_requirements(options: Options) -> bool:
... | StarcoderdataPython |
187743 | <reponame>ifwe/digsby
import wx
from gui.uberwidgets import UberWidget
from gui import skin
from gui.skin.skinobjects import SkinColor,Margins
from cgui import SimplePanel
objget = object.__getattribute__
class PanelFrame(SimplePanel, UberWidget):
'''
Frame for panels in the buddylist
'''
def __init_... | StarcoderdataPython |
27281 | import geopandas as gpd
# not used anymore - converts esri jobs shapefile to a csv
# see assign_jobs_lat_lng.py
gdf = gpd.GeoDataFrame.from_file("est10_esri_gt1.shp")
gdf = gdf.to_crs(epsg=4326)
fname_map = {
'Duns_Numbe': 'duns_number',
'Business_N': 'business_name',
'Emp_Total': 'total_employment',
... | StarcoderdataPython |
3270124 | from threading import Thread
from tanager_feeder import utils
from tanager_feeder.connection_checkers.connection_checker import ConnectionChecker
class Listener(Thread):
def __init__(self, connection_manager: utils.ConnectionManager, connection_checker: ConnectionChecker):
Thread.__init__(self)
s... | StarcoderdataPython |
156687 | <gh_stars>10-100
try:
from functools import cache
except ImportError:
from functools import lru_cache
def cache(f):
return lru_cache(maxsize=None)(f)
import shlex
try:
join_command_terms = shlex.join
except AttributeError:
def join_command_terms(terms):
return ' '.join(shlex.quot... | StarcoderdataPython |
146090 | <gh_stars>0
import falcon.testing
import pytest
import sqlalchemy as sa
import marshmallow as mm
import marshmallow_sqlalchemy as mms
import falcon_helpers.sqla.orm as orm
import falcon_helpers.sqla.db as db
from falcon_helpers.middlewares.marshmallow import MarshmallowMiddleware
@pytest.fixture()
def client():
... | StarcoderdataPython |
80870 | """Host Model"""
from cbw_api_toolbox.cbw_objects.cbw_package import CBWPackage
from cbw_api_toolbox.cbw_objects.cbw_server import CBWCve
from cbw_api_toolbox.cbw_parser import CBWParser
class CBWHost:
"""Host Model"""
def __init__(self,
id, # pylint: disable=redefined-builtin
... | StarcoderdataPython |
4811491 | '''
@author: <NAME>
@summary: Holds all the utilities functions required to support batch_requests.
'''
from __future__ import absolute_import, unicode_literals
import six
from django.test.client import RequestFactory, FakePayload
from batch_requests.settings import br_settings as _settings
# Standard WSGI support... | StarcoderdataPython |
3216646 | from django.test import TestCase
class StoreDomainTestCase(TestCase):
...
| StarcoderdataPython |
1632907 | <filename>learning/oscilloscope/aom_power_change.py
import sys
sys.path.append("D:\\Control\\PythonPackages\\")
import SingleChannelAO
import tektronix
#pixels where the height is the data
#background is where there isnt data
#time scale must be 500ns per square
pulse_range = (330, 470)
background_range = (0, 150)... | StarcoderdataPython |
20055 | <filename>setup.py
from setuptools import setup
setup(
name='csv_locate',
version='0.1',
py_modules=['csv_to_json'],
install_requires=[
'click',
'colorama',
'geocoder',
'geojson',
'jinja2',
],
entry_points='''
[console_scripts]
csv_locate=... | StarcoderdataPython |
75708 | <reponame>lmrissi/piloto_geodjango<gh_stars>0
import os
from django.contrib.gis.utils import LayerMapping
from .models import pocos
# Auto-generated `LayerMapping` dictionary for pocos model
pocos_mapping = {
'proprietario': 'proprietar',
'orgao': 'orgao',
'data_perfuracao': 'data_perfu',
'pro... | StarcoderdataPython |
131778 | import logging
import os
from dvc.repo import locked
from dvc.repo.scm_context import scm_context
from dvc.scm.base import RevError
from dvc.utils.fs import remove
from .base import (
EXEC_APPLY,
ApplyConflictError,
BaselineMismatchError,
InvalidExpRevError,
)
from .executor.base import BaseExecutor
... | StarcoderdataPython |
174234 | from abc import ABC, ABCMeta, abstractmethod, abstractproperty
from torch.nn import Module, MSELoss, Linear
from torch.optim import Adam
import torch
from torch.autograd import Variable
import torch.nn.functional as F
from torch import FloatTensor
import os
import matplotlib as mpl
import torch.nn as nn
mpl.use('Agg')... | StarcoderdataPython |
1633108 | <filename>mundo3/ex114.py
import urllib.request
try:
urllib.request.urlopen('http://www.pudin.com.br')
except:
print('Deu erro.')
else:
print('Tudo ok')
| StarcoderdataPython |
4819893 | from .formulas import get_mappings
from .workspace import workspace
from .workspace_structure import WorkspaceStructure
class Correspondence(WorkspaceStructure):
def __init__(
self,
object_from_initial,
object_from_target,
concept_mappings,
flip_target_object,
):
... | StarcoderdataPython |
3297065 | <reponame>dry923/scribe
from . import ScribeModuleBaseClass
from . lib.util import validate_length
import re as _re
class Cpuinfo(ScribeModuleBaseClass):
def __init__(self, input_dict=None, module_name=None, host_name=None,
input_type=None, scribe_uuid=None):
ScribeModuleBaseClass.__init... | StarcoderdataPython |
26944 | import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import matplotlib.pyplot as plt
num = np.array(['3.14','-2.7','30'], dtype=np.string_) #코드 이해 쉽게 : dtype=np.string_
# num=num.astype(int)
# print(num)
# ValueError: invalid literal for int() with base 10: '3.14'
num=num.astype(float).... | StarcoderdataPython |
1646377 | <gh_stars>100-1000
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/adapters.prophet.ipynb (unless otherwise specified).
__all__ = ['AutoARIMAProphet']
# Cell
import sys
from copy import deepcopy
import numpy as np
import statsmodels.api as sm
import pandas as pd
from ..arima import AutoARIMA
if sys.version_info.min... | StarcoderdataPython |
1772667 | <reponame>juan0tron/wagtailmedia
from django.apps import AppConfig
class WagtailMediaAppConfig(AppConfig):
name = 'wagtailmedia'
label = 'wagtailmedia'
verbose_name = "Wagtail media"
| StarcoderdataPython |
3219821 | # Copyright {% now 'local', '%Y' %} {{ cookiecutter.author }}
# See LICENSE for details.
import io
from setuptools import setup, find_packages
def readme():
with io.open('README.md', encoding='utf-8') as f:
return f.read()
def requirements(filename):
reqs = list()
with io.open(filename, encodin... | StarcoderdataPython |
4840217 | import os
import time
import datetime
# The sum of elements in celeba test data recognition & not recognition ≠ the number of celeba test data.
# So I code this to detect repeat elements.
# a:celeba test data; b:recognition; c:not recognition
# There are 5 cases:
# 1.in b+c not in a
# 2.in a not in b+c
# 3.in b and in... | StarcoderdataPython |
3295917 | <filename>migrations/0009_add_api_key_to_user.py
from playhouse.migrate import PostgresqlMigrator, migrate
from redash.models import db
from redash import models
if __name__ == '__main__':
db.connect_db()
migrator = PostgresqlMigrator(db.database)
with db.database.transaction():
column = models.U... | StarcoderdataPython |
98225 | <filename>egs2/ptbr/asr1/relatorio/recognize.py
import os
import io
import copy
import yaml
import torch
import shutil
import zipfile
import librosa
import numpy as np
from pathlib import Path
from os.path import abspath, join, exists, dirname, isfile, isdir
from typing import Tuple, Any, Dict, Union, Type... | StarcoderdataPython |
3254742 | <gh_stars>1-10
#!/usr/bin/python3
# coding: utf-8
# Contributors:
# ---------------
# (I lost interest in this project, make good use of what code is here) Also FYI, When I told you that you should make a community chat this isn't what I meant.
# @inc0gnit0
# @
# @
# Colors.
Red = '\033[91m'
Cyan = '\033[96m'
Pi... | StarcoderdataPython |
1791568 | from shared_config import *
word_size = 7
num_words = 256
words_per_row = 4
local_array_size = 25
output_extended_config = True
output_datasheet_info = True
netlist_only = True
nominal_corner_only = True
| StarcoderdataPython |
3367897 | #2790---Ioanna---Papagianni
def findLimits():
with open('Beijing_restaurants.txt', 'r', encoding = 'UTF-8') as df1:
lineNum = 0
maxX = 0
maxY = 0
minX = 200
minY = 200
try:
df1.__next__()
except StopIteration:
print('StopIter... | StarcoderdataPython |
105973 | #!/usr/bin/env python
# Copyright (c) 2011, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, thi... | StarcoderdataPython |
77041 | <filename>Lesson 5 Miniflow/Backpropagation/nn.py
import numpy as np
from miniflow import *
X, W, b = Input(), Input(), Input()
y = Input()
f= li | StarcoderdataPython |
86464 | import basilica
import os
from dotenv import load_dotenv
load_dotenv()
BASCILICA_API_KEY=os.getenv("BASCILICA_API_KEY", default="oops")
sentences = [
"This is a sentence!",
"This is a similar sentence!",
"I don't think this sentence is very similar at all...",
]
with basilica.Connection(BASCILICA_API_KEY)... | StarcoderdataPython |
20368 | from distutils.core import setup
setup(
name='pyASA',
packages=['pyASA'],
version='0.1.0',
description='Wrapper for the Cisco ASA REST API',
author='xpac',
author_email='<EMAIL>',
url='https://github.com/xpac1985/pyASA',
download_url='https://github.com/xpac1985/pyASA/tarball/0.1.0',
... | StarcoderdataPython |
169352 | <filename>framework/generated/vulkan_generators/vulkan_command_buffer_util_header_generator.py
#!/usr/bin/python3 -i
#
# Copyright (c) 2018-2019 Valve Corporation
# Copyright (c) 2018-2019 LunarG, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated doc... | StarcoderdataPython |
185213 | #!/usr/bin/env python3
# coding: UTF-8
import requests, socket, re, time
import os, json, datetime, subprocess, calendar
from requests_oauthlib import OAuth1Session
from bs4 import BeautifulSoup
import collections as cl
from flask import Flask, render_template, request, jsonify
# chromium用 Selenium
from selenium impor... | StarcoderdataPython |
4837406 |
import itertools
def prune(compare):
toPrune = set(test[0]).issubset(compare[0]) and test[1] > compare[1]
print(toPrune)
return not(toPrune)
tests = [
[[["a"], 0.9], [["b"], 0.2], [["c"], 0.1]],
[[["a","b"], 0.3], [["b","c"], 0.4], [["a","c"], 0.7]],
[[["a","b","c"], 0.1], [["d","e","f"],0.01]]
]
fo... | StarcoderdataPython |
1753634 | import pickle
import os
from modules.nlp_engine.model_builder.trainer import Trainer
from modules.services.auth_service import AuthService
from modules.data.dao.broker_dao import BrokerDao
from modules.data.dao.trained_classifier_dao import TrainedClassifierDao
from modules.utils.yaml_parser import Config
import loggin... | StarcoderdataPython |
1679336 | # -*- coding: utf-8 -*-
import copy
import redis
from nose.tools import eq_, ok_
from ddtrace import Pin, compat
from ddtrace.contrib.redis import get_traced_redis, get_traced_redis_from
from ddtrace.contrib.redis.patch import patch, unpatch
from ..config import REDIS_CONFIG
from ...test_tracer import get_dummy_trac... | StarcoderdataPython |
1663768 | <reponame>sayakpaul/ConvNeXt-TF
from tqdm import tqdm
import os
"""
Details about these checkpoints are available here:
https://github.com/facebookresearch/ConvNeXt#results-and-pre-trained-models.
"""
imagenet_1k_224 = {
"convnext_tiny": "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth",
... | StarcoderdataPython |
3361449 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-06-22 12:08
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... | StarcoderdataPython |
3261843 | <filename>Solutions/Solution_Problem_4.py
mass = int(input("Qual seu peso? "))
height = int(input("Qual seu tamanho? "))
def calcIMC(mass, height):
mass = mass * 10000
phisicalCondition = mass / (height ** 2)
print("IMC: ", phisicalCondition)
calcIMC(mass, height) | StarcoderdataPython |
3321292 | <gh_stars>0
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 |
3389314 | from scipy.optimize import fsolve
import math
def equations(p):
#vin, imax = p
#return (-78*vin + 3700*imax-2194*vin*imax-23410*imax**2+22.9*vin**3+716382*imax**3)
#vin, imax = fsolve(equations, (0.9, 0.01))
#print (equations((vin, imax)))
fnom = p
return(3.7442024014121142e04 + -6.846677e-05*fnom ... | StarcoderdataPython |
153091 | from flask_restful import reqparse
from werkzeug.datastructures import FileStorage
blog_create_parser = reqparse.RequestParser(bundle_errors=True)
blog_create_parser.add_argument("title", type=str, required=True)
blog_create_parser.add_argument("content", type=str, required=True)
blog_create_parser.add_argument(
"... | StarcoderdataPython |
1674245 | # -*- coding: utf-8 -*-
from ccxt.async.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
class mixcoins (Exchange):
def describe(self):
return self.deep_extend(super(mixcoins, self).describe(), {
'id': 'mixcoins',
'name': 'MixCoins',
... | StarcoderdataPython |
1737462 | <gh_stars>0
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from mmcv.runner.hooks import EvalHook, DistEvalHook
class MyEvalHook(EvalHook):
def _save_ckpt(self, runner, key_score):
"""Save the best checkpoint.
It will compare the score according to the compare function, wr... | StarcoderdataPython |
77741 | <filename>editor_api/database/output/aquifer.py
from peewee import *
from .base import OutputBase
class Aquifer(OutputBase):
flo = DoubleField(null=True)
stor = DoubleField(null=True)
rchrg = DoubleField(null=True)
seep = DoubleField(null=True)
revap = DoubleField(null=True)
dep_wt = DoubleField(null=True)
no3... | StarcoderdataPython |
3253186 | # Echo client program
import socket
import matplotlib.pyplot as plt
import numpy as np
def importar(arquivo):
s=[]
t=[]
flag=0
l=[]
with open(arquivo) as csvfile:
spamreader = csv.reader(csvfile, delimiter='\t', quotechar=',')
for row in spamreader:
if(len(row)>2):
s.append(float(... | StarcoderdataPython |
3382910 | """
*
* Author: <NAME>(coderemite)
* Email: <EMAIL>
*
"""
i=input
a=i()
exec('b=['+'i(),'*10+']')
b=dict(zip(b,range(10)))
for i in range(0,len(a),10):
print(b[a[i:i+10]],end='') | StarcoderdataPython |
1703161 | <filename>framework3d/speech.py
import platform
if platform.system()=="Linux":
import espeak.core
else:
from accessible_output2.outputs import auto
o=auto.Auto()
def speak(text,interrupt=True):
if platform.system()=="Linux":
if interrupt:
espeak.core.cancel()
return espeak.core.synth(text)
else:
o.braille... | StarcoderdataPython |
3394790 | # finds 2 specific elements of a list for 3 qubits (101 and 110)
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_histogram
# Apply an H-gate to n# of qubits
def initialize_s(QuantumCirc... | StarcoderdataPython |
187330 | <reponame>OpenMDAO-Plugins/nastranwrapper
from openmdao.main.api import Component
from openmdao.lib.datatypes.api import Float
from openmdao.lib.components.nastran.nastran import NastranComponent
class Bar3Dynamic(NastranComponent):
""" Dynamic model of three bar truss """
lumpedmass = Float(1., nastran_car... | StarcoderdataPython |
1764896 | <reponame>julio-navarro-lara/thesis_scripts<filename>experiment_9/morwilog_v10/phase2_execution.py
#Copyright 2018 <NAME>
#Built at the University of Strasbourg (France). CSTB team @ ICube laboratory
#12/06/2018
import random
import math
from library import *
def roulette_choice(choices):
max = sum(choices.value... | StarcoderdataPython |
33801 | class Error():
def __init__(self):
print("An error has occured !")
class TypeError(Error):
def __init__(self):
print("This is Type Error\nThere is a type mismatch.. ! Please fix it.") | StarcoderdataPython |
91864 | <filename>factory-ai-vision/EdgeSolution/modules/WebModule/backend/vision_on_edge/azure_training/tests/test_drf_urls.py
"""DRF url tests
"""
import pytest
from django.urls import resolve, reverse
from vision_on_edge.azure_training.models import Project
pytestmark = pytest.mark.django_db
def test_project_detail(pro... | StarcoderdataPython |
166295 | # Clean data for predicting
import pandas as pd
import numpy as np
import scipy.sparse as sparse
import pickle
import os
import ipdb
import gc
from sklearn.cluster import MiniBatchKMeans
from joblib import Parallel, delayed
from departments import all_departments, top_upcs
train = test = labels = features = None
gr... | StarcoderdataPython |
34527 | #
# SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""
Channel sub-package of the Sionna library implementing 3GPP TR39.801 models.
"""
# pylint: disable=line-too-long
from .antenna import AntennaElement, AntennaPanel, Pane... | StarcoderdataPython |
3207517 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Copyright (C) 2015-2016 <NAME> <<EMAIL>>
# Use of this source is governed by the MIT license, see LICENSE file.
#-------------------------------------------------------------------------------
... | StarcoderdataPython |
168911 | <reponame>elifesciences/elife-cleaner<filename>tests/helpers.py<gh_stars>0
import io
import os
import importlib
def delete_files_in_folder(folder, filter_out=None):
file_list = os.listdir(folder)
for file_name in file_list:
file_path = os.path.join(folder, file_name)
if filter_out and file_nam... | StarcoderdataPython |
124463 | <gh_stars>100-1000
import os
from setuptools import find_packages, setup
version = None
with open("README.md") as ref:
data = ref.readlines()[2]
version = data[data.find("version-v")+9:data.find("-blue")]
assert version is not None, data
cwd = os.path.dirname(os.path.abspath(__file__))
def write_version... | StarcoderdataPython |
115721 | # Tests for subclasses of Immutable
#
# Written by <NAME>
#
import unittest
from immutable import Immutable, ImmutableTuple
class Test1(Immutable):
def __init__(self, a, b):
self.a = a
self.b = b
class Test2(Test1):
def __init__(self, a, b, c):
Test1.__init__(self, a, b)
se... | StarcoderdataPython |
1668100 | <reponame>Andrew-Chen-Wang/django-infinite-scroll
from django.urls import path
from django.views.generic import TemplateView
from . import views
urlpatterns = [
path("", TemplateView.as_view(template_name="index.html")),
path("function/", views.index, name="function"),
# path("class/", views.all_view, name... | StarcoderdataPython |
3239807 | <gh_stars>0
from daphne_context.models import UserInformation
from dialogue.param_extraction_helpers import sorted_list_of_features_by_index, crop_list
def extract_example(processed_question, number_of_features, user_information: UserInformation):
# Get a list of examples
examples = ["example1", "example2", "... | StarcoderdataPython |
19895 | <gh_stars>1-10
"""MetroRail Station related structures
"""
from enum import Enum
from typing import Any, Optional
class Station(Enum):
"""A MetroRail Station
"""
A01 = "A01"
A02 = "A02"
A03 = "A03"
A04 = "A04"
A05 = "A05"
A06 = "A06"
A07 = "A07"
A08 = "A08"
A09 = "A09"
A... | StarcoderdataPython |
1671381 | <reponame>boroivanov/ecr-tools<gh_stars>1-10
import pytest
from click.testing import CliRunner
@pytest.yield_fixture(scope='session')
def runner():
'''
Setup a Python Click cli runner, this gets executed for each test function.
'''
yield CliRunner()
| StarcoderdataPython |
112133 | from dags.dag import concatenate_functions
from dags.dag import get_ancestors
__all__ = [
"concatenate_functions",
"get_ancestors",
]
| StarcoderdataPython |
3335791 | """
========================================
Robust Soft Learning Vector Quantization
========================================
This example shows the different glvq algorithms and how they project
different data sets. The data sets are chosen to show the strength of each
algorithm. Each plot shows for each data point w... | StarcoderdataPython |
1717347 | <filename>GUAP/generate_perturbation.py
#!/usr/bin/env python
# coding: utf-8
from __future__ import division
from __future__ import print_function
import os
import time
import argparse
import numpy as np
import math
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import... | StarcoderdataPython |
3252901 | # Example 2: Real threads
import thredo
def func(n, label):
total = 0
while n > 0:
total += n
n -= 1
if n % 10_000_000 == 0:
print(label, n)
return total
def main():
t1 = thredo.spawn(func, 60_000_000, 'thread-1')
t2 = thredo.spawn(func, 40_000_000, 'thread... | StarcoderdataPython |
164500 | <reponame>kjappelbaum/pymatgen<filename>pymatgen/command_line/tests/test_mcsqs_caller.py
import os
import unittest
from monty.os.path import which
from monty.serialization import loadfn
from pymatgen import Structure
from pymatgen.command_line.mcsqs_caller import run_mcsqs
from pymatgen.util.testing import PymatgenTe... | StarcoderdataPython |
3383795 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file is to query and download data from PubMed
@author: <NAME> @ Metis, 02/12/2021
"""
#%%
from pymed import PubMed
from util import save_as_pickle
from collections import defaultdict
#%%
pubmed = PubMed(tool="MyTool", email="")
query = ['((traumatic brain injur... | StarcoderdataPython |
117740 | <reponame>astamm/geomstats
"""Unit tests for the 3D heisenberg group in vector representation."""
import geomstats.backend as gs
import geomstats.tests
from geomstats.geometry.heisenberg import HeisenbergVectors
class TestHeisenbergVectors(geomstats.tests.TestCase):
def setup_method(self):
self.dimension... | StarcoderdataPython |
4824339 | <reponame>StrayRobots/stray
def transform_points(T, points):
R = T[:3, :3]
t = T[:3, 3]
return (R @ points[..., :, None])[..., :, 0] + t
| StarcoderdataPython |
144018 | import os
import sys
import hou
import struct
class pcache(object):
fileName = ""
fileType = 'a'
fileVersion = 1.0
propertyNames = []
propertyTypes = []
propertyData = bytearray()
itemcount = 0
itemstride = 0
defaultBindings = {
'P': 'position',
'N': 'normal',
... | StarcoderdataPython |
1623088 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 9 10:13:09 2021
@author: ruy
"""
from dataclasses import asdict
import pytest as pt
from gl_hsc_scantling.shortcut import StiffenerSection
from .exp_output import ExpStiffenerSection
def _get_stiffener_stiff_dict(section: StiffenerSection):
return {
"bend_s... | StarcoderdataPython |
3316901 | <reponame>albertonavaa/Cirq<filename>dev_tools/notebooks/utils.py
# Copyright 2021 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/... | StarcoderdataPython |
3339578 | from math import log, floor, sqrt
import numpy as np
import matplotlib.pyplot as plt
from fjlt import *
from Trigonomity import *
plt.style.use('ggplot')
def printKValues(e,n):
k1 = (log(n) * 4) / (((e**2)/2)-((e**3)/3)) # Simple proofOur paper.
k2 = 9/((((e**2))-(2*(e**3)/3)))* log(n) #
k3 = (e**-2)*log(n)
... | StarcoderdataPython |
130375 | <reponame>mikewolfli/django2-goflow<filename>goflow/graphics2/urls_admin.py
from django.urls import path
from goflow.graphics2 import views as goflow_graphics2_views
urlpatterns = [
path('processimage/<int:process_id>/pos_activity/', goflow_graphics2_views.pos_activity),
]
| StarcoderdataPython |
4828188 | <reponame>txya900619/Intern-Training<gh_stars>1-10
# Compute the derivative of the pReLU activation function.
import torch
from d2l import torch as d2l
def PReLU(x, a):
"""define PReLU(x)=max(x,0)+a*min(x,0)"""
constant_zero = torch.FloatTensor([0.0])
return torch.max(x, constant_zero) + (a * torch.min(x... | StarcoderdataPython |
1649297 | import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import (
cross_val_score,
train_test_split,
ShuffleSplit,
)
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score, recall_score
from sklearn.metrics import confusion_matrix
import ... | StarcoderdataPython |
1654511 | <gh_stars>0
# Copyright 2021 MosaicML. All Rights Reserved.
from __future__ import annotations
import argparse
import collections.abc
import logging
import os
from typing import TYPE_CHECKING, Dict, List, Sequence, Tuple, Union, cast
import yaml
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from yahp.... | StarcoderdataPython |
1749553 | import pytest
from uricomcuscuz.models import User, Problem, Submission
@pytest.mark.parametrize(('Model', 'id', 'expected_link'), (
(User, 1, '/judge/pt/profile/1?sort=Ranks.created&direction=desc'),
(Problem, 1, '/judge/pt/problems/view/1'),
))
def test_link(populate_db, Model, id, expected_link):
"""Te... | StarcoderdataPython |
3251890 | from quest.alltests.quest_forms_tests import *
from quest.alltests.quest_models_tests import *
from quest.alltests.quest_views_tests import *
| StarcoderdataPython |
65428 | <reponame>Priyansh2/LeetCode-Solutions
# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|),
# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)
# Space: O(|E| + |V|) = O(|E|)
import heapq
# dijkstra's algorithm
class Solution(object):
def minimumWeight(self, n, edges, src1, src2, d... | StarcoderdataPython |
3256286 | <gh_stars>1-10
import random
fdo=open('./textfile_r.dat','w')
fto=open('./textfile_st.dat','w')
sdo=""
sto=""
for index in range (10):
#state
#bank
tmp=bin(random.randint(0,7))[2:]
if len(tmp)<3:
for j in range(3-len(tmp)):
sto+="0";
sto+=tmp+'\n';
else:
sto+=(tmp+'\n')
tmp=bin(random.randint(0,1023))... | StarcoderdataPython |
1709024 | # -*- coding: utf-8 -*-
# Created By: <NAME>
# Created On: 2009-09-18
# Copyright 2010 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.har... | StarcoderdataPython |
3379604 | <reponame>natefduncan/flask-pyodide
import os
from flask import request
from app import init_app
from app.api.models import User
from app.utils.objects import Token
app = init_app()
def get_current_user():
token = request.cookies.get("token")
try:
user = User.query.get(Token.decode(token).get("id")... | StarcoderdataPython |
53782 | <reponame>darcyabjones/bioplotlib
""" Extension of matplotlib collections.
Classes for the efficient drawing of large collections of objects that
share most properties, e.g., a large number of line segments or
polygons.
The classes are not meant to be as flexible as their single element
counterparts (e.g., you may no... | StarcoderdataPython |
1681803 | <reponame>lcopland18/99-CapstoneProject-201930<filename>src/m2_laptop_code.py<gh_stars>0
"""
Capstone Project. Code to run on a LAPTOP (NOT the robot).
Displays the Graphical User Interface (GUI) and communicates with the robot.
Authors: Your professors (for the framework)
and <NAME>.
Spring term, 2018-2... | StarcoderdataPython |
4817208 | <gh_stars>1-10
from .context import src
from src.core import slice_list
def test_slice_list():
assert slice_list(range(1, 4), 2) == [[1, 2], [3]]
assert slice_list(range(1, 5), 2) == [[1, 2], [3, 4]]
assert slice_list(range(1, 7), 3) == [[1, 2], [3, 4], [5, 6]]
assert slice_list(range(1, 3), 1) == [[1... | StarcoderdataPython |
1606278 | import numpy as np
from scipy import stats
def create_data(N = 10):
a = np.random.randn(N) + 2 #mean = 2, var = 1
b = np.random.randn(N) #mean = 0, var = 1
return a, b
def variance(a,b):
var_a = a.var(ddof = 1) #Numpy uses the population (N) and not sample (N-1), thus pass ddof = 1
var_b = b.var... | StarcoderdataPython |
3342920 | import collections
import copy
import json
def parse_request(request):
"""
Parses JSON bodies safely.
"""
try:
body = json.loads(request.body.decode("utf-8"))
return body
except Exception:
return None
def stringify_keys(dictionary: dict):
"""
This helper function ... | StarcoderdataPython |
3378205 | <gh_stars>1-10
#!-*- coding:utf-8 -*-
#!/usr/bin/env python
#---------------------------------------------------
#規約違反を報告する
#copyright 2010-2012 ABARS all rights reserved.
#---------------------------------------------------
import os
import template_select
from google.appengine.ext import webapp
from google.appengi... | StarcoderdataPython |
1685959 | # Store all the valid replacements in a list and sort them desc. The apply each change on S.
class Solution:
def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
changes = []
for i in range(len(indexes)):
start = indexes[i]
... | StarcoderdataPython |
176631 | <reponame>Sean-Ker/data_patty_hunter<gh_stars>0
import operator as op
from functools import reduce
import random
import pickle
def ncr(n, r): # Code contributed by @dheerosaur
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer / denom
... | StarcoderdataPython |
1732226 | from fractions import Fraction as Q
import unittest
from quest.assembler import assemble
from quest.process import Process
from quest.register import Register
from quest.stdio import StandardStream
STDIN = StandardStream.STDIN.value
STDOUT = StandardStream.STDOUT.value
STDERR = StandardStream.STDERR.value
ECHO_SOURC... | StarcoderdataPython |
26119 | <filename>archive/lym_project/treeano-master/benchmarks/fractional_max_pooling.py
import numpy as np
import theano
import theano.tensor as T
import treeano.nodes as tn
from treeano.sandbox.nodes import fmp
fX = theano.config.floatX
# TODO change me
node = "fmp2"
compute_grad = True
if node == "mp":
n = tn.MaxPool... | StarcoderdataPython |
1633828 | #!/usr/bin/env python3
# coding: utf-8
from copy import deepcopy
from pathlib import Path
from cwl_inputs_parser.utils import Inputs, wf_location_to_inputs
from cwl_utils.parser.cwl_v1_2 import CommandInputArraySchema, InputArraySchema
from yaml import safe_load
from const import CONFORMANCE_TEST_PATH, CWL_UTILS_OBJ_... | StarcoderdataPython |
3332559 | import os
import cv2
import numpy as np
import tensorflow as tf
import utils
import time
class DMSC():
def __init__(self, sess, config):
self.config = config
self.sess = sess
self.batch_size = config['batch_size']
self.train_dir = config['train_dir']
self.D_size = config['d... | StarcoderdataPython |
1667959 | <gh_stars>0
#!/usr/bin/env python
import sys
import subprocess
import getopt
import time
client = "c"
server = "c"
def dotest(client_dir, server_dir):
server_args = [ "%s/server" % server_dir ]
client_args = [ "%s/client" % client_dir ]
server_proc = subprocess.Popen(server_args)
time.sleep(0.1)
... | StarcoderdataPython |
3312604 | <gh_stars>10-100
"""
Log video stream provided by OpenCV camera
"""
import cv2
from threading import Thread
class LogOpenCVCamera:
def __init__(self, config, bus):
self.input_thread = Thread(target=self.run_input, daemon=True)
self.bus = bus
bus.register('raw')
port = config.get... | StarcoderdataPython |
1699854 | <reponame>Kixiron/libc
#! /usr/bin/env python
#
# Copyright (c) 2004 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.