id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3365541 | # -*- coding: utf-8 -*-
import json
from unittest.mock import MagicMock, patch
from chaosaws.iam.actions import (attach_role_policy, create_policy,
detach_role_policy)
@patch('chaosaws.iam.actions.aws_client', autospec=True)
def test_create_policy(aws_client):
client = MagicMock... | StarcoderdataPython |
3374986 | # --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
data = pd.read_csv(path)
bank = pd.DataFrame(data)
categorical_var = bank.select_dtypes(include = 'object')
print(categorical_var)
numerical_var = bank.select_dtypes(include = 'number')
print(numerical_var)
# co... | StarcoderdataPython |
6703036 | <filename>exercicios/desafio 36.py
v = float(input('Qual รฉ o valor da casa? \n'))
s = float(input('Qual รฉ o seu salรกrio? \n'))
a = float(input('Vai pagar em quantos anos? \n'))
p = v/(a*12)
if p < (s+s*.3):
print('a prestaรงรฃo serรก de R${:.2f}' .format(p))
else:
print('Emprestimo negado') | StarcoderdataPython |
1931660 | <gh_stars>1-10
'''
#Train a simple deep CNN on the CIFAR10 small images dataset using augmentation.
Using TensorFlow internal augmentation APIs by replacing ImageGenerator with
an embedded AugmentLayer using LambdaLayer, which is faster on GPU.
** Benchmark of `ImageGenerator`(IG) vs `AugmentLayer`(AL) both using aug... | StarcoderdataPython |
96492 | <reponame>evgeny-dmi3ev/js-services<filename>js_services/admin.py<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import copy
from aldryn_apphooks_config.admin import BaseAppHookConfig, ModelAppHookConfig
from aldryn_people.models import Person
from aldryn_translation_tools.admin import AllT... | StarcoderdataPython |
9789549 | <reponame>Horta/pandas-plink<filename>build_ext.py
import os
from os.path import join
from cffi import FFI
ffibuilder = FFI()
ffibuilder.set_unicode(False)
folder = os.path.dirname(os.path.abspath(__file__))
with open(join(folder, "pandas_plink", "_bed_reader.h"), "r") as f:
ffibuilder.cdef(f.read())
with open... | StarcoderdataPython |
370402 | <reponame>freshjang/MyCoin
import os
import sys
import psutil
import sqlite3
import numpy as np
import pandas as pd
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from utility.setting import columns_gj1, db_stg, ui_num
from utility.static import now, timedelta_sec, thread_decorator, strf_t... | StarcoderdataPython |
8044711 | from imblearn.under_sampling import AllKNN
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, MinMaxScaler, RobustScaler, StandardScaler, Normalizer, PowerTransformer, QuantileTransformer
from sklearn.compose import ColumnTran... | StarcoderdataPython |
6602284 | <gh_stars>1-10
import pytest
import numpy as np
from .tin import *
def TIN1():
p = np.array([
[-0.5, -0.5, 0],
[ 0.5, -0.5, 0],
[ 0.5, 0.5, 0],
[-0.5, 0.5, 0],
[ 0, 0, 0.5]
])
return TIN('TIN1', p)
def TIN2():
p = np.array([
[-0.5, -0.5... | StarcoderdataPython |
3501481 | <reponame>erocs/AOC
inp = 'hepxcrrq'
alpbet = 'abcdefghjkmnpqrstuvwxyz'
_inc = {alpbet[i]:alpbet[i+1] for i in xrange(len(alpbet)-1)}
_inc['z'] = 'a'
invld = 'iol'
def valid(s):
if len(s) != 8:
return False
l1 = len(s) - 1
l2 = len(s) - 2
p1 = None
p2 = None
trip = False
for i in xrange(len(s)):
... | StarcoderdataPython |
6569835 | import time
from itertools import chain
import torch
from addict import Dict
from torch import nn
from codes.model.base_model import BaseModel
from codes.model.imagination_model.util import get_component, merge_first_and_second_dim, \
unmerge_first_and_second_dim, sample_zt_from_distribution, clamp_mu_logsigma
fr... | StarcoderdataPython |
1647712 | <filename>python/p001.py
def solve():
return sum(x for x in range(1000) if (x % 3 == 0 or x % 5 == 0))
if __name__ == "__main__":
print(solve())
| StarcoderdataPython |
3477963 | <filename>seq.py<gh_stars>0
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Define Sequential model with 3 layers
model = keras.Sequential(
[
layers.Dense(2, activation="relu", name="layer1"),
layers.Dense(3, activation="relu", name="layer2"),
laye... | StarcoderdataPython |
67818 | <reponame>Mee321/HAPG_exp
import tensorflow as tf
from garage.envs import normalize
from garage.envs.box2d import CartpoleEnv
from garage.misc.instrument import run_experiment
from garage.tf.baselines import GaussianMLPBaseline
from garage.tf.envs import TfEnv
from garage.tf.policies import GaussianMLPPolicy
from test... | StarcoderdataPython |
5127391 | <reponame>pulp-platform/stream-ebpc
# Copyright 2019 ETH Zurich, <NAME> and <NAME>
# Copyright and related rights are licensed under the Solderpad Hardware
# License, Version 0.51 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://solder... | StarcoderdataPython |
4871029 | <gh_stars>10-100
from __future__ import print_function
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding, Reshape
from keras.layers import LSTM
from keras.datasets import imdb
import numpy as np
max_features = 20000
maxlen = 256 # cut texts after t... | StarcoderdataPython |
250850 | <filename>web/telebble/utils.py
import re
import json
import logging
import random
import string
import pytz
import datetime
import dateutil.parser
from common import api
import constants
import sources
import timeline
def generate_key():
"""
Generate a random string.
"""
return ''.join(random.choic... | StarcoderdataPython |
3437982 | <gh_stars>0
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from teachers.models import Teacher
from operation.models import UserFavorite
# Create your views here.
class TeacherDetailView(View):
def get(self, request,teacher_id):
teacher = Teacher.ob... | StarcoderdataPython |
3424918 | def df_rename_col(data, col, rename_to, destructive=False):
"""Rename a single column
data : pandas DataFrame
Pandas dataframe with the column to be renamed.
col : str
Column to be renamed
rename_to : str
New name for the column to be renamed
destructive : bool
If ... | StarcoderdataPython |
77669 | import os
from . import PyScoreDraft
ScoreDraftPath_old= os.path.dirname(__file__)
ScoreDraftPath=""
#\\escaping fix
for ch in ScoreDraftPath_old:
if ch=="\\":
ScoreDraftPath+="/"
else:
ScoreDraftPath+=ch
if os.name == 'nt':
os.environ["PATH"]+=";"+ScoreDraftPath
elif os.name == "posix":
os.environ["PATH"]+="... | StarcoderdataPython |
5040320 | from __future__ import division
import golly as g
from PIL import Image
from math import floor, ceil, log
import os
import json
#---------------------------------------------
# settings
srcPath = "/Volumes/MugiRAID1/Works/2015/13_0xff/ae/a_frame.png"
#---------------------------------------------
# ... | StarcoderdataPython |
1865454 | <filename>tests/sdk/queries/fileevents/filters/test_device_filter.py
# -*- coding: utf-8 -*-
import pytest
from tests.sdk.queries.conftest import EXISTS
from tests.sdk.queries.conftest import IS
from tests.sdk.queries.conftest import IS_IN
from tests.sdk.queries.conftest import IS_NOT
from tests.sdk.queries.conftest im... | StarcoderdataPython |
8191410 | <filename>search/value.py
# ----------
# User Instructions:
#
# Create a function compute_value which returns
# a grid of values. The value of a cell is the minimum
# number of moves required to get from the cell to the goal.
#
# If a cell is a wall or it is impossible to reach the goal from a cell,
# assign that cel... | StarcoderdataPython |
3292034 | <filename>tests/test_linear_router.py<gh_stars>10-100
import pytest
from simobility.routers import LinearRouter
from simobility.core import GeographicPosition
from simobility.core.clock import Clock
def test_router2d():
speed_kmph = 25
nyc_pos = GeographicPosition(-73.935242, 40.730610)
nyc_pos_shift = Ge... | StarcoderdataPython |
3374306 | <reponame>thomasjpfan/distiller<gh_stars>10-100
#
# Copyright (c) 2018 Intel 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
#
... | StarcoderdataPython |
3437710 | <filename>statsrat/bayes_regr/tausq_inv_dist.py
import numpy as np
from scipy import stats
'''
Distributions for prior weight precision (tausq_inv), defined as classes.
constant: Prior precision (tausq_inv) is treated as constant, i.e.
there is no attempt to change the initial hyperparameter values.
ard: Automat... | StarcoderdataPython |
6667115 | <gh_stars>0
def main():
import nltk
from nltk.corpus import stopwords
(dictOfTexts, fullText) = getTextFromFiles('test_docs')
freqDist = getMostFrequentWords(fullText).most_common(10)
hashTags = [w for (w, num) in freqDist ]
finalResultDictionary = {}
for hashTag in hashTags:
final... | StarcoderdataPython |
158479 | <filename>sdapis/migrations/0012_post_comment_list.py<gh_stars>0
# Generated by Django 3.2.8 on 2021-10-22 04:33
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sdapis', '0011_auto_20211021_2133'),
]
operat... | StarcoderdataPython |
1606458 | <filename>predict.py
import os
import time
import torch
import numpy as np
import torch.backends.cudnn as cudnn
from argparse import ArgumentParser
# user
from builders.dataset_builder import build_dataset_test
from lib import models, utils
from lib.utils import save_predict, zipDir
import lib.scribble_genera... | StarcoderdataPython |
4803418 | <reponame>lnxpy/postern
# Generated by Django 2.2.8 on 2020-01-12 09:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0003_auto_20200112_0934'),
]
operations = [
migrations.RenameField(
model_name='adminprofile',
... | StarcoderdataPython |
3431080 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
import copy
class Net(torch.nn.Module):
def __init__(self, dataset, device):
super(Net, self).__init__()
self.device = device
self.dataset = dataset # ๆฐๆฎ้ๅ ่ฝฝ
# ็บฟๆง็นๅพๆๅ
s... | StarcoderdataPython |
6704737 | from bs4 import BeautifulSoup
import requests
import time
# Manually extracted count for each topic
index = {"a": 100, "b": 96, "c": 99, "d": 97, "e": 99, "f": 99, "g": 100, "h": 95, "i": 99, "j": 80, "k": 87, "l": 95,
"m": 97, "n": 92, "o": 94, "p": 98, "q": 76, "r": 95, "s": 99, "t": 95, "u": 84, "v": 96, "... | StarcoderdataPython |
12828882 | <filename>2019/06_UniversalOrbitMap/uomap.py
# ======================================================================
# Universal Orbit Map
# Advent of Code 2019 Day 06 -- <NAME> -- https://adventofcode.com
#
# Computer simulation by Dr. <NAME>
# ==================================================================... | StarcoderdataPython |
9684849 |
import csv
import pandas as pd
import argparse
import random
# file = 'results_veridical/all_dataset'
# 0 id
# 1 text: <NAME> john and tom
# 2 hypothesis: fred saw john
# 3 depth: 1
# 4 occur: 1
# 5 label: yes
res_dir = 'results_veridical'
positive_clause_preds = ['realized', 'acknowledged', 'remembered', 'noted',... | StarcoderdataPython |
8154478 | """
FILTERED ELEMENT COLLECTOR
"""
__author__ = '<NAME> - <EMAIL>'
__twitter__ = '@solamour'
__version__ = '1.0.0'
# Importing Reference Modules
import clr # CLR ( Common Language Runtime Module )
clr.AddReference("RevitServices") # Adding the RevitServices.dll special
# Dynamo module to deal with Revit
... | StarcoderdataPython |
104940 | import unittest
import numpy as np
from sklearn.datasets import make_classification
from skactiveml.classifier import ParzenWindowClassifier
from skactiveml.stream import (
FixedUncertainty,
VariableUncertainty,
Split,
RandomVariableUncertainty,
)
class TemplateTestUncertaintyZliobaite:
def setU... | StarcoderdataPython |
3250027 | from flask_babel import gettext
def weekdays():
return [
gettext(u"Mon"),
gettext(u"Tue"),
gettext(u"Wed"),
gettext(u"Thu"),
gettext(u"Fri"),
gettext(u"Sat"),
gettext(u"Sun")
] | StarcoderdataPython |
5057321 | def sumHealth(enemies):
totalHealth = 0
for enemy in enemies:
totalHealth += enemy.health
return totalHealth
cannon = hero.findNearest(hero.findFriends())
enemies = cannon.findEnemies()
ogreSummaryHealth = sumHealth(enemies)
hero.say("Use " + ogreSummaryHealth + " grams.")
| StarcoderdataPython |
3318007 | <filename>python/testData/MockSdk3.4/Lib/abc.py<gh_stars>0
# Stubs
class object:
pass
class ABCMeta:
pass
def abstractmethod(foo):
pass | StarcoderdataPython |
8115459 | r = []
while True:
(a,b) = [int(i) for i in input().split(" ")]
if (a==0 and b==0):
break
r.append(a+b)
for num in r:
print(num)
| StarcoderdataPython |
119622 | array([[ -8.71756106, -1.36180276],
[ -8.58324975, -1.6198254 ],
[ -8.44660752, -1.87329902],
[ -8.30694854, -2.12042891],
[ -8.16366778, -2.35941504],
[ -8.01626074, -2.58846783],
[ -7.8643173 , -2.80576865],
[ -7.70752251, -3.0094502 ],
[ -7.5458139 , -... | StarcoderdataPython |
6438443 | import pymssql
import json
import os.path
from cryptography.fernet import Fernet
class Conn:
def __init__(self, host, port, user, password):
self.host = host
self.port = port
self.user = user
self.password = password
def Open(self):
try:
conn = pymssql.conn... | StarcoderdataPython |
46236 | <reponame>exoplanetvetting/DAVE<filename>diffimg/AbstractPrfLookup.py<gh_stars>1-10
"""
Created on Sun Dec 2 14:12:41 2018
@author: fergal
"""
from __future__ import print_function
from __future__ import division
import numpy as np
class AbstractPrfLookup(object):
"""Store and lookup a previously computed PRF... | StarcoderdataPython |
8119955 | <gh_stars>1-10
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This module is for gtest-related operations.
It provides functions to:
* normalize the test names
* concatenate gtest logs
* Remove p... | StarcoderdataPython |
12842815 | <gh_stars>0
#!/usr/bin/python
"""Sends a message that is read by the StillCaptureModule."""
import roslib; roslib.load_manifest('reefbot')
import rospy
from reefbot_msgs.msg import ImageCaptured
if __name__ == "__main__":
rospy.init_node('TestStillCaptureModule')
publisher = rospy.Publisher(
rospy.get_param(... | StarcoderdataPython |
5178664 |
from sys import path
path.append("../")
import logging as log
import unittest
import libCommon as COMMON
from libConstants import CUSTOM
import libEmail as TEST
test_from = "<EMAIL>"
password = "<PASSWORD>"
client_list = [{"user_email" : "<EMAIL>","first_name":"Puppy","last_name":"Paws", "user_login":"p... | StarcoderdataPython |
11224258 | from flask import current_app, Flask, render_template, redirect, url_for, request
import datadef
import actualdata
import regiondef
def create_app(debug=False, testing=False):
app = Flask(__name__)
app.debug = debug
app.testing = testing
@app.route("/")
def index():
return render_... | StarcoderdataPython |
8107604 | <filename>recommend.py
import tensorflow as tf
import pandas as pd
import numpy as np
import time
from remtime import printTime
user_index = pd.read_csv('data/test_index.csv')['indexId']
userId = pd.read_csv('data/test.csv')['userId']
movId = pd.read_csv('data/mov_hash.csv')['movId']
train_index = pd.read_csv('data/tr... | StarcoderdataPython |
3483791 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 23 00:49:01 2018
@author: tinokuba
"""
from .rsttree import RstTree, RstType, RstNode
from .relationstable import RelTable, Relation, RelElement
from .reltablegenerator import TableGenerator
from .comparisontable import ComparisonTable, Comparison,\
... | StarcoderdataPython |
8026593 | class QueuedNode(object):
"""Base class for all nodes in the call tree. A node may be an actual call or attribute set/get, in this case this
is a leaf node, or a call group (ordered, unordered, etc.), in that case it's a branch node."""
def __init__(self):
super(QueuedNode, self).__init__()
... | StarcoderdataPython |
9606157 | <filename>wsgi_intercept/tests/install.py<gh_stars>10-100
import os
import pytest
import wsgi_intercept
skipnetwork = pytest.mark.skipif(os.environ.get(
'WSGI_INTERCEPT_SKIP_NETWORK', 'False').lower() == 'true',
reason="skip network requested"
)
class BaseInstalledApp(object):
def __init__(self, app, ho... | StarcoderdataPython |
3244910 | from relax.vm import *
from relax.primitives import *
def signature(model,const):
(rvmap,_) = concolic_vm(model('_',const),0)
rands = 0
rvs = {}
output_types = []
for rv in rvmap:
(rand,output_type) = rvmap[rv].dist.lean_type()
rvs[rvmap[rv].name] = (rvmap[rv].dist,list(range(rands,... | StarcoderdataPython |
6542776 | class Participant():
def __init__(self, connection, id, year):
select_sql = """
SELECT name, email, likes, dislikes, in_office, participant_id
FROM v_participants WHERE participant_id = %d AND year = %d
""" % (id, year)
for data_row in connection.cursor().execute(sel... | StarcoderdataPython |
9637035 |
class LimitedDict(dict):
def __init__(self, _max_len: int) -> None:
if _max_len < 1:
raise ValueError("Length must be a positive number.")
super().__init__()
self._max_len = _max_len
def __setitem__(self, key: object, item: object) -> None:
if self.__len__() != 0 a... | StarcoderdataPython |
5054047 | #!/usr/bin/env python
# The Expat License
#
# Copyright (c) 2017, <NAME>
#
# 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 u... | StarcoderdataPython |
316051 | <reponame>Social-CodePlat/Comptt-Coding-Solutions
n=int(input())
arr=[int(x) for x in input().split()]
brr=[int(x) for x in input().split()]
my_list=[]
for i in arr[1:]:
my_list.append(i)
for i in brr[1:]:
my_list.append(i)
for i in range(1,n+1):
if i in my_list:
if i == n:
print("I beco... | StarcoderdataPython |
6620032 | <reponame>PieterBlomme/proteus<gh_stars>1-10
import logging
from pathlib import Path
import cv2
import numpy as np
from PIL import Image
from proteus.models.base import BaseModel
from proteus.models.base.modelconfigs import BaseModelConfig
from proteus.types import BoundingBox, Segmentation
from tritonclient.utils imp... | StarcoderdataPython |
1603897 | from personal_mycroft_backend.extra.backend_gui import BackendGUI
if __name__ == "__main__":
browser = BackendGUI()
browser.open()
| StarcoderdataPython |
182912 | #!/usr/bin/python
# (c) 2019, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | StarcoderdataPython |
12846851 | from rest_framework import viewsets
from .serializers import UniversitySerializer
from .models import University
class UniversityViewSet(viewsets.ModelViewSet):
queryset = University.objects.all()
serializer_class = UniversitySerializer
| StarcoderdataPython |
12805466 | <gh_stars>1-10
import random
def file_num_writer(fp):
runtotal = 0
while True:
num = yield
runtotal += num
print(num, runtotal, file=fp)
with open('/tmp/spam.txt', 'w') as fp:
handler = file_num_writer(fp)
next(handler) # Prime coroutine
for f in range(5):
num = ran... | StarcoderdataPython |
3468187 | <gh_stars>0
# -*- coding: utf8 -*-
import requests
from xml.etree import ElementTree
def process(xmldata):
articles = ElementTree.fromstring(xmldata)
data = []
for article in articles:
if article.tag != 'artikel':
continue
entry = {}
use_entry = True
try:
... | StarcoderdataPython |
9681275 | import os
import random
import numpy as np
import torch
import tensorflow as tf
def seed_everything(seed=42, seed_gpu=True):
'''
Fix ramdom seed to make all processes reproducable.
Call this before running scripts.
Note deterministic operation may have a negative single-run performance impact.
To ... | StarcoderdataPython |
1947387 | #!/home/wyf/anaconda3/envs/test/bin/python
#!coding=utf-8
import rospy
import cv2
import numpy as np
from sensor_msgs.msg import Image
import cv_bridge
from cv_bridge import CvBridge, CvBridgeError
import traffic_count.test.test as test
from traffic_count.detector.detector import Detector
import traffic_count.tracker... | StarcoderdataPython |
11259606 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-20 18:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0004_auto_20160720_2130'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
131335 | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import sys
import json
#from caresjpsutil import PythonLogger
FOSSIL_CAP = "/images/1_top_ten_emission_countries_fossil_ele_cap.png"
FOSSIL_CAP_PER = "/images/1_top_ten_emission_countries_fossil_ele_cap_per.png"
FOSSIL_GEN = ... | StarcoderdataPython |
6679564 | from time import sleep
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))))
import server
import loadbalancer as lb
# 1. Check whether there is or not default VM OS Template
# 1-1. If find, Go Step 2
# 1-2. If no exists, stop Your Default V... | StarcoderdataPython |
6615517 | <filename>chain_reaction/graphics/window.py
from abc import ABC, abstractmethod
import pygame
import pygame.font as font
import pygame.gfxdraw as gfxdraw
import chain_reaction.graphics.sprites as sprites
import chain_reaction.wrappers.engine as engine
# ----------- COLORS -------------
COL_BACK = (0, 0, 0)
COL_FORE... | StarcoderdataPython |
3219303 | # -*- coding: utf-8 -*-
# This module follows Mathematica 5 conventions. In current Mathematica a number of these functiions don't exist.
# Some of the functions in Mathematica 5 appear now under Information.
"""
Types of Values
"""
from mathics.builtin.base import Builtin
from mathics.builtin.assignments.internals ... | StarcoderdataPython |
12838107 | <gh_stars>10-100
import os
import asyncio
from pyppeteer import launch
from ..log_adapter import get_logger
from ..common_utils import get_user_home_dir, add_to_osenv
from ..constants import CONSTANTS
def render_html(url=None, html=None, get_text=False, script=None, reload_=False, wait_time=5, timeout=10):
result,... | StarcoderdataPython |
6433389 | #!/usr/bin/python
try:
from sequanto.automation import Client, AutomationObject
except:
import sys
from os import path
sys.path.insert ( 0, path.join ( path.dirname(__file__), '..', 'lib' ) )
from sequanto.automation import Client, AutomationObject
import serial
from gi.repository import Gtk
import... | StarcoderdataPython |
8067938 | <filename>Shift a Letter.py<gh_stars>0
# Write a procedure, shift, which takes as its input a lowercase letter,
# a-z and returns the next letter in the alphabet after it, with 'a'
# following 'z'.
def shift(letter):
return chr(ord(letter) + 1) if letter != 'z' else 'a'
print (shift('a'))
#>>> b
print... | StarcoderdataPython |
76660 | <reponame>PhilippMatthes/diplom
from tensorflow import keras
def make_fcn(input_shape, output_classes):
input_layer = keras.layers.Input(input_shape)
conv1 = keras.layers.Conv1D(filters=128, kernel_size=8, padding='same')(input_layer)
conv1 = keras.layers.BatchNormalization()(conv1)
conv1 = keras.lay... | StarcoderdataPython |
321107 | # -*- coding: utf-8 -*-
import os
from PIL import Image
def resizeImg(origin_file_path, new_file_path, width=640, height=0):
im = Image.open(origin_file_path)
(w, h) = im.size
if w > width:
w_n = width
else:
w_n = w
if height != 0 and h > height:
h_n = height
elif heigh... | StarcoderdataPython |
5055017 | <filename>ufdl-core-app/src/ufdl/core_app/permissions/_IsAuthenticated.py
from rest_framework.permissions import IsAuthenticated as IsAuthenticatedOrig
class IsAuthenticated(IsAuthenticatedOrig):
"""
Override for the built-in IsAuthenticated permission class
which adds object support.
"""
def has_... | StarcoderdataPython |
1916081 | <reponame>MadhavJivrajani/LFSR-Encryption<filename>lfsr.py
import numpy as np
from numpy.linalg import matrix_power
from feedback import feedback_poly, one_hot_encode
class LFSR:
def __init__(self, n, count_type, seed):
"""
n : order of the minimal polynomial
count_type : t... | StarcoderdataPython |
3262041 | <filename>ssafy/practice/subset.py
def subset(nums):
for i in range(1, 2 ** len(nums)):
sub = []
for j in range(len(nums) + 1):
if i & (1 << j):
sub.append(nums[j])
print(sub)
subset([3, 6, 7, 1, 5, 4])
| StarcoderdataPython |
3417099 | # emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... | StarcoderdataPython |
146361 |
import copy
configs = dict()
config = dict(
agent=dict(
q_model_kwargs=None,
v_model_kwargs=None,
pi_model_kwargs=None,
),
algo=dict(
discount=0.99,
batch_size=256,
training_ratio=256,
target_update_tau=0.005,
target_update_interval=1,
... | StarcoderdataPython |
4964079 | <filename>test/unit/http.py
import binascii
import io
import os
import re
import time
import json
import socket
import select
from unit.main import TestUnit
class TestHTTP(TestUnit):
def http(self, start_str, **kwargs):
sock_type = (
'ipv4' if 'sock_type' not in kwargs else kwargs['sock_type']... | StarcoderdataPython |
9601504 | <reponame>apoorv-x12/Django
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("<em>My Second Project</em>")
def help(request):
helpdict = {'help_insert':'HELP PAGE'}
return render(request,'apptwo/help.html',context=he... | StarcoderdataPython |
76387 | #!/usr/bin/env python3
from caproto.threading.client import Context
prefix = 'TEST:SERVER.'
ctx = Context()
CMD, = ctx.get_pvs(prefix+'seq.CMD')
ACK, = ctx.get_pvs(prefix+'seq.ACK')
message, = ctx.get_pvs(prefix+'seq.message')
values, = ctx.get_pvs(prefix+'seq.values')
example_pv, = ctx.get_pvs(prefix+'example_pv')
VA... | StarcoderdataPython |
11221063 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import math
import time
from datetime import datetime
from typing import Dict, List, Union
import isodate
import requests
DATE_FORMAT_SRC = '%Y-%m-%dT%H:%M:%SZ'
# Game must have one of these platforms to be tracked
game_platforms = [
'n5683oev', # Game Boy
... | StarcoderdataPython |
8134267 | from binance.exceptions import BinanceAPIException
from datetime import datetime
import pytz
import json
class ServiceBase:
METHOD_GET = 'GET'
METHOD_POST = 'POST'
METHOD_DELETE = 'DELETE'
def __init__(self, binanceInst):
self.binance = binanceInst
self.client = binanceInst.client
... | StarcoderdataPython |
9698199 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
DETR model and criterion classes.
"""
import torch
import torch.nn.functional as F
from torch import nn
from .position_encoding import PositionEmbeddingSine
from .transformer import Transformer, TransformerTemporal, TransformerReverse, Transfor... | StarcoderdataPython |
6474863 | <reponame>harshavardhanc/sunbird-analytics
# Author: <NAME>, <EMAIL>
import os
#This function traverses a directory finding all files with a particular substring
#Returns a list of files found
def findFiles(directory,substrings):
ls=[]
if (type(directory) == unicode or type(directory) == str) and type(substrings) =... | StarcoderdataPython |
4983813 | """
===============
Polarimeter GUI
===============
This is the variable waveplate GUI.
:copyright: 2020by Hyperion Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import hyperion
from hyperion import logging
import sys, os
import numpy as np
import pyqt... | StarcoderdataPython |
8032720 | from EXOSIMS.Observatory.SotoStarshade_ContThrust import SotoStarshade_ContThrust as sss
import math as m
import unittest
import numpy as np
import astropy.units as u
from scipy.integrate import solve_ivp
import astropy.constants as const
import hashlib
import scipy.optimize as optimize
from scipy.optimize import basin... | StarcoderdataPython |
4820108 | # encoding: utf-8
import os
import re
import arrow
from slugify import slugify
from flask import Flask, render_template, request, url_for, redirect
app = Flask(__name__)
from db import get_backend
import local_settings as conf
def format_size(num):
if num is None:
return None
format_str = '{:.1f}\xa... | StarcoderdataPython |
335325 | from .settings import settings_form_factory
__all__ = [
'settings_form_factory',
]
| StarcoderdataPython |
8081231 | import numpy
import timeit
from thinc.api import NumpyOps, LSTM, PyTorchLSTM, with_padded, fix_random_seed
from thinc.util import has_torch
import pytest
@pytest.fixture(params=[1, 6])
def nI(request):
return request.param
@pytest.fixture(params=[1, 2, 7, 9])
def nO(request):
return request.param
def test... | StarcoderdataPython |
60493 | <reponame>Hominine720202/BERT-NER-ScienceIE<filename>data/dataprocess.py<gh_stars>1-10
import pandas as pd
import numpy as np
import os,sys
from pytorch_pretrained_bert import BertTokenizer
import stanfordnlp
import nltk
from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
nlp = stanfordnlp.P... | StarcoderdataPython |
3524719 | from LinkedList import *
def test_linked_list_basic():
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(4)
node = linked_list.head
while node:
print(node.value)
node = node.next
test_linked_list_basic()
def test_linked_list_to_python_li... | StarcoderdataPython |
6452318 | from anndata import AnnData
import GEOparse
import gzip
import numpy as np
import os
from scanorama import *
import scanpy as sc
from scipy.sparse import vstack
from sklearn.preprocessing import normalize
from process import process, load_names, merge_datasets
from utils import *
NAMESPACE = 'masuda_mouse_microglia'
... | StarcoderdataPython |
51094 | <gh_stars>0
"""
Classes to manage job runs.
"""
from collections import deque
import logging
import itertools
from tron import node, command_context, event
from tron.core.actionrun import ActionRun, ActionRunFactory
from tron.serialize import filehandler
from tron.utils import timeutils, proxy
from tron.utils.observe... | StarcoderdataPython |
8005204 | <reponame>TheCamusean/sds
import autograd.numpy as np
import autograd.numpy.random as npr
from autograd.scipy.special import logsumexp
from sds.initial import CategoricalInitState
from sds.transitions import StationaryTransition
from sds.observations import GaussianObservation
from sds.utils import ensure_args_are_v... | StarcoderdataPython |
8031489 | # -*- coding: utf-8 -*-
import setuptools
def read(path):
"""Read file."""
with open(path) as f:
return f.read()
version = '3.7.dev0'
long_description = '\n\n'.join([
read('README.rst'),
read('CHANGES.rst'),
])
setuptools.setup(
name='icemac.ab.calendar',
version=version,
descri... | StarcoderdataPython |
4889878 | from typing import Callable, Iterable, Mapping, Tuple, Union
Filter = Callable[..., str]
Filters = Union[Iterable[Tuple[str, Filter]], Mapping[str, Filter]]
| StarcoderdataPython |
1622856 | """
Verifies that embedding UAC information into the manifest works.
"""
import TestGyp
from xml.dom.minidom import parseString
test = TestGyp.TestGyp(formats=['msvs', 'ninja'], platforms=['win32'], disable='Need to solve win32api.LoadLibrary problems')
import pywintypes
import win32api
import winerror
RT_MANIFEST... | StarcoderdataPython |
374623 | <filename>setup.py<gh_stars>1-10
#!/usr/bin/env python3
# coding: utf-8
from setuptools import find_packages, setup
from filesystem import version
setup(
name='masonite-fs',
version=version,
packages=find_packages(),
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description='Pr... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.