id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
9741590 | <filename>src/genie/libs/parser/iosxe/tests/ShowIpNatTranslations/cli/equal/golden_output_1_expected.py
expected_output = {
"vrf": {
"default": {
"index": {
1: {
"inside_global": "10.1.7.2",
"inside_local": "192.168.1.95",
... | StarcoderdataPython |
11295014 | # code from Learning Card 08 - Rainbow HAT
# import the rainbowhat and signal modules
import rainbowhat
import signal
# this section links a press on button A
# to what to do when it happens
@rainbowhat.touch.A.press()
def touch_a(channel):
rainbowhat.lights.rgb(1, 0, 0)
# this section links a letting go of any... | StarcoderdataPython |
3260783 | import unittest
import qgate
import numpy as np
if hasattr(qgate.simulator, 'cudaruntime') :
class TestMemstore(unittest.TestCase) :
def set_mgpu_preference(self) :
# max chunk size, 2 MB.
max_po2idx_per_chunk = 21
# device memory per memstore
memory_store_... | StarcoderdataPython |
6518220 | <filename>program/audio_command.py
#!/usr/bin/env python
from robot_cmd_ros import *
begin()
bip()
wait()
run = True
while run:
a = asr();
if (a!=''):
print a
if ('avanti' in a):
forward();
elif ('dietro' in a):
backward();
elif ('sinistra' in a):
left();
... | StarcoderdataPython |
5090565 | <reponame>prachetos/goibibo-hackathon2016
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='CheckInPhotoDB',
... | StarcoderdataPython |
4829881 | <reponame>KyleKing/dash_charts
"""Example Bulma layout.
See documentation on Bulma layouts: https://bulma.io/documentation/layout/tiles/
"""
import dash_html_components as html
import plotly.express as px
from implements import implements
from dash_charts.utils_app import STATIC_URLS, AppBase, AppInterface
from das... | StarcoderdataPython |
8182630 | # Za pomocą funkcji isinstance() oraz issubclass()
# sprawdź wynik dla instancji obiektu Pracownik oraz Menadzer
# dla klas Osoba, Pracownik i Manadzer.
class Osoba:
def __init__(self, imie, nazwisko):
self.imie = imie
self.nazwisko = nazwisko
def przedstaw_sie(self):
return ... | StarcoderdataPython |
3348795 | # -*- coding: utf-8 -*-
import math
# 素数
num = int(input("Enter the number "))
for i in range(2, num):
# 怎么优化?
if num % i == 0:
print("The number is not a prime")
break
else:
print("The number is a prime")
for i in range(2, int(math.sqrt(num)) + 1):
# 怎么优化?
# 只选择素数来检验
if num ... | StarcoderdataPython |
186005 | import json
from pathlib import Path
import pytest
from cb_backend.eye.models import EventSessionStatus
@pytest.fixture(scope="module")
def load_schemas():
schemas = []
for file_name in ["fixtures/schema.json", "fixtures/schema_2.json"]:
fixture_json = open(Path(__file__).parent / file_name, "r")
... | StarcoderdataPython |
3483121 | <reponame>jehboyes/finance_manager
"""Luminate commercial income table"""
from finance_manager.database.replaceable import ReplaceableObject as o
sql = f"""
SELECT c.directorate_id, s.acad_year, s.set_cat_id, c.costc + ' ' + x.description as description, x.amount
FROM
(
--Courses
SELECT set_id, course_name as desc... | StarcoderdataPython |
4909650 | <reponame>michaelberks/madym_python
'''
Module for working with the active uptake and efflux model (AUEM). This has
a bi-exponential IRF, and uses the dibem model to compute a forward model.
All times are assumed to be in minutes.
The AIF must be a QbiPy AIF object (see dce_aif). However if you have a set of AIF valu... | StarcoderdataPython |
1759367 | __copyright__ = """\
(c). Copyright 2008-2020, Vyper Logix Corp., All Rights Reserved.
Published under Creative Commons License
(http://creativecommons.org/licenses/by-nc/3.0/)
restricted to non-commercial educational use only.,
http://www.VyperLogix.com for details
THE AUTHOR VYPER LOGIX CORP DISCLAIMS ALL WARRA... | StarcoderdataPython |
399239 | import chainer.functions.pooling as P
import numpy as np
from helpers import calculate_cost
def test_max_pooling():
x = np.random.randn(1, 3, 100, 100).astype(np.float32)
f = P.max_pooling_2d.MaxPooling2D(np.int64(2), np.int64(2),
np.int64(0), cover_all=True)
flops, ... | StarcoderdataPython |
1645113 | <reponame>crzdg/acconeer-python-exploration<filename>src/acconeer/exptool/clients/base.py
import abc
import logging
from distutils.version import StrictVersion
from acconeer.exptool import SDK_VERSION, modes
from acconeer.exptool.structs import configbase
log = logging.getLogger(__name__)
class BaseClient(abc.ABC)... | StarcoderdataPython |
5131476 | <gh_stars>10-100
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('powerdns', '0033_auto_20161114_1442'),
]
operations = [
migrations.AddField(
model_name='domain... | StarcoderdataPython |
3486739 | import json, boto3, base64
def getpath(p, env=None):
p = p.strip('/?')
if env and env.get('data_root'):
p = p[len(env['data_root']):] if p.startswith(env['data_root']) else p
p = p[:-len('.json')] if p.endswith('.json') else p
return p.strip('/').split('/')
def get_env_context(event, context):... | StarcoderdataPython |
4870679 | from .injection import inject_db
from .markers import DBSessionInTransactionMarker
__all__ = [
'inject_db',
'DBSessionInTransactionMarker'
]
| StarcoderdataPython |
1865350 | <filename>test.py<gh_stars>1-10
from util import get_args, detect_with_thresholding, mask_to_detections
from network import *
from util import *
from datasets import VideoDataset
from torchvision import transforms
import torch.backends.cudnn as cudnn
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"
def nms(proposal... | StarcoderdataPython |
11259896 | <filename>problems/statistics10binomialdistribution2/submissions/accepted/stefan.py<gh_stars>1-10
#!/usr/bin/env python3
#Author: <NAME>
from math import factorial
def choose(n, k):
return factorial(n)/factorial(k)/factorial(n-k)
def binom(n, k, p):
return choose(n, k)*(p**k)*((1-p)**(n-k))
if __name__ == ... | StarcoderdataPython |
3527636 | <filename>extra_apps/DjangoUeditor/urls.py
# coding:utf-8
from django import VERSION
from .widgets import UEditorWidget, AdminUEditorWidget
from .views import get_ueditor_controller
from django.urls import path
urlpatterns = [
path('controller/', get_ueditor_controller),
]
| StarcoderdataPython |
1707528 | import os
from flask import Flask
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_migrate import Migrate
from flask_wtf.csrf import CSRFProtect
from flask_cors import CORS
from flask_jwt_extended import JWTManager
app = Flask(__name__)
csrf = CSRFProtect(... | StarcoderdataPython |
6536799 | <filename>test/issue_94_111_154.py
import time
import RPi.GPIO as GPIO
LED_PIN = 12
def issue_154():
# fails with led off at around 400
count = 0
pinRef = GPIO.PWM(LED_PIN,50) # create new PWM instance
while True:
pinRef.start(10) # update PWM value
time.sleep(0.05)
pinRef.stop... | StarcoderdataPython |
3446847 | <reponame>redst4r/arboreto
'''
File created to address the reviewer's comment: how many trees were used
'''
import pandas as pd
import time
import sys
from arboreto.utils import load_tf_names
from arboreto.algo import *
from distributed import Client
if __name__ == '__main__':
ex_path = sys.argv[1]
tf_path ... | StarcoderdataPython |
6634125 | <reponame>e2jk/syncboom
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Running the tests:
# $ python3 -m unittest discover --start-directory ./tests/
# Checking the coverage of the tests:
# $ coverage run --include=./*.py --omit=tests/* -m unittest discover && \
# rm -rf html_dev/coverage && coverage html --directo... | StarcoderdataPython |
6567341 | <filename>main.py
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
messages = dict()
@app.route("/")
def index():
return render_template("index.html")
@app.route('/message', methods=['POST'])
def update_message():
content = request.get_json()
print(content)
messages[... | StarcoderdataPython |
3382748 | <gh_stars>1-10
import re
import requests
from bs4 import BeautifulSoup
class Tracker:
def __init__( self ):
self.url = 'https://www.worldometers.info/coronavirus/?utm_campaign=homeAdvegas1%3F'
def maincounter( self ):
r = requests.get(self.url)
if r.status_code == 200:
r = r.t... | StarcoderdataPython |
345408 | from django.db import models
from django.db.models import Q
from rest_framework import serializers
from iaso.api.common import TimestampField
from iaso.models import OrgUnit, OrgUnitType, Group
class TimestampSerializerMixin:
"""This Mixin override the serialization of the DateTime field to timestamp
instead... | StarcoderdataPython |
11243309 | <reponame>kanihal/CS631_pg_semantic_search
from gensim.utils import smart_open, simple_preprocess
from gensim.corpora.wikicorpus import _extract_pages, filter_wiki
from gensim.parsing.preprocessing import STOPWORDS
import gensim
import pandas as pd
import numpy as np
def tokenize(text):
try:
t=[token for ... | StarcoderdataPython |
11262867 | <reponame>Common-Tool/flare-fakenet-ng
# Diverter for Windows implemented using WinDivert library
import logging
from pydivert.windivert import *
from pydivert.enum import Direction, Defaults
import socket
import os
import dpkt
import time
import threading
import platform
from winutil import *
import subproces... | StarcoderdataPython |
5112276 | import pytest
import os
import glob
from subprocess import call
from snips.parser import parse
from snips.ast import Snippet, parse_snippet_body
snippets = 'https://github.com/honza/vim-snippets.git'
@pytest.fixture(scope='module')
def snippets_dir(current_dir):
d = os.path.join(current_dir, 'data', 'vim-snippe... | StarcoderdataPython |
3340155 | import io
from CommonServerPython import *
import CortexXDRCloudProviderWidget
import pytest
def util_load_json(path):
with io.open(path, mode='r', encoding='utf-8') as f:
return json.loads(f.read())
@pytest.mark.parametrize('incident_data, expected_result', [
(util_load_json('test_data/incident_dat... | StarcoderdataPython |
9632875 | <gh_stars>0
"""List of common fit functions."""
import numpy as np
from eddington.exceptions import FitFunctionLoadError
from eddington.fit_function_class import fit_function
@fit_function(
n=2,
syntax="a[0] + a[1] * x",
x_derivative=lambda a, x: np.full(shape=x.shape, fill_value=a[1]),
a_derivative=... | StarcoderdataPython |
3526709 | <reponame>ithaaswin/TeachersPetBot<gh_stars>0
import sqlite3
from sqlite3 import Error
import os
CON = None
def connect():
''' connect program to database file db.sqlite '''
global CON
db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'db.sqlite')
print(db_path)
try:
... | StarcoderdataPython |
6542789 | <filename>DbUtil.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import mysql.connector
from mysql.connector import errorcode
def close_db(cursor, cnx):
cursor.close()
cnx.close()
def open_db():
config = {
'user': 'root',
'password': '<PASSWORD>',
'host': '127.0.0.1',
'data... | StarcoderdataPython |
4926524 | <gh_stars>10-100
#!/usr/bin/env python
# encoding: utf-8
import mock
from unittest import TestCase
from ycyc.frameworks.events import base
class TestEvent(TestCase):
def test_event(self):
event = base.Event()
mock_callback1 = event.register(mock.MagicMock(side_effect=ValueError))
mock_... | StarcoderdataPython |
48160 | <gh_stars>1-10
import json
from temapi.commons.paths import OUTPUTS_DIR
class Loader:
file = None
def __init__(self):
assert self.file is not None
_file = OUTPUTS_DIR / self.file
with _file.open() as f:
data = json.load(f)
self.setup(data)
def setup(self, ... | StarcoderdataPython |
4805748 | """
Problem Statement
We are given an array containing ‘n’ objects. Each object, when created, was assigned a unique number from 1 to ‘n’
based on their creation sequence. This means that the object with sequence number ‘3’ was created just before the
object with sequence number ‘4’.
Write a function t... | StarcoderdataPython |
1940542 | <gh_stars>0
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | StarcoderdataPython |
6584956 | <gh_stars>1-10
"""
Pylibui test suite.
"""
from pylibui.controls import ProgressBar
from tests.utils import WindowTestCase
class ProgressBarTest(WindowTestCase):
def setUp(self):
super().setUp()
self.progressbar = ProgressBar()
def test_value_initial_value(self):
"""Tests the progr... | StarcoderdataPython |
11210462 | <gh_stars>0
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_sc... | StarcoderdataPython |
3459569 | <filename>pensa/dimensionality/pca.py
import numpy as np
import pyemma
from pyemma.util.contexts import settings
import MDAnalysis as mda
import matplotlib.pyplot as plt
# --- METHODS FOR PRINCIPAL COMPONENT ANALYSIS ---
def calculate_pca(data):
"""
Performs a PyEMMA PCA on the provided data.
Para... | StarcoderdataPython |
1876780 | <filename>scripts/python/backend_server/wsgi/alerts.py
#!/usr/bin/env python
# *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
# ** Copyright UCAR (c) 1992 - 2015
# ** University Corporation for Atmospheric Research(UCAR)
# ** National Center for Atmospheric Research(NCAR)
# ** Research A... | StarcoderdataPython |
8141504 | import os
import win32com.client as wincl
class redeem:
def banhammer(self, name):
speak = wincl.Dispatch("SAPI.SpVoice")
speak.Speak(name + " has been banned for spamming. Goodbye.")
return
def voicecomm(self, keyword):
speak = wincl.Dispatch("SAPI.SpVoice")
if keywor... | StarcoderdataPython |
3413360 | <gh_stars>0
# Time: O(logn * log(logn))
# Space: O(1)
import math
class Solution(object):
def smallestGoodBase(self, n):
"""
:type n: str
:rtype: str
"""
num = int(n)
max_len = int(math.log(num,2))
for l in xrange(max_len, 1, -1):
... | StarcoderdataPython |
3545176 | <reponame>cj-mills/OpenCV-Notes<filename>streamlit-demo-color-spaces.py
import streamlit as st
import cv2 as cv
import numpy as np
st.title("Color Spaces")
st.header("RGB")
img_bgr = cv.imread("images/flower.jpg")
st.image(cv.cvtColor(img_bgr, cv.COLOR_BGR2RGB), caption="Input")
st.header("BGR")
st.image(img_bgr, "B... | StarcoderdataPython |
1797685 | <reponame>Cobaltians-Samples/Samples-SideMenu-Web
# WARNING :
# install handlebars first (same version as used in js file)
# sudo npm install handlebars@2.0.0 -g
# (you will need nmp (node) to be installed first
#
# use this script like this :
# python compile.py
#
# it will build every files ending with .handlebars in... | StarcoderdataPython |
6608352 | <gh_stars>0
import sqlalchemy
from datetime import datetime
from ml_buff.database import DeclarativeBase
from ml_buff.models import feature_value
from sqlalchemy.orm import relationship
class Feature(DeclarativeBase):
__tablename__ = 'features'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
name =... | StarcoderdataPython |
3496693 | import requests
from bs4 import BeautifulSoup
import re
import time
import sys
import urllib.request
import xlwt
from lxml import etree
from multiprocessing import Pool
def getHTMLText(url,cookies):
try:
r = requests.get(url,cookies)
r.raise_for_status()
r.encoding = r.apparent_encoding
... | StarcoderdataPython |
8191736 | <reponame>immunIT/octowire-framework
# -*- coding: utf-8 -*-
# Octowire Framework
# Copyright (c) ImmunIT - <NAME> / <NAME>
# License: Apache 2.0
# <NAME> / Eresse <<EMAIL>>
# <NAME> / Ghecko <<EMAIL>>
import inspect
import os
import pathlib
import pkg_resources
import pkgutil
import platform
import subprocess
impor... | StarcoderdataPython |
4958402 | <filename>web_app/app/game_models/Game.py
"""
Game
====
"""
import random
from .Player import Player
from .GameSettings import GameSettings
from trivia_generator.web_scraper.WebScraper import get_page_by_random
from trivia_generator.web_scraper.WebScraper import get_page_by_category
from trivia_generator.web_scraper.W... | StarcoderdataPython |
9777549 | import ctypes as ct
import numpy as np
class BeeDNN:
c_float_p = ct.POINTER(ct.c_float)
lib = ct.cdll.LoadLibrary("./BeeDNNLib") # .dll is added under windows, .so under linux
lib.create.argtypes=[ct.c_int32]
lib.create.restype=ct.c_void_p
lib.add_layer.argtypes = [ct.c_void_p,ct.c_char_p]
lib.... | StarcoderdataPython |
8154908 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-01-23 17:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('easyrequest_hay_app', '0003_auto_20180118_1216'),
]
operations = [
migratio... | StarcoderdataPython |
6512692 | <reponame>ariafyy/R2Base
import requests
import os
host_url = "http://localhost:8000"
def delete_index(index_id):
res = requests.delete(url=os.path.join(host_url, 'r2base/v1/index/{}'.format(index_id)))
if res.status_code > 300:
raise Exception(res.json())
def make_index(index_id, mapping):
re... | StarcoderdataPython |
5194055 | <filename>apps/breakfast/tools/Life/tools/cx/messages/CxRecordRequestMsg.py
#
# This class is automatically generated by mig. DO NOT EDIT THIS FILE.
# This class implements a Python interface to the 'CxRecordRequestMsg'
# message type.
#
import tinyos.message.Message
# The default size of this message type in bytes.
... | StarcoderdataPython |
11386380 | <filename>fliswarm/tools.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: <NAME> (<EMAIL>)
# @Date: 2020-11-01
# @Filename: tools.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
import asyncio
from typing import Any, Dict, List, Optional, Set, Union
import fliswarm.node
_... | StarcoderdataPython |
372112 | from flask import Flask
import requests
APP = Flask(__name__)
@APP.route("/")
def home():
return f"Hello World" | StarcoderdataPython |
12805627 | from portal_gun.fabric.operations import *
| StarcoderdataPython |
3271068 | #-*- coding: utf-8 -*-
import ask_util
import json
import os, sys
import re
import requests
import time
class ParkReview:
def get(self,prdNo):
url = 'http://mbook.interpark.com/api/my/review/shortReviewList?sc.prdNo=%s&sc.page=1&sc.row=20' % prdNo
res = requests.get(url)
#print(res.text)
jsonD... | StarcoderdataPython |
4897909 | # -*- coding: utf-8 -*-
# Swish integration
from __future__ import absolute_import
# Copyright 2019 Open End AB
#
# 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/... | StarcoderdataPython |
6502848 | # Django
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
# Models
from coeadmin.user.models import User, Profile
class CustomUserAdmin(UserAdmin):
""" User model admin. """
list_display = ('email','username','first_name','phone_number','is_staff','is_pollster', 'is_admin', '... | StarcoderdataPython |
4821194 | <gh_stars>0
#!/usr/bin/python3
"""
/c/<text>: display “C ”, followed by the value of the text
variable (replace underscore _ symbols with a space )
"""
from flask import Flask
app = Flask(__name__)
@app.route('/', strict_slashes=False)
def hello_hbnb():
return 'Hello HBNB!'
@app.route('/hbnb', stric... | StarcoderdataPython |
4983180 | import numpy as np
from PIL import Image, ImageTk
import matplotlib.pyplot as plt
import cv2
from scipy.integrate import simps
import os
import tkinter
from scipy.signal import find_peaks
import math
import re
from matplotlib.ticker import (AutoMinorLocator)
from tkinter import Text, Radiobutton, Frame, Button, filedia... | StarcoderdataPython |
3557733 | n = cont = soma = media = maior = menor = 0
escolha = 's'
while escolha in 'SIMsim':
n = float(input('Digite um número: '))
if cont == 0:
maior = menor = n
else:
if n > maior:
maior = n
if n < menor:
menor = n
soma += n
cont += 1
escolha = input('Q... | StarcoderdataPython |
1765828 | from setuptools import setup, find_packages
setup(
name='dash_data_viewer',
python_requires='>=3.10',
version='1.0',
packages=find_packages('src'),
package_dir={'': 'src'},
url='https://github.com/TimChild/dash_data_viewer',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
... | StarcoderdataPython |
5007433 | import pandas
from ccxt.base.exchange import Exchange
from ccxt.base.errors import BadRequest, InvalidOrder, OrderNotFound
from collections import defaultdict
from copy import deepcopy
from decimal import Decimal
from btrccts.check_dataframe import _check_dataframe
from btrccts.convert_float import _convert_float_or_ra... | StarcoderdataPython |
6666558 | import tempfile
import time
import logging
from collections import OrderedDict
from .exceptions import RateLimitError
try:
import fiona # try importing fiona directly, because otherwise geopandas defers errors to later on when it actually needs to use it
import geopandas
GEOPANDAS_AVAILABLE = True
except ImportEr... | StarcoderdataPython |
9651609 | import re, itertools
import cfgescape as config
import random
class Factor(object):
__idx = 0
def __init__(self, name=None, abbv=None, label=None, values=None, id=None, tabular=True, bounds=None, visualize=True, default=0):
if tabular:
if values:
self.values = values
self.binary = False
... | StarcoderdataPython |
3214505 | from typing import Tuple
from sqlalchemy import select, String
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload, aliased
from sqlalchemy import func
from . import models, schemas
async def get_user(async_session: AsyncSession, user_id: int):
result = await async_session.exe... | StarcoderdataPython |
5157286 | from flask import Flask
from threading import Thread
app = Flask(__name__)
@app.route('/')
def home(): return "Hello, I am alive!"
def runWebServer():
print('Running WebServer...')
app.run('0.0.0.0', 8080)
def keep_alive(): Thread(target=runWebServer).start() | StarcoderdataPython |
232534 | '''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... | StarcoderdataPython |
1972126 | import numpy
import pytest
import sympy
from mpmath import mp
import quadpy
mp.dps = 50
test_cases = [
(lambda t: 1, -1, +1, 2),
(lambda t: 1, 0, +5, 5),
(lambda t: t, -0, +1, sympy.Rational(1, 2)),
(lambda t: t ** 2, -1, +1, sympy.Rational(2, 3)),
# Bailey example 1:
(lambda t: t * sympy.log... | StarcoderdataPython |
11308390 | from aws_cdk import aws_ec2 as ec2
from aws_cdk import core
from aws_emr_launch.constructs.security_groups.emr import EMRSecurityGroups
def test_emr_security_groups():
app = core.App()
stack = core.Stack(app, 'test-stack')
vpc = ec2.Vpc(stack, 'test-vpc')
emr_security_groups = EMRSecurityGroups(stack... | StarcoderdataPython |
1887697 | import logging
import socket
import pickle
from select import select
from gen import generate_code_str
import time
import os
import numpy
import scipy
from net import *
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(15)... | StarcoderdataPython |
16014 | import sys
from util.Timer import Timer
from util.FileOpener import FileOpener
from util.Logger import Logger
from util.PathExtractor import PathExtractor
from util.PathValidator import PathValidator
from service import SpacyModel
def lemmatize_text(file_path: str, timer: Timer):
logger = Logger()
output_file = File... | StarcoderdataPython |
4819557 | <filename>check_process.py<gh_stars>0
#!/usr/bin/env python
'''Checks processes'''
#===============================================================================
# Import modules
#===============================================================================
# Standard Library
import os
import subprocess
import ... | StarcoderdataPython |
11380501 | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/augment_PIL-img_filters.ipynb (unless otherwise specified).
__all__ = ['is_3dlut_row', 'read_lut', 'ApplyPILFilter']
# Cell
try:
from fastai.vision.all import *
except:
from fastai2.vision.all import *
from PIL import ImageFilter
from typing import List, Tuple, ... | StarcoderdataPython |
270292 | <reponame>aplneto/Algoritmos-IF969
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 16:13:59 2019
@author: apln2
"""
class _No:
'''
Classe auxiliar
Usada dentro da programação das classes das estruturas lineares.
A lista implementada abaixo é uma lista de encadeamento simples, ou seja,
... | StarcoderdataPython |
1992570 | from __future__ import absolute_import, unicode_literals
GRAPH_URL = 'https://graph.facebook.com'
API_VERSION = ''
APP_SECRET = None
APP_TOKEN = None
DEBUG = False
DEBUG_REQUESTS = DEBUG
DEBUG_HEADERS = False
TESTING = False
ETAGS = True
CACHE = None
DEDUP = True
MIGRATIONS = {}
RELATIVE_URL_HOOK = None
SUMMARY_INFO ... | StarcoderdataPython |
6470990 | <filename>sdk/python/lib/pulumi/_utils.py
# Copyright 2016-2020, Pulumi Corporation.
#
# 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
#
# Unl... | StarcoderdataPython |
3336614 | <gh_stars>1-10
from dataclasses import InitVar, dataclass, field
import numpy as np # type: ignore
from survival_evaluation.types import NumericArrayLike
def to_array(array_like: NumericArrayLike, to_boolean: bool = False) -> np.array:
array = np.asarray(array_like)
shape = np.shape(array)
if len(shape... | StarcoderdataPython |
6514161 | import_batch['contacts'] = {k: v for (k, v) in contacts.items(
) if k in fields or k in CONFIG['departments'][dept]}
for k, v in contacts.items():
contact = {}
contact['mobileNumber'] = v['sis']['Mobile']
contact['uniqueCampusId'] = k
contact['firstName'] = v['sis']['FirstName']
contact['lastName'] ... | StarcoderdataPython |
3580877 | # Copyright 2021 Sony Group Corporation.
#
# 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 ... | StarcoderdataPython |
11224022 | import os
import csv
def match(matched_dir,
matching_dir,
output_dir,
matched_key_column=0,
matching_key_column=0,
matched_column=-1,
matching_column=-1,
matched_header=True,
matching_header=True,
output_header=True,
i... | StarcoderdataPython |
56178 | <reponame>yudame/prakti-api
from django.test import TestCase
from ..test_behaviors import TimestampableTest
from ...models import Address
class AddressTest(TimestampableTest, TestCase):
model = Address
| StarcoderdataPython |
9757683 |
import tensorflow as tf
from tensorflow.python.compiler.tensorrt import trt_convert as trt
with tf.Session() as sess:
# First deserialize your frozen graph:
with tf.gfile.GFile(“/path/to/your/frozen/graph.pb”, ‘rb’) as f:
frozen_graph = tf.GraphDef()
frozen_graph.ParseFromString(f.read())
#... | StarcoderdataPython |
1885696 | try:
from libs.layers import *
from libs.utils_ft import *
except:
from layers import *
from utils_ft import *
import copy
import os
import sys
from collections import defaultdict
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
from torch.nn import MultiheadAtte... | StarcoderdataPython |
1936962 | import datasets
from typing import List, Optional, Union
def get_code_search_net_dataset(split: Optional[Union[str, List[str]]] = None, lang: str = 'all'):
dataset = datasets.load_dataset('code_search_net', split=split, name=lang)
return dataset
| StarcoderdataPython |
316992 | import numpy as np
from ..numpy_functions import np_func
from ..signatures import NUMPY_MA as NP_MA
np_ma = {
name: np_func(getattr(np.ma, name), "ma." + name, sigs)
for name, sigs in NP_MA.items()
}
| StarcoderdataPython |
8195148 | <gh_stars>10-100
import unittest
import tempfile
from shutil import rmtree
from os import path
from quikey.directories import AppDirectories
class AppDirectoriesTestCase(unittest.TestCase):
def setUp(self):
self.data = tempfile.mkdtemp()
self.config = tempfile.mkdtemp()
self.cache = tempf... | StarcoderdataPython |
3385666 | <gh_stars>0
# valueIterationAgents.py
# -----------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including ... | StarcoderdataPython |
6497649 | import unittest
from sidemash_sdk.sum import sum
class TestSum(unittest.TestCase):
def test_list_int(self):
data = [1, 2, 3]
result = sum(data)
self.assertEqual(result, 6)
if __name__ = '__main__'
unittest.main()
| StarcoderdataPython |
3319532 | <gh_stars>0
import random
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
REGRESSION = LinearRegression()
def linear_reg_anim(x_values, y_values, time):
"""
Creates animated linear regression with randomly
created dataset.
Params:
x_value... | StarcoderdataPython |
8190829 | from dvc.command.base import CmdBase
from dvc.exceptions import DvcException
class CmdDestroy(CmdBase):
def run_cmd(self):
try:
msg = u'This will destroy all information about your pipelines, ' \
u'all data files, as well as cache in .dvc/cache.\n' \
u'Are y... | StarcoderdataPython |
9722563 | <filename>gwtarget/DESI_mainInjector/Main-Injector-master/python/insideDesFootprint.py
import numpy as np
import matplotlib.path
def insideFootprint (ra, dec) :
ix = ra > 180
ra[ix] = ra[ix]-360.
footprint = getFootprint()
ix = footprint.contains_points( zip(ra,dec) )
return ix
def getFootprint() ... | StarcoderdataPython |
11304580 | import sys
sys.path.insert(0, '../')
import unittest
import lib.base as sinon
from lib.spy import SinonSpy
from lib.stub import SinonStub
from lib.sandbox import sinontest
"""
======================================================
FOR TEST ONLY START
==================================================... | StarcoderdataPython |
3394129 | <gh_stars>0
from __future__ import absolute_import
import json
import six
import tempfile
from datetime import timedelta
from django.core import mail
from django.core.urlresolvers import reverse
from django.utils import timezone
from sentry.data_export.base import ExportQueryType, ExportStatus, DEFAULT_EXPIRATION
fro... | StarcoderdataPython |
1840355 | import os
from django.conf import settings
from django.core.management.base import BaseCommand
from oldp.apps.cases.processing.case_processor import CaseProcessor, CaseInputHandlerFS, CaseInputHandlerDB
class Command(BaseCommand):
help = 'Processes cases from FS or DB with different processing steps (extract re... | StarcoderdataPython |
6506316 | #!/usr/bin/env python
# encoding: utf-8
# ----------------------------------------------------------------------------
from django.conf import settings as django_settings
from django.core import mail
from django_mailer import models, constants, queue_email_message
from base import MailerTestCase
class TestBackend(Ma... | StarcoderdataPython |
294287 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import copy
import beanmachine.ppl as bm
import gpytorch.likelihoods as likelihoods
import torch
from beanmachine.ppl.model.rv_identifier i... | StarcoderdataPython |
335 | <reponame>nirdslab/streaminghub
#!/usr/bin/env python3
import glob
import os
import pandas as pd
import dfs
SRC_DIR = f"{dfs.get_data_dir()}/adhd_sin_orig"
OUT_DIR = f"{dfs.get_data_dir()}/adhd_sin"
if __name__ == '__main__':
files = glob.glob(f"{SRC_DIR}/*.csv")
file_names = list(map(os.path.basename, files))... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.