id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
12861936 | import os
import shutil
def pull_default(folder=None):
cwd = os.getcwd()
if None == folder:
folder = cwd
for path in os.listdir(folder):
project_path = os.path.join(folder, path)
if os.path.isdir(project_path):
dot_git_folder = os.path.join(project_path, '.git')
... | StarcoderdataPython |
3542654 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from har2tree import CrawledTree
import os
from glob import glob
class TestBasic(unittest.TestCase):
def test_lalibre(self):
test_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data', 'lalibre')
to_process = sorted(gl... | StarcoderdataPython |
3576293 | <filename>model/model-development/eval_models.py
import warnings
import matplotlib
matplotlib.use("Agg")
import os
import sys
import argparse
import pickle
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cluster ... | StarcoderdataPython |
5057138 | from qrcode import QRCode
import colorama
colorama.init()
def draw(data: str, version: int=1):
white_block = '\033[0;0;47m '
black_block = '\033[0;0;48m '
new_line = '\033[m\n'
qr = QRCode(version)
qr.add_data(data)
qr.make()
output = white_block*(qr.modules_count+2) + new_line
for... | StarcoderdataPython |
295008 | <filename>atest/testdata/keywords/named_args/DynamicLibrary.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from six import string_types
from helper import pretty
KEYWORDS = {
'Escaped Default Value': ['d1=${notvariable}', 'd2=\\\\', 'd3=\n', 'd4=\t'],
'Four Kw Args': ['a=default', 'b=default', 'c=default',... | StarcoderdataPython |
1696498 | <reponame>sachinumrao/Kaggle
from collections import Counter
from nltk.tokenize import RegexpTokenizer
from unidecode import unidecode
import numpy as np
import pandas as pd
import contractions
import string
import re
train_file = '~/Data/Kaggle/real_or_not/train.csv'
df = pd.read_csv(train_file)
df = df.drop(['id', ... | StarcoderdataPython |
235575 | # -*- coding: utf-8 -*-
"""mylambdatatoo.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1gqu7Q5kOkcgbVBpD5Y9wACNw4Cd3F8ig
"""
pip install -i https://test.pypi.org/simple/ mylambdatatoo==0.0.6
import mylambdatatoo
mylambdatatoo?
mylambdatatoo.... | StarcoderdataPython |
1741185 | <reponame>lammySup/ncscli<filename>examples/loadtest/master_locust.py<gh_stars>1-10
import datetime
import json
import os
import six
import sys
import locust
from locust import events
from locust import HttpLocust, TaskSet
from locust.log import console_logger
from locust import web
def indexxx(l):
l.client.get(... | StarcoderdataPython |
1870097 | import time
import logging
import requests
class WebsiteDownException(Exception):
pass
def ping_website(address, timeout=20):
"""
Fetch a url and check if status_code >= 200.
Report if status_code >= 400
"""
try:
response = requests.head(address, timeout=timeout)
if response... | StarcoderdataPython |
232572 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 14:06:56 2020
Class to handle coordinates in Hive according to how they are used in the
entomology Hive position editor.
cf.
https://entomology.appspot.com/hive.html?bg=0&board=:w***@bA**@bB***@bG*@bL*@bM*@bP*@bQ**@bS***@wA**@wB***@wG*@wL*@wM*@w... | StarcoderdataPython |
3391052 | # -*- coding: utf-8 -*-
'''
https://leetcode.com/discuss/interview-question/376581/Twitter-or-OA-2019-or-Unique-Twitter-User-Id-Set
'''
class Solution(object):
def uniqloID(self, arr):
arr = sorted(arr, reverse = False)
ans = 0
currmin = 0
for a in arr:
currmin = max( currmin + 1, a )
ans += currmin... | StarcoderdataPython |
233943 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from generate_paper_outputs import wave_column_headings
def plot_grouped_bar(backend="combined", output_dir="released_outputs/combined", measure="declined", breakdown="high_level_ethnicity"):
''' Plot a chart showing the percent of people of ea... | StarcoderdataPython |
1617908 | <reponame>andreaskranis/genofix
'''
Created on Sep 17, 2021
@author: mhindle
'''
import unittest
import numpy as np
import pandas as pd
from empirical.jalleledist3 import JointAllellicDistribution
from scipy.stats import rankdata
class Test(unittest.TestCase):
def test_basicuse(self):
sim_data = pd.read_... | StarcoderdataPython |
6690719 | from splinter import Browser
from bs4 import BeautifulSoup
from webdriver_manager.chrome import ChromeDriverManager
from rdb_functions import clean_list
from scrapy import Selector
import pandas as pd
import time
def scrape():
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Bro... | StarcoderdataPython |
8155960 | <reponame>saimoncse19/bltk
from .langtools.tokenizer import Tokenizer
from .langtools.stopwords import remove_stopwords
from .langtools.pos_tagger import PosTagger
from .langtools.chunker import Chunker
from .langtools.stemmer import UgraStemmer
| StarcoderdataPython |
6440767 | import pytest
from .core import FakeProcess
@pytest.fixture
def fake_process():
with FakeProcess() as process:
yield process
| StarcoderdataPython |
1635577 | import darpa_lwll.jpl as jpl
if __name__ == '__main__':
jpl.main() | StarcoderdataPython |
8187665 | <gh_stars>1000+
from unittest import mock
import graphene
import pytest
from .....shipping.models import ShippingMethod, ShippingZone
from ....tests.utils import get_graphql_content
@pytest.fixture
def shipping_method_list(shipping_zone):
shipping_method_1 = ShippingMethod.objects.create(
shipping_zone=... | StarcoderdataPython |
3255780 | import sys
from Bio import SeqIO
for rec in SeqIO.parse(open(sys.argv[1]), "genbank"):
for feature in rec.features:
if feature.type == "CDS":
# print feature
gene_id = feature.qualifiers.values()[0][0].split(":")[1]
print ">%s:%s\n%s" % (gene_id, rec.name, feature.location.extract(rec).seq)
| StarcoderdataPython |
3402474 | <filename>layers/__init__.py
from .gcn import GCN
from .assign import Assign
from .discriminator import Discriminator
| StarcoderdataPython |
11242281 | <reponame>akifumi-maeda/django_diy_mini_blog
from django.contrib import admin
# Register your models here.
from .models import BlogAuthor, Blog, BlogComment
admin.site.register(BlogAuthor)
admin.site.register(Blog)
admin.site.register(BlogComment) | StarcoderdataPython |
4942948 | '''This module builds a class for k-nearest neighbor classification.
'''
from src.classification.knn_classify import KNNClassify
import numpy as np
class KNNRegression(KNNClassify):
'''
A class used to represent a k-nearest neighbor regressor.
The regression methods and attributes can be found in the
... | StarcoderdataPython |
1646933 | def anagram(s):
if len(s) % 2 == 1:
return -1
mid = len(s) // 2
A = map(lambda x: ord(x) - ord('a'), list(sorted(s[:mid:])))
B = map(lambda x: ord(x) - ord('a'), list(sorted(s[mid::])))
d = 0
for i in range(len(A)):
if A[i] != B[i]:
d += 1
return d
n = int(raw_input())
for i in range(n):
print anagram(r... | StarcoderdataPython |
4888983 | from django.db import models
from rest_framework import serializers, viewsets
from rest_framework_nested import serializers as nested_serializers
from rest_framework_nested import relations
class Parent(models.Model):
name = models.CharField(max_length=10)
class Child1(models.Model):
name = models.CharField... | StarcoderdataPython |
5103809 | import re
from django.conf import settings
from django.conf.urls.defaults import handler404, handler500
from django.core.urlresolvers import RegexURLPattern, RegexURLResolver, get_callable
from django.core.urlresolvers import NoReverseMatch
from django.core.urlresolvers import get_script_prefix
from django.utils.datas... | StarcoderdataPython |
4835920 | <reponame>LOGON17/10-Days-of-Statistics-HackerRank
import numpy as np
from scipy import stats
size = int(input())
numbers = list(map(int, input().split()))
print(np.mean(numbers))
print(np.median(numbers))
print(int(stats.mode(numbers)[0])) | StarcoderdataPython |
6538648 | <filename>jsrt.py
# -*- coding: utf-8 -*-
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from csv import reader, excel_tab
from os import listdir
import tensorflow as tf
import copy
import math
class JsrtImage(object):
""" JSRTImage object provides the imag... | StarcoderdataPython |
5174795 | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | StarcoderdataPython |
6570792 | <reponame>Ojhowribeiro/PythonProjects<filename>exercicios/PycharmProjects/exepython/ex003.py
n1 = int(input('digite um numero:'))
n2 = int(input('digite outro numero:'))
s = int((n1+n2))
print('A soma entre {} e {} é igual á {}'.format(n1, n2, s))
print(type(s))
| StarcoderdataPython |
11295440 | <filename>graphene_frappe/api.py
import frappe
import json
from frappe.api import get_request_form_data
import graphene
from graphene import Schema
from graphene_frappe.graphql.query import Query
from graphene_frappe.graphql.mutations import Mutation
@frappe.whitelist(allow_guest=True)
def graphql():
""" this w... | StarcoderdataPython |
9794624 | <filename>artellapipe/widgets/waiter.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains widgets to wait for Artella operations
"""
from __future__ import print_function, division, absolute_import
__author__ = "<NAME>"
__license__ = "MIT"
__maintainer__ = "<NAME>"
__email__ = "<EM... | StarcoderdataPython |
12835088 | import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalSubscriber(Node):
def __init__(self):
super().__init__('minimal_subscriber')
self.subscription = self.create_subscription(
String, 'chatter', self.listener_callback)
def listener_callback(self, ... | StarcoderdataPython |
5037158 | import streamlit as st
import psycopg2
import inspect
import sys
import os
import importlib
import functions.fn_db as fn_db
import functions.fn_plot as fn_plot
import pandas as pd
import numpy as np
import webbrowser
import markdown
import base64
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontP... | StarcoderdataPython |
8150475 | <filename>WebPage/prog/views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.views.generic import View
# Create your views here.
from django.http import HttpResponse
#base
class HomeView(View):
def get(self, request, *args, **kwargs):
return rende... | StarcoderdataPython |
3358096 | <gh_stars>1-10
import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
# SMTP - Simple Mail Transfer Protocol
# parâmetros do servidor do e-mail
smtpHost:str = "smtp.gmail.com"
smtpPort:int = 587
server = smtplib... | StarcoderdataPython |
3498505 | from datetime import datetime
robot_name = '小麦'
def show_time():
dt = datetime.now()
print(dt.strftime('今天是:%Y年%m月%d日 %H:%M:%S'))
#定义1个函数
def hello(name):
print('---------------')
print(f'你好,{name},我是{robot_name}')
print(f"天地之间,{name}最帅!")
print(f'我对{name}的敬仰之情,犹如黄河之水一发而不可收拾!')
print(f'帅归帅,{name}出门别忘记带口罩!') | StarcoderdataPython |
3443930 | <gh_stars>0
import subprocess
def svg2pdf(infile, outfile):
subprocess.check_output(f'inkscape {infile} --export-pdf {outfile}', shell=True)
def svg_line(x1, y1, x2, y2, color, thickness):
return ''.join([
'<line ',
'stroke="' + color + '" ',
'stroke-width="' + str(thickn... | StarcoderdataPython |
4836812 | # Given two words (begin_word and end_word), and a dictionary's word list,
# return the shortest transformation sequence from begin_word to end_word, such that:
# Only one letter can be changed at a time.
# Each transformed word must exist in the word list. Note that begin_word is not a transformed word.
# Note:
# Retu... | StarcoderdataPython |
4803822 | <gh_stars>100-1000
# coding=utf-8
import time
import timeit
from datetime import datetime
utcnow = datetime.utcnow()
numbers = 1000000
# timeit_timeit = timeit.timeit(lambda: '%04d-%02d-%02dT%02d:%02d:%02dZ' % (
# utcnow.year, utcnow.month, utcnow.day, utcnow.hour, utcnow.minute, utcnow.second), number=numbers)
#... | StarcoderdataPython |
4848091 | <gh_stars>0
from NlpCtr import nlpCtr
from ModeCtr import modeCtr
paragraph = """
在美丽的旌湖旁,坐落着德阳市实验小学校。
一进校门,看到四周有几座高大的教学楼,分别是真全楼、真玉楼、真思楼、真问楼、真学楼。穿过真玉楼来到了我们篮球场和乒乓球场,又穿过乒乓球场就来到了红红的跑道上。跑道像一大片红领巾似的,向前走来到了升旗台。每到星期一的时候,全校同学在升旗台下一起唱国歌。这是一所非常美丽的学校!
春天,学校的树木和小草开始发芽了,到处鸟语花香,生机勃勃。漂亮的李花开了,白白的,像花仙子正在翩翩起舞似的。
夏天,学校树木的叶子长得又多又密,像撑开... | StarcoderdataPython |
6682272 | <gh_stars>0
"""Python package to handle python interface to egta online api"""
# pylint: disable=too-many-lines
import asyncio
import base64
import collections
import copy
import functools
import hashlib
import itertools
import json
import logging
import inflection
import jsonschema
import requests
from lxml import et... | StarcoderdataPython |
1617643 | <reponame>TugberkArkose/MLScheduler
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power ... | StarcoderdataPython |
9687180 | """Model construction functions."""
import torch
from fvcore.common.registry import Registry
MODEL_REGISTRY = Registry("MODEL")
MODEL_REGISTRY.__doc__ = """
Registry for video/audio model.
The registered object will be called with `obj(cfg)`.
The call should return a `torch.nn.Module` object.
"""
def build_model(c... | StarcoderdataPython |
183691 | <reponame>onefinestay/pylytics<filename>pylytics/library/warehouse.py
from contextlib import closing
import logging
from utils import classproperty
log = logging.getLogger("pylytics")
class Warehouse(object):
""" Global data warehouse pointer singleton. This class avoids
having to pass a data warehouse con... | StarcoderdataPython |
3403898 | <reponame>pafri/DJV<filename>examples/CmdLinePy/AnimationCmdLineExample.py<gh_stars>100-1000
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2019-2020 <NAME>
# All rights reserved.
import djvCorePy
import djvCmdLineAppPy
import sys
from datetime import timedelta
app = None
def animationValue(v):
buf = "... | StarcoderdataPython |
47264 | string = input().lower().split()
for word in set(string):
print(word, string.count(word))
| StarcoderdataPython |
3390188 | <gh_stars>1000+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~ Definitions ~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import re
TENSOR_MAPS_2D = ['read_tensor']
TENSOR_MAPS_1D = ['reference']
TENSOR_SUFFIX = '.hd5'
DNA_SYMBOLS = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
INPUTS_INDEL = {'A': 0, 'C': 1, 'G': 2, 'T': 3, '*... | StarcoderdataPython |
12857610 | # https://codewith.mu/en/tutorials/1.0/microbit
from microbit import *
flag = True
while True:
sleep(100)
if button_a.was_pressed():
flag = not flag
if flag:
print((accelerometer.get_x(),))
else:
print(accelerometer.get_values()) | StarcoderdataPython |
1714993 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 1 13:05:36 2018
@author: thieunv
"""
import tensorflow as tf
a = tf.placeholder(tf.float64)
b = tf.placeholder(tf.float64)
c = a * b
with tf.Session() as sess:
a, b, output = sess.run([a, b, c], feed_dict={a:[3, 4, 5], b:[1,5,6]})
... | StarcoderdataPython |
1624096 | <gh_stars>0
#!/usr/bin/env python3
# quesiton 45: triangular, pentagonal, hexagonal
def triangular(n):
return n*(n+1)/2
def pentagonal(n):
return n*(3*n-1)/2
def hexagonal(n):
return n*(2*n-1)
# first sequence is t285 = p165 = h143
# start with these values and up to others
# initialize
# idea, keep only ... | StarcoderdataPython |
1869213 | import tensorflow.compat.v1 as tf
import collections
import numpy as np
import dnc_utils
from dense_layer import DenseLayer
from freeness import Freeness
from temporal_linkage import TemporalLinkage
tf.disable_v2_behavior()
AccessState = collections.namedtuple('AccessState',
(
'memory',
'read_w... | StarcoderdataPython |
3283933 | #!/usr/bin/env python
'''
Script to compare some scalar values from different runs of Thwaites melt variability experiment.
'''
# Parse options
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-p", dest="process", action="store_true", help="read and process data", metavar="FILE")
options, ... | StarcoderdataPython |
3348900 | <reponame>MrMino/pip
from pip._internal.models.candidate import InstallationCandidate
from pip._internal.models.link import Link
def make_mock_candidate(version, yanked_reason=None, hex_digest=None):
url = f'https://example.com/pkg-{version}.tar.gz'
if hex_digest is not None:
assert len(hex_digest) ==... | StarcoderdataPython |
5073903 | import speech_recognition as sr
from gtts import gTTS
import pyglet
from time import sleep
import os
r = sr.Recognizer()
def tts(text, lang):
file = gTTS(text=text, lang=lang)
filename = 'sp1.mp3'
file.save(filename)
music = pyglet.media.load(filename, streaming=False)
music.play()
sleep(mus... | StarcoderdataPython |
1994778 | <gh_stars>1-10
#!/usr/bin/env python3
"""
This file is intended to be a verbose "bootstrap" script used in conjunction with a jupyter notebook.
From <git root>/experiments/annealing/notebooks/my-notebook.ipynb, invoke:
%run ../../startup.py
And the following commands will run (verbosely).
"""
import sys
import s... | StarcoderdataPython |
6674227 | from __future__ import division
import argparse, os, codecs, re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
from chorus.helpers import create_chroma
####
no_word = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '[', ']', ',', '.', '<', '>', ':']
root = 'data'
cand... | StarcoderdataPython |
4809516 | <reponame>ethansaxenian/RosettaDecode
from bisect import bisect_left
def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi
hi = hi if hi is not None else len(a) # hi defaults to len(a)
pos = bisect_left(a,x,lo,hi) # find insertion position
return (pos if pos != hi and a... | StarcoderdataPython |
1749626 | #/usr/bin/env python
#coding=utf-8
import re
def change_sentence(sentence):
# 去除标点符号
sentence = sentence.replace(",", "")
sentence = sentence.replace(",", "")
sentence = sentence.replace(".", "")
sentence = sentence.replace("。", "")
sentence = sentence.replace("?", "")
sentence... | StarcoderdataPython |
5075655 | import socket
try:
raise socket.error(104, 'Connection reset by peer')
except socket.error:
print "cachao"
| StarcoderdataPython |
1974112 | """
DeepCache
DeepCache is distributed under the following BSD 3-Clause License:
Copyright(c) 2019
University of Minensota - Twin Cities
Authors: <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>
All rights reserved.
Redistribution and use in source and bin... | StarcoderdataPython |
8045088 | """
Cosmo Tech Plaform API
Cosmo Tech Platform API # noqa: E501
The version of the OpenAPI document: 0.0.11-SNAPSHOT
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from cosmotech_api.api_client import ApiClient, Endpoint as _E... | StarcoderdataPython |
5134744 |
# import sys
# sys.path.insert(0, sys.path[0].rstrip('/pipeline/src'))
# %load_ext autoreload
# %autoreload 2
# import os
# os.environ.update(dict(
# WML_USERNAME='admin',
# WML_PASSWORD='password',
# CP4D_URL='https://zen-cpd-zen.apps.pwh.ocp.csplab.local'
# ))
import os
import time
import types
im... | StarcoderdataPython |
9620897 | #!/usr/bin/env python3
"""
Demo for Os class, allowing fine-grained Windows Cygwin/WSL OS detection not available in Python standard library
"""
from pybashutils.os_detect import Os
print(Os())
| StarcoderdataPython |
373651 | <reponame>catalpainternational/rapidsms<filename>rapidsms/contrib/handlers/app.py
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import logging
from rapidsms.apps.base import AppBase
from .utils import get_handlers
logger = logging.getLogger(__name__)
class App(AppBase):
def __init__(self, *args, **kwargs... | StarcoderdataPython |
3585438 | <gh_stars>100-1000
# pylint: skip-file
def main():
'''
ansible oc module for registry
'''
module = AnsibleModule(
argument_spec=dict(
state=dict(default='present', type='str',
choices=['present', 'absent']),
debug=dict(default=False, type='bool'),... | StarcoderdataPython |
4810079 | <gh_stars>1-10
#
# Copyright (c) 2013 <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 use, copy, modify, merge, publ... | StarcoderdataPython |
3382365 | import os, sys, pymzml, pickle, shutil, argparse
import numpy as np
import pandas as pd
import scipy.signal
import scipy.optimize as opt
import pyteomics.mass as pymass
import matplotlib.pyplot as plt
DEFAULT_MIN_CLUSTER_WIDTH = 5
DEFAULT_EXTRACTION_WIDTH = 0.01
DEFAULT_EXTRACTION_LENGTH = 0.5
DEFAULT_ISOTOPE_WEIGHT =... | StarcoderdataPython |
3320185 | <filename>tests/misc/speech_engine_test.py
from vxt.misc.speech_engine import (
init_speech_engine,
BING,
GOOGLE,
GOOGLE_CLOUD,
SPHINX,
HOUNDIFY,
IBM,
)
from vxt.view.config import Config
import pytest
CONFIG = Config()
def test_init_speech_engine_bing():
assert (
CONFIG.engi... | StarcoderdataPython |
3261239 | <reponame>juneyochen/sc-projects<gh_stars>0
"""
File: boggle.py
Name:
----------------------------------------
TODO:
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE = 'dictionary.txt'
python_list = [] # 字典用的
current = [] # 使用者輸入的字母
used... | StarcoderdataPython |
1747864 | #!/bin/python
# -*- coding: cp1252 -*-
'''
// Licenca Creative Commons
// Circuitos Integrados e Sistemas Embarcados - Relatorio Final de
// <NAME>, <NAME>, <NAME> e <NAME>
// esta licenciado com uma Licenca Creative Commons
// Atribuicao-NaoComercial-CompartilhaIgual 4.0 Internacional.
// Baseado no trabalho disponiv... | StarcoderdataPython |
1737415 | import unittest
from math import acos, floor, pi, sqrt
from random import randint
from pymath.tank_truck import tankvol
def tankvol_sol(h, d, vt):
if h == 0:
return 0
r = d / 2.0
if h == r:
return vt // 2
if h == d:
return vt
if h > r:
h = d - h
hilevel = T... | StarcoderdataPython |
1727910 | <filename>jsonp/ext/jsonp.py
from .base import FormatterBase
import json
class Parser(FormatterBase):
"""A very basic formatter.
"""
def format(self, data):
return str(json.dumps(data, indent=4))
| StarcoderdataPython |
5111450 | #!/usr/bin/env python
#coding=utf-8
'''
Definition of Oracle class. Given the gold AMR graph, the alignments and
the current state, it decides which action should be taken next.
@author: <NAME> (<EMAIL>)
@since: 03-10-16
'''
from action import Action
from relations import Relations
import copy
from subgraph import S... | StarcoderdataPython |
5023265 | """Simple Policy Gradient"""
import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, optimizers
import gym
import numpy as np
import fire
print("Tensorflow " + tf.__version__)
def make_model(obser_dim, n_actions):
# activation = lambda x: tf.nn.leaky_relu(x, alpha=0... | StarcoderdataPython |
5070222 | import inject
from typing import Optional
from common.domain.player import Player
from common.domain import PlayerCacheInterface
class GetPlayer:
@inject.autoparams('cache')
def __init__(self, cache: PlayerCacheInterface):
self.__cache = cache
def execute(self, player_id: str) -> Optional[Player... | StarcoderdataPython |
11398163 | <filename>dialogos/build/queuelib/queuelib/tests/test_pqueue.py
from queuelib.pqueue import PriorityQueue
from queuelib.queue import FifoMemoryQueue, LifoMemoryQueue, FifoDiskQueue, LifoDiskQueue
from queuelib.tests import QueuelibTestCase
def track_closed(cls):
"""Wraps a queue class to track down if close() met... | StarcoderdataPython |
1956553 | # module: tokrules.py
# author: helq
# license: wtfpl
# This module contains the type analizer and the interpreter
primitives = ['CONS', 'CAR', 'CDR', 'Not', 'ToString']
def isInfacts_list(id, facts_list):
lenEnvs = len(facts_list)
for i in range(lenEnvs-1,-1,-1):
if id in facts_list[i]:
r... | StarcoderdataPython |
1949024 | #
# 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"); you may not u... | StarcoderdataPython |
1603824 | <reponame>jamsidedown/adventofcode2020
from functools import reduce
from operator import or_
import re
from typing import Dict, List, Set
ingredient_pattern = re.compile(r'^([\w\s]+) \(contains ([\w\s,]+)\)$')
class Food:
def __init__(self, input: str):
ingredients, allergens = ingredient_pattern.match(... | StarcoderdataPython |
3204391 | import os
import argparse
import xmltodict
import json
import requests
from concurrent.futures import ThreadPoolExecutor
MAX_WORKERS = 10
ENDPOINT = 'https://explorecourses.stanford.edu/'
DEPARMENTS_ENDPOINT = ENDPOINT + '?view=xml-20140630'
COURSE_ENDPOINT = (ENDPOINT + 'search?view=xml-20140630&academicYear='
... | StarcoderdataPython |
7723 | #
# OMNIVORE CONFIDENTIAL
# __________________
#
# [2013] - [2019] Omnivore Technologies
# All Rights Reserved.
#
# NOTICE: All information contained herein is, and remains
# the property of Omnivore Technologies and its suppliers,
# if any. The intellectual and technical concepts contained
# herein are proprietary... | StarcoderdataPython |
4961950 | <filename>watchdog_kj_kultura/organizations_requests/fields.py
from django.db.models import CharField
from django.utils.translation import ugettext_lazy as _
from .validators import is_valid_relative_date
PERIOD_HELP_TEXT = _("Try to write words a period of time.")
class RelativeDeltaField(CharField):
def __i... | StarcoderdataPython |
11307535 | # Autor: <NAME>
# Only support python 3+
# To update data just run: py -3 fetch.py
import urllib.request, json, os
path = os.path.dirname(os.path.abspath(__file__))
print('Working directory: '+path)
os.chdir(path)
os.makedirs('../json/', exist_ok=True)
langs=[{"url": "en","code": "en", "name": "English"}, {"url": "th... | StarcoderdataPython |
127391 | # -*- coding: utf-8 -*-
"""
# @file name : cross_entropy.py
# @author : JLChen
# @date : 2020-03-12
# @brief : cross_entropy
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class CrossEntropyLossFloat(nn.Module):
"""
浮点类型的CE实现,适用于标签是连续变量
(补充说明:PyTorch提供的CE Loss,只适用于标... | StarcoderdataPython |
3273247 | <gh_stars>0
"""ASN.1 definitions for fingerprint objects.
.. code-block:: text
Crypto-Conditions DEFINITIONS AUTOMATIC TAGS ::= BEGIN
-- Fingerprint Content
-- The PREIMAGE-SHA-256 condition fingerprint content is not DER
-- encoded
-- The fingerprint content is the preimage
... | StarcoderdataPython |
4971892 | # THIS FILE IS GENERATED FROM QISKIT_RUNTIME SETUP.PY
# pylint: disable=missing-module-docstring
short_version = '0.1.0'
version = '0.1.0.dev0+7f0e711'
release = False
| StarcoderdataPython |
3524132 | # -*- encoding: utf-8 -*-
# pylint: disable=E0203,E1101,C0111
"""
@file
@brief Runtime operator.
"""
import numpy
from ..shape_object import ShapeObject
from ._op import OpRun
from ._new_ops import OperatorSchema
class ComplexAbs(OpRun):
def __init__(self, onnx_node, desc=None, **options):
OpRun.__init__... | StarcoderdataPython |
6425943 | <reponame>Danielznn16/RoboticHand-in-KG
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import torch as pt
import importlib
import os
import sys
import numpy as np
from data_utils.ModelNetDataLoader import pc_normalize, ModelNetDataLoader
# In[2]:
model_name = 'pointnet2_cls_msg'
# device_name = 'cuda:0'
device_n... | StarcoderdataPython |
4872719 | <warning descr="Too few arguments for format string">"{} {}"</warning>.format(1)
<warning descr="Too few arguments for format string">'{}'</warning>.format() | StarcoderdataPython |
1761675 | <reponame>ninemoreminutes/doctorf
# Django REST Framework
from rest_framework import renderers
class BrowsableAPIRenderer(renderers.BrowsableAPIRenderer):
'''
Customizations to the default browsable API renderer for the raw data form.
'''
def get_context(self, data, accepted_media_type, renderer_cont... | StarcoderdataPython |
228660 | import numpy as np
# from pathos.multiprocessing import cpu_count
# from pathos.pools import ParallelPool as Pool
from multiprocessing import Pool,cpu_count
import libs.contact_inhibition_lib as lib #library for simulation routines
import libs.data as data
from structure.global_constants import *
import structure.initi... | StarcoderdataPython |
293353 | import numpy as np
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
from keras.models import Sequential, Model
from keras.layers import Dropout, Flatten, Dense, GlobalAveragePooling2D, Input
from keras.applications.inception_v3 import InceptionV3
from keras import optimizers
from keras.u... | StarcoderdataPython |
9687369 | <gh_stars>100-1000
#!/usr/bin/env python3
from distutils.core import setup
setup(name = "trimage",
version = "1.0.6",
description = "Trimage image compressor - A cross-platform tool for optimizing PNG and JPG files",
author = "<NAME>, <NAME>",
author_email = "<EMAIL>",
url = "http://trimage.org",... | StarcoderdataPython |
9671567 | <gh_stars>0
# -*- coding: utf-8 -*-
import os
import sys
import signal
import asyncio
import logging
import functools
from lin.accepter import Accepter
from lin.worker import Worker
logger = logging.getLogger(__name__)
class Manager:
BOOT_ERROR = 128
def __init__(self, connectors, config):
self.c... | StarcoderdataPython |
3225017 | <filename>powerfulseal/clouddrivers/open_stack_driver.py
# Copyright 2017 <NAME> L.P.
#
# 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
#
# U... | StarcoderdataPython |
8092836 | import numpy as np
import pandas as pd
from typing import Any, Union
def get_timestamp(value: Union[int, str]) -> Union[pd.Timestamp, None]:
if value is None or isinstance(value, pd.Timestamp):
return value
if isinstance(value, (int, np.integer)):
return pd.Timestamp(value, unit='s')
retu... | StarcoderdataPython |
11325663 | """Database helper functions for single database connectivity
Manage saved settings for Db2 connections
db_connect() - Connect using loaded/prompted credentials
db_connect_prompt() - Prompts for connection settings
db_connected() - Return connection status
db_connection() - Retur... | StarcoderdataPython |
74122 | <reponame>Samerodeh/data-structures-and-algorithms
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue(object):
def __init__(self, size):
self.queue = []
self.size = size
def enqueue(self, value):
'''This function adds an value to the r... | StarcoderdataPython |
4833116 | '''Faça um programa que leia uma frase e mostre:
Quantas vezes aparece a letra "a"
Qual a primeira posição que o "a" aparece
Qual a última posição que o "a" aparece'''
frase = input('Digite uma frase').strip()
fraseLow = frase.lower()
print(f'Sua frase possui {fraseLow.count("a")} "a"')
print(f'A posição em que o pri... | StarcoderdataPython |
196694 | <reponame>lgbouma/cdips-pipeline
# -*- coding: utf-8 -*-
'''
run
$ python TESS_ETE6_reduction.py --help
'''
from __future__ import division, print_function
import os, time
import matplotlib as mpl
mpl.use('AGG')
import numpy as np, pandas as pd, matplotlib.pyplot as plt
import aperturephot as ap, shared_variables as s... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.