id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
4838306 | <reponame>zinsmatt/slambook2<gh_stars>0
from sympy import Symbol, exp, diff, simplify
a = Symbol('a')
b = Symbol('b')
c = Symbol('c')
x = Symbol('x')
y = Symbol('y')
F = (y - exp(a*x*x+b*x+c))**2/2
print(F)
print(diff(F, a))
print(diff(F, b))
print(diff(F, c))
print("\n")
print(diff(F, a, a))
print(diff(F, b, b))
pr... | StarcoderdataPython |
1704678 | <gh_stars>0
#
# @lc app=leetcode.cn id=69 lang=python3
#
# [69] sqrtx
#
None
# @lc code=end | StarcoderdataPython |
3235520 | <reponame>anubhab-code/Competitive-Programming
n = list(input())
l = len(n)
for i in range(l-1, 0, -1):
temp = 9-int(n[i])
if temp<int(n[i]):
n[i] = str(temp)
temp = 9-int(n[0])
if temp!=0 and temp<int(n[0]):
n[0] = str(temp)
print("".join(n)) | StarcoderdataPython |
194621 | import numpy as np
from controller import Controller
from wrappers import visualize
from collections import defaultdict
from math import pi
GRID_SIZE = 0.5
ROTATION_STEPS = 4
def move_position(position, rotation):
if rotation == 0:
return (position[0] + 1, position[1])
elif rotation == 1:
retu... | StarcoderdataPython |
1743873 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from dp_tornado.engine.helper import Helper as dpHelper
try:
from PIL import Image
except ImportError:
Image = None
try:
from PIL import ImageDraw
except ImportError:
ImageDraw = None
try:
from PIL import ImageOps
except ImportError... | StarcoderdataPython |
1753787 | import FWCore.ParameterSet.Config as cms
from Configuration.ProcessModifiers.gpu_cff import *
from Configuration.ProcessModifiers.gpuValidationEcal_cff import *
from Configuration.ProcessModifiers.gpuValidationHcal_cff import *
from Configuration.ProcessModifiers.gpuValidationPixel_cff import *
# This modifier chain ... | StarcoderdataPython |
1622539 | <filename>python/Load_and_Pickle_Scenario.py
import numpy as np
import pickle
import timeit
from copy import deepcopy
import sys
from Model_Manager.Link_Model_Manager import Link_Model_Manager_class
from Java_Connection import Java_Connection
from copy import copy
from Solvers.Frank_Wolfe_Solver_Static import construc... | StarcoderdataPython |
3372414 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import modules.update_data
import modules.update_domaine
| StarcoderdataPython |
3321498 | <filename>setup.py
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
readme = open(os.path.join(here, 'README.rst')).read()
requires = [
'pytest',
'six'
]
def get_version():
p = os.path.join(os.path.dirname(os.path.abspath(__file__)), "VERSION.txt")... | StarcoderdataPython |
93493 | <reponame>realnoobs/django-kepoin
import os
from celery import Celery
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
# Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings")
app = Celery("example")
# Read the configuration from the config file.
... | StarcoderdataPython |
55557 | <filename>app_python/common/db.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import common.env as env
class Db:
def __init__(self):
self.engine = create_engine('postgresql+psycopg2://{user}:{password}@{host}:{port}/{database}'.format(
user=env.POSTGRES_USER,
... | StarcoderdataPython |
155417 | import meetup.api
class MeetupUtils:
def __init__(self, api_key):
self.__client__ = meetup.api.Client(api_key)
def get_find_groups(self, places_filters, keyword_filters):
"""
Get groups from the meetup api based on the given filters and filter them by keywords
:param places_f... | StarcoderdataPython |
3290342 | <reponame>halk/recowise
from flask import Blueprint, request
from flask.ext import restful
from worker.event import process_event
event = Blueprint('event', __name__)
api = restful.Api(event)
# api
class Event(restful.Resource):
def post(self, subject):
process_event.delay(subject, request.get_json())
... | StarcoderdataPython |
3298845 | <gh_stars>0
from django.db import migrations
def set_implicit_connection_to_profile_service(apps, schema_editor):
Service = apps.get_model("services", "Service")
Service.objects.filter(is_profile_service=True).update(implicit_connection=True)
class Migration(migrations.Migration):
dependencies = [
... | StarcoderdataPython |
107778 | #!/usr/bin/python
from jinja2 import Template, Environment, FileSystemLoader
import json
import autopep8
import os
import re
import sys
def replaceSpecialChars(str):
return str.replace('-', '_').replace('.', '_').replace('+', 'plus')
def getModuleName(path, name):
return replaceSpecialChars(path.lower()) + "... | StarcoderdataPython |
1621097 | <gh_stars>0
#!/usr/bin/python
#
# 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... | StarcoderdataPython |
3219051 | # -*- coding: utf-8 -*-
from nose.plugins.attrib import attr
from unittest import TestCase
import os
class BookTestCase(TestCase):
@attr("skip")
def test_scaffold(self):
assert False
# create temp directory
directory = "../var/tests/book"
if not os.path.exists(directory):
... | StarcoderdataPython |
3252511 | class Solution(object):
def checkIfPangram(self, sentence):
for i in sentence:
a.append(i)
a = set(a)
if(len(a) == 26):
return True
else:
return False
"""
:type sentence: str
:rtype: bool... | StarcoderdataPython |
130542 | <reponame>a-tsen/hpq-django-project
from django.contrib import admin
from .models import Item
# Username: testing
# Password: <PASSWORD>
class ItemAdmin(admin.ModelAdmin):
list_display = ('item_name', 'item_type') # appears from Item model change page
list_filter = ['item_type'] # can filter by type of it... | StarcoderdataPython |
1792126 | <gh_stars>1-10
class LecturerDirectory:
def __init__(self, lecName, lecPhone, lecOffice, lecSubjects, lecStart):
self.name = lecName
self.phone = lecPhone
self.office = lecOffice
self.subjects = lecSubjects
self.startYear = lecStart
def changeName(self, newN... | StarcoderdataPython |
1719993 |
from model.project import Project
import random
def test_del_project(app, config):
app.session.ensure_login(username=config['webadmin']['username'], password=config['webadmin']['password'])
if len(app.soap.get_project_list()) == 0:
app.project.create(Project(name="Some project" + str(random.randrange... | StarcoderdataPython |
4814785 | <filename>scripts/run.py
import datetime
import fire
import logging
import pytz
from core.config import ConfigLoader
from core.logger import init_logger
from provider import GoogleAds, Facebook, TamagoRepeat
from writer import WriterBuilder
JST = pytz.timezone('Asia/Tokyo')
def main(start_date="", end_date="",
... | StarcoderdataPython |
1628983 | <filename>atlas_generator.py
import json
import math
import os
import shutil
from pathlib import Path
from typing import Optional, List, Tuple
from PIL import Image
ATLAS_WIDTH = 64
ATLAS_HEIGHT = 64
DEFAULT_TYPE_ID = 255
atlas = Image.new("RGBA", (ATLAS_WIDTH * 16 * 2, ATLAS_HEIGHT * 16 * 2))
texture_count = 0
re... | StarcoderdataPython |
3380915 | <gh_stars>10-100
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import crypt
import random
import string
from ansible.module_utils.basic import AnsibleModule
def gen_pass(size=16, chars=string.ascii_letters + string.digits):
'''G... | StarcoderdataPython |
92542 | <filename>whdenovo/validate_real.py
from collections import defaultdict
import sys, os, subprocess
def readBothFile(allreads, tagTXT):
partitioned = open(allreads, 'r').read().split('\n')[:-1]
readnameSet1 = set()
for read in partitioned:
readnameSet1.add(read.split()[0])
tag = open(tagTXT, 'r').read().split(... | StarcoderdataPython |
3340325 | <reponame>perf-suite/tools-taurus
from abc import abstractmethod
from collections import namedtuple
from bzt.engine import Aggregator
from bzt.utils import BetterDict, iteritems
class FunctionalAggregator(Aggregator):
"""
:type listeners: list[FunctionalAggregatorListener]
:type underlings: list[Function... | StarcoderdataPython |
192496 | from app import database
from app.database import Database
import datetime
from configparser import ConfigParser
config = ConfigParser()
def rep():
#Get delivery time from config
config.read("app/config.ini")
del_time = datetime.timedelta(days=int(config.get("Settings", "del_time")))
today = datetime.... | StarcoderdataPython |
3255389 | # -*- coding: utf-8 -*-
"""
1506. Find Root of N-Ary Tree
You are given all the nodes of an N-ary tree as an array of Node objects, where each node has a unique value.
Return the root of the N-ary tree.
Custom testing:
An N-ary tree can be serialized as represented in its level order traversal where each group of c... | StarcoderdataPython |
3237347 | import unittest
from ModularChess.controller.Player import Player
from ModularChess.game_modes.Classical import Classical
from ModularChess.movements.BasicMovement import BasicMovement
from ModularChess.movements.EnPassant import EnPassant
from ModularChess.movements.Movement import MovementData
from ModularChess.piec... | StarcoderdataPython |
3382430 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import os
from unittest import TestCase, main
from recc.package.package_utils import get_module_directory, list_submodule_names
from recc import lamda_builtin
class PackageUtilsTestCase(TestCase):
def test_get_module_directory(self):
self.assertTrue(os.path.isdir(ge... | StarcoderdataPython |
4840834 | def find_top(state, curr):
for pair in state:
#looking for the pair where the specified container is on the
#top and returns said pair
if pair[0] == curr:
return pair
return 0
def update(plan, state):
#looping through every move in plan
for move in plan:
#che... | StarcoderdataPython |
82085 | import os
from urllib.parse import urlparse
from .base import *
DEBUG = False
SECRET_KEY = os.environ['SECRET_KEY']
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'stura-md.de,www.stura-md.de').split(',')
# Application definition
MIDDLEWARE += [
'whitenoise.middleware.WhiteNoiseMiddleware',
]
# Database
... | StarcoderdataPython |
4823229 | <gh_stars>0
from pyspark.sql import SparkSession
from util.TypeConversion import xmlToCsv
def init_spark():
spark = SparkSession.builder.appName("XMLReader").getOrCreate()
sc = spark.sparkContext
return spark, sc
def main():
spark, sc = init_spark()
xml_file = "../resources/itemsales.xml"
ou... | StarcoderdataPython |
1781390 | #
# Copyright (C) 2019 The Android Open Source Project
#
# 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 la... | StarcoderdataPython |
1621824 | # package to encrypt file with AES standard
import pyAesCrypt
# glob is a filename globbing utility, needed to change the file names with regex
# FUNCTIONS
# escape(pathname) - escape all special characters
# glob(pathname, *, recursive=False) - returns a list of path matching a pathname pattern
import glob
# os - ru... | StarcoderdataPython |
138462 | <reponame>pyarnold/wot
"""MapReduce implementation of the Sequitur algorithm.
Right now this is really just using mapreduce as a way of scalable batch processing. A true massively-parallel mapreduce
reimplementation could lead to some crazy good performance if done right. Sequitur is a recursive algorithm, but I think... | StarcoderdataPython |
3387507 | <reponame>catherinec98/lucabot
#!/usr/bin/env python
# coding: utf-8
import random
import time
import sys
import tweepy
#import credentials
#import urllib.request
import copy
from os import environ
#import gc
'''
CONSUMER_KEY = credentials.CONSUMER_KEY
CONSUMER_SECRET = credentials.CONSUMER_SECRET
ACCESS_KEY = credent... | StarcoderdataPython |
97137 | <reponame>sdpython/mlprodic
"""
@file
@brief Inspired from skl2onnx, handles two backends.
"""
from pyquickhelper.pycode import is_travis_or_appveyor
from .utils_backend_common_compare import compare_runtime_session
from ...tools.ort_wrapper import (
InferenceSession, GraphOptimizationLevel, SessionOptions)
def _... | StarcoderdataPython |
198313 | <filename>src/nasa/conf/dev_settings.py
from nasa.conf.global_settings import *
SECRET_KEY = 'dev'
DEBUG = TEMPLATE_DEBUG = True
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.back... | StarcoderdataPython |
4811548 | from .abc import ABCStateDispenser
from .default import DefaultStateDispenser
| StarcoderdataPython |
3301589 | <reponame>BCD65/electricityLoadForecasting
URL_TRANSCODING = {
'France' : '',
'Auvergne-Rhône-Alpes' : 'Auvergne-Rh%C3%B4ne-Alpes',
'Bourgogne-Franche-Comté' : 'Bourgogne-Franche-Comt%C3%A9',
}
XLS_TRANSCODING = {
... | StarcoderdataPython |
30555 | #!/usr/bin/env python
import os
os.environ['POMAGMA_LOG_LEVEL'] = '3'
from pomagma.compiler.util import temp_memoize # isort:skip
from pomagma.reducer import bohm # isort:skip
print('Example 1.')
with temp_memoize():
bohm.sexpr_simplify('(ABS (ABS (1 0 (1 0))) (ABS (ABS (1 (0 0)))))')
print('Example 2.')
w... | StarcoderdataPython |
4825901 |
#########################################################
##
## Prepare command line to run a rendering processing from *.bat
##
## Github repo - https://github.com/Neill3d/MoPlugs
## Licensed under BSD 3-clause
## https://github.com/Neill3d/MoPlugs/blob/master/LICENSE
##
## Author <NAME> (Neill3d) 2017
## e-mail to... | StarcoderdataPython |
77355 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 4 10:59:17 2021
Machine class
@author: marynaw
"""
import matplotlib.artist as ma
import matplotlib.pyplot as plt
import random
import dtwin.dttypes as dtTypes
import simpy
import kafka
import datetime
import json
import dtwin.dtpart as dtPart
import environ... | StarcoderdataPython |
6183 | <reponame>starofrainnight/ncstyler<gh_stars>0
#!/usr/bin/env python
import argparse
import CppHeaderParser
import re
import sys
import yaml
import copy
import six
import os.path
import traceback
class CppDefine(dict):
def __init__(self):
self["name"] = None
self["parameters"] = []
self["li... | StarcoderdataPython |
4824100 | #!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License")... | StarcoderdataPython |
3226100 | from copy import deepcopy
from collections import defaultdict
from turtle import clone
import networkx as nx
import numpy as np
from sklearn.linear_model import LinearRegression as LR
from ylearn.utils._common import check_cols
from ylearn.estimator_model.double_ml import DML4CATE
from .utils import (check_nodes, ch... | StarcoderdataPython |
130207 | <filename>pycaishen/user_programs/Bloomberg/Bloomberg_all_symbols.py<gh_stars>1-10
from pycaishen.pycaishenstorage import PycaishenStorage
from pycaishen.user_programs.user_programs_settings import Configurer
bloomberg_references = [Configurer.LIB_INDEX_COMPOSITION,Configurer.LIB_BLOOMBERG_OPEN_FIGI]
# bloomberg_re... | StarcoderdataPython |
3253522 | from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... | StarcoderdataPython |
3341749 | """Vigenère Cipher Dictionary Hacker
Implements a function that can hack a Vigenère cipher encrypted message using a dictionary.
Attributes:
DICTIONARY_FILE (str): String with absolute location of dictionary.txt file.
Note:
* https://www.nostarch.com/crackingcodes/ (BSD Licensed)
"""
from pythontutorials.b... | StarcoderdataPython |
72029 | # -*- coding: utf-8 -*-
"""Command line scripts to launch a `MatdynCalculation` for testing and demonstration purposes."""
from __future__ import absolute_import
from aiida.cmdline.params import options, types
from aiida.cmdline.utils import decorators
from ..utils import launch
from ..utils import options as options... | StarcoderdataPython |
1753058 | '''
Created on Jun 14, 2016
@author: <NAME>
@contact: <EMAIL>
@copyright: You are free to use, change, or redistribute this code in any
way you want for non-commercial purposes.
'''
import os.path as osp
from nn_saliency.src.mesh import Mesh
import nn_saliency.src.nn_io as nn_io
class_names = ['ba... | StarcoderdataPython |
3239021 | <filename>functest/opnfv_test/vnf/openbaton/openbaton.py
#!/usr/bin/env python
# Copyright (c) 2016 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
... | StarcoderdataPython |
4814053 | from ztk.api.base import RestApi
class ZtkAlipayAgentPayRequest(RestApi):
'''__init__(self, password, alipay_account, alipay_name, money, remark, domain='api.zhetaoke.com', port=10001)
password 付安全秘钥代付设置
alipay_account 支付宝账号
alipay_name 支付宝真实姓名
money 代付金额,单位:元,最少0.1元/笔,只... | StarcoderdataPython |
183115 | <reponame>svaisakh/captioner
from multiprocessing import cpu_count as __num_cores
# Extractor
architecture = 'resnet34'
image_shape = 224
extractor_batch_size = 16
num_workers = 8
num_workers = min(num_workers, __num_cores())
# Captions
vocab_size = 10000
caption_idx = 0
prune_batch_size = 8
# Model
rnn_type = 'LST... | StarcoderdataPython |
3396172 | from model.contact import Contact
from random import randrange
import re
def test_contact_compare_home_page_with_db_data(app, db):
contact = Contact(firstname="Anna", lastname="Latusek", address="Klonowa, Katowice", home="555666",
mobile="333444555", work="tester", email="<EMAIL>", email2="<... | StarcoderdataPython |
4808205 | #-----------------------------------------------------------------------------
# Copyright (c) 2013-2021, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt... | StarcoderdataPython |
167245 | """String formating language samples."""
import collections
import locale
# category: exemples
def basic_formating():
"""Simple replacement..."""
return "{}".format('infinite')
def deep_formating():
"""Mix of many formating possibilities."""
return "{value.__class__.__bases__[0].__name__!r}".fo... | StarcoderdataPython |
117873 | from jsonobject import (BooleanProperty, DefaultProperty, IntegerProperty,
JsonObject, ListProperty, StringProperty)
class TlsResult(JsonObject):
ips_scanned = IntegerProperty()
protocols = ListProperty(StringProperty())
hsts_present = BooleanProperty()
trusted = BooleanPropert... | StarcoderdataPython |
1710557 | # -*- coding: utf-8 -*-
"""Sources should have a single staging model.
"""
from typing import List, Tuple
from olivertwist.manifest import Manifest, Node
from olivertwist.ruleengine.rule import rule
from olivertwist.rules.utils import partition
@rule(
id="single-staging-model-per-source",
name="Sources can... | StarcoderdataPython |
165507 | <reponame>arnaud-fontaine/Zope
from zope.interface import Attribute
from zope.interface import Interface
#############################################################################
# Publication events
# These are events notified in 'ZPublisher.Publish.publish'.
class IPubEvent(Interface):
'''Base class for ... | StarcoderdataPython |
1621507 | <reponame>CodedLadiesInnovateTech/-python-challenge-solutions<gh_stars>1-10
#program to count number of substrings with same first and last characters of a given string.
def no_of_substring_with_equalEnds(str1):
result = 0;
n = len(str1);
for i in range(n):
for j in range(i, n):
if (str1[i] == str1[j]):
... | StarcoderdataPython |
4816262 | #!/usr/bin/python
import random
def dictionary():
z = []
for i in range(10):
z.append(chr(48+i))
for i in range(26):
z.append(chr(97+i))
return z
print("".join(random.choices(dictionary(),k=8)))
| StarcoderdataPython |
3205477 | # Geodict
# Copyright (C) 2010 <NAME> <<EMAIL>>
#
# 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.
#
# Thi... | StarcoderdataPython |
3263106 | <reponame>RenskeW/cwltool<filename>tests/test_input_deps.py
"""Tests for --print-inputs-deps."""
import json
import os
from io import StringIO
from pathlib import Path
from cwltool.main import main
from cwltool.process import CWL_IANA
from .util import get_data
def test_input_deps() -> None:
"""Basic test of -... | StarcoderdataPython |
10888 | import unittest
import pandas as pd
import git
import os
from dfstools import get_dataset_dtypes
from dfstools import find_related_cols_by_name
from dfstools import find_related_cols_by_content
from dfstools import find_parent_child_relationships
from dfstools import pecan_cookies_load_data
class RelationshipTools(un... | StarcoderdataPython |
8080 | import datetime
def iso_extract_info(string):
"""
Will get all of the info and return it as an array
:param string: ISO formatted string that will be used for extraction
:return: array [year, month, day, military_time_hour, minutes, hours]
:note: every item is an int except for minutes
... | StarcoderdataPython |
1668450 | # All tests for R4 - sell go here | StarcoderdataPython |
1683803 | <filename>Chance/prob.py
coin_flipped = ["🪙 heads!", "🪙 tails!"]
dice_bag = ["⚀","⚁","⚂","⚃","⚄","⚅"]
| StarcoderdataPython |
14504 | <gh_stars>1-10
import warnings
from django.test import SimpleTestCase
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.safestring import mark_safe
from ..utils import render, setup
class UnorderedListTests(SimpleTestCase):
@setup({'unordered_list01': '{{ a|unordered_list }}'})
... | StarcoderdataPython |
39574 | <reponame>84KaliPleXon3/bni-api
import setuptools
import re
with open('README.md', 'r') as fh:
long_description = fh.read()
def get_version():
with open('bni_api/__init__.py') as f:
v = re.findall(r'__version__ = \'(.+?)\'', f.read())[0]
return v
setuptools.setup(
name="bni_api",
version=... | StarcoderdataPython |
1633285 | <reponame>VCMason/PyGenToolbox<filename>src/pygentoolbox/FilterVCF.py
def filter_variants(variants):
# variants is a list of lists
keepvars = []
for line in variants:
# line is list
if line[-3].split(';')[0] == 'INDEL':
# process indel variants
if (line[-1].spl... | StarcoderdataPython |
1707410 | <reponame>chenjj2/colab_gan_playground
from torch import nn
class Discriminator(nn.Module):
def __init__(self, **kwargs):
super().__init__()
self.loss_function = kwargs.get("loss_function", nn.BCELoss())
self._optimizer = None
self.model = nn.Sequential(
nn.Linear(2, ... | StarcoderdataPython |
3358992 | from firedrake import *
from inner import solve_inner
from injection import injection
from petsc4py import PETSc
from termcolor import colored
import matplotlib.pyplot as plt
import numpy as np
import pdb
op2.init(log_level="WARNING")
parameters['assembly_cache']['enabled'] = False
p = pdb.set_trace
class Simulation:
... | StarcoderdataPython |
1607930 | from __future__ import annotations
import copy
from enum import IntEnum
from generic_search import bfs, nodeToPath
from intcode import IntCode
from typing import Dict, List, NamedTuple, Set
class Direction(IntEnum):
NORTH = 1
SOUTH = 2
WEST = 3
EAST = 4
class Point(NamedTuple):
x: int
y: int... | StarcoderdataPython |
1682291 | <filename>examples/example.py
"""
This is an example module to test textpy
"""
import textpy
print(textpy.words('hello World. This is a great idea.'))
print(textpy.sentences('hello World.'))
print(textpy.numbers('hello World123 Hello World 345'))
print(textpy.telephone('Hello World My number is 319-378-8183'))
print(... | StarcoderdataPython |
180886 | <filename>telecom_churn.py
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from collections import Counter
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import classificati... | StarcoderdataPython |
197563 | <filename>train.py
import os
import random
import time
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from lib.models import get_model_class
from util.datasets import load_dataset
from util.environments import load_environment
from util.logging import LogEntry
def run_e... | StarcoderdataPython |
3344615 | <gh_stars>10-100
from problog.engine import DefaultEngine
from problog.logic import *
from problog.program import PrologString
pl = PrologString("""
mother_child(trude, sally).
father_child(tom, sally).
father_child(tom, erica).
father_child(mike, tom).
sibling(X, Y) :- parent_child(Z, X), parent_child(Z, Y).
pare... | StarcoderdataPython |
1755166 | import sys
import numpy as np
import torch
import torch.nn as nn
from torch.nn import init
import torch.optim as optim
import math
import random
import os
import csv
from pathlib import Path
from model import model
import time
from tqdm import tqdm
TESTLOSS = False
SAVEMODEL = False
def read_input(task... | StarcoderdataPython |
4818626 | from django.db import models
# Create your models here.
class Xray(models.Model):
scan = models.ImageField(upload_to = 'images/') | StarcoderdataPython |
87711 | from dropout import dropout
import math
import theano
import theano.tensor as T
import util
class ConcatWithSoftmax(object):
def __init__(self, inp, n_labels, n_hidden_previous, update_fn,
training=None, keep_prob=None):
if type(inp) == list:
self.input = T.concatenate(inp)
... | StarcoderdataPython |
1689971 | <reponame>e-esteva/cipher
from . import deepbind
| StarcoderdataPython |
3265433 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014+ Type Network
#
# T N B I T S
# No distribution without permission.
#
# ---------------------------------------------------------------------------... | StarcoderdataPython |
3340291 | <gh_stars>10-100
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# vim: fenc=utf-8
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
#
"""
File name: test.py
Author: dhilipsiva <<EMAIL>>
Date created: 2017-01-08
"""
DOMAINS = ['test.com']
| StarcoderdataPython |
4815657 | <reponame>benSepanski/loopy
from pymbolic.primitives import Variable
from loopy.symbolic import (RuleAwareIdentityMapper, SubstitutionRuleMappingContext)
from loopy.kernel.data import ValueArg
from loopy.transform.iname import remove_unused_inames
class ScalarChanger(RuleAwareIdentityMapper):
def __init__(self, r... | StarcoderdataPython |
1760656 | <filename>utils/auth.py
from utils.extentions import db
from functools import wraps
from flask import session, redirect
import flask
from config import LOGIN_URL, AUTH_USER_MODEL
import importlib
def login(user):
session['login'] = user.id
def logout():
session.clear()
def initialize_user_model():
app... | StarcoderdataPython |
1605715 | import jinja2
import os
import base
import site_db
import csv
import geopy
import logging
from geopy import geocoders
import metaphone
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
template = jinja_environment.get_template('import.html')
from google.appengine.ext i... | StarcoderdataPython |
3348295 | <filename>v1/utils/__init__.py<gh_stars>0
import logging
import sys
from logging.handlers import RotatingFileHandler
from .future import SafeFuture
from .terminal import Terminal
from .routine import create_task, findNumeric, loadJsonConfig, numPattern, parseNumeric
# -------------------------------------------------... | StarcoderdataPython |
3273772 | # -*- coding: utf-8 -*-
"""
Utility functions needed by the DNSDB module
"""
from dateutil.parser import parse
def build_uri(options):
"""
Build URI for DNSDB API query
:param options: Dictionary
:return: String
"""
path = build_path(options)
uri = build_parameters(options, path)
r... | StarcoderdataPython |
29196 | <reponame>ace6807/spec-data-validation-pattern
from dataclasses import dataclass
from . import Spec
from dto.person import PersonDTO
@dataclass
class HasNameSpec(Spec):
def passes(self, candidate: PersonDTO) -> bool:
return candidate.name is not None and candidate.name != ""
@dataclass
class HasAgeSpec(... | StarcoderdataPython |
123126 | r"""
Finite dimensional Hopf algebras with basis
"""
#*****************************************************************************
# Copyright (C) 2008 <NAME> (CNRS) <<EMAIL>>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#********************... | StarcoderdataPython |
1734350 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
TESTS_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = [
"django.contrib.sessions",
"django.contrib.auth",
"django.contrib.contenttyp... | StarcoderdataPython |
127759 | <filename>pypahdb/decomposer.py<gh_stars>1-10
#!/usr/bin/env python3
"""decomposer.py
Subclass of DecomposerBase for writting results to disk.
This file is part of pypahdb - see the module docs for more
information.
"""
import copy
import sys
from datetime import datetime, timezone
import matplotlib.gridspec as gri... | StarcoderdataPython |
3364011 | from __future__ import print_function
import RPi.GPIO as io
io.setmode(io.BCM)
import time
# FIXME: enable PWM
class Wheel():
def __init__(self, in1, in2):
self.in1 = in1
self.in2 = in2
def setup(self):
io.setup(self.in1, io.OUT)
io.setup(self.in2, io.OUT)
# motor1 = io.PWM(4,100)
# motor1.start(0)
#... | StarcoderdataPython |
4823674 | <reponame>keenan-burnett/radar_to_lidar_calib<filename>calibrate.py
# import sys
# sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
import os
import os.path as osp
import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.ndimage import shift
from features import ... | StarcoderdataPython |
1623226 | <gh_stars>0
import math
DATASET = 10
if DATASET == 0:
DATA = '13-exemple.txt'
elif DATASET == 1:
DATA = '13-exemple2.txt'
elif DATASET == 2:
DATA = '13-exemple3.txt'
elif DATASET == 3:
DATA = '13-exemple4.txt'
BORNEMIN = 1000000000
else:
DATA = '13.txt'
BORNEMIN = 1000000000... | StarcoderdataPython |
1782018 | __all__ = []
from .targetClass import *
__all__ += targetClass.__all__ | StarcoderdataPython |
1621504 | <gh_stars>1-10
"""
Script to disable "default" text tracks in videos.
"""
from mackee import main, get_cms
#===========================================
# callback to disable all default tracks
#===========================================
def disable_tt(video: dict):
"""
This will find text tracks wit... | StarcoderdataPython |
1666819 | import numpy as np
from ...utilities import get_num_atom_ids, normalize_ids
from .utilities import get_maximum_diameter
def test_get_maximum_diameter(case_data, get_atom_ids):
"""
Test :meth:`.Molecule.get_maximum_diameter`.
Parameters
----------
case_data : :class:`.CaseData`
A test cas... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.