id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1679876 | <reponame>hsclinical/leetcode
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalOrder(self, root: TreeNode) -> List[List[int]]:
if root ==... | StarcoderdataPython |
1742543 | #! /usr/bin/env python
# -*- coding: ISO-8859-15 -*-
#
# pkpgcounter : a generic Page Description Language parser
#
# (c) 2003, 2004, 2005, 2006, 2007 <NAME> <<EMAIL>>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free... | StarcoderdataPython |
1748550 | from distutils.core import setup
setup(
name='tojson',
version='0.1',
description='Python Convert HTML Document to JSON',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/Bezmehrabi/tojson.git',
license='LICENSE.txt',
install_requires=[
'bs4 >= 0.0.1',
'... | StarcoderdataPython |
1759244 | <gh_stars>0
import json
import csv
import time
from PageReader import PageReader
# Main class, loads config, runs the scrape, and handles scrape output
class SiteScraper:
# Config data loaded from JSON
config = None
# Raw page scraper results
results = {}
# Results after analysis (collation, key co... | StarcoderdataPython |
1758537 | <filename>test/test_course.py
from html import unescape
from textwrap import wrap
import unittest
from lib import *
class TestCourseClass(unittest.TestCase):
courses = []
def setUp(self):
with open('test/courses-fixture.json', 'r') as file:
data = json.load(file)
self.courses... | StarcoderdataPython |
1796655 | <gh_stars>0
'''
Prompt:
Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting
node. Note that the intersection is defined based on reference, not value. That is, if the kth
node of the first linked list is the exact same node (by reference) as the jth node of the second
linked l... | StarcoderdataPython |
1603669 | import numpy as np
import cv2 as cv
import argparse
from PIL import Image, ImageEnhance, ImageDraw
import matplotlib.pyplot as plt
import os
def ROI(frame):
#enhancer = ImageEnhance.Contrast(frame)
#img = enhancer.enhance(0.7)
face_classifier = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
... | StarcoderdataPython |
1750366 | <reponame>livlikwav/Algorithms<gh_stars>1-10
'''
<반만 Success>
Pypy3로 성공하였으나, Python3에서는 시간 초과이다.
<답안과 차이점>
다 비슷하고,
내가 실수한 점이 딱 하나 다른 것이
data(graph)를 갱신할 때,
문제에서 주어진 것처럼 다 끝나고 다시 다 2중 for문 돌면서 갱신하지 않아도 된다.
visited 되었기 때문에, 어짜피 다음 연합 찾을때는 탐색하지 않기 때문
<답안 메모>
답안 풀이는 매우 간결했다.
나처럼 여러 경우에 대한 고려가 없이 문제에서 설명한대로 bfs 구현하였다.
'''... | StarcoderdataPython |
163550 | from __future__ import absolute_import
from django.apps import apps
from django.core.management.base import BaseCommand, CommandError
import sys
from djipsum import __VERSION__
from djipsum.fields import DjipsumFields
class Command(BaseCommand):
help = 'To generate awesome lorem ipsum for your model!'
def ... | StarcoderdataPython |
3384224 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 11 22:58:58 2016
@author: yxl
"""
import numpy as np
def count_box(s1, s2, c, r):
box1c = slice(max(0, c), min(s1[1], c+s2[1]))
box1r = slice(max(0, r), min(s1[0], r+s2[0]))
box2c = slice(max(-c, 0), min(s2[1], s1[1]-c))
box2r = slice(max(-r, 0), min(s2[0... | StarcoderdataPython |
3386044 | import networkx as nx
import pandas as pd
import sys
import re
from UMAP_analysis.core import nearest_neighbor
filename = sys.argv[1]
m = re.match("networks/(?P<dataset>.*?)_similarity.*?.gml", filename)
dataset = m.groupdict()['dataset']
G = nx.read_gml(filename)
true_labels = pd.read_csv(f"data/intermediate/{datas... | StarcoderdataPython |
54605 | # -*- coding: utf-8 -*-
"""
Data Definition File
"""
import astropy.units as u
from astropy.coordinates import SkyCoord
from .coords import OsirisInstrumentFrame
from ..coords import AstrometricFrame
class SpectrographParameters(object):
"""Spectrograph parameters"""
def __init__(self, filter, scale, itime, ... | StarcoderdataPython |
4834654 | <reponame>mesaguy/ansible-hashicorp<filename>molecule/unconfigured/tests/test_nothing_installed.py
def test_base_directory_missing(host):
directory = host.file('/opt/hashicorp')
assert not directory.exists
| StarcoderdataPython |
3318772 | <filename>teraserver/python/modules/FlaskModule/Views/About.py
from flask.views import MethodView
from flask import render_template, request
from modules.LoginModule.LoginModule import user_multi_auth
from opentera.utils.TeraVersions import TeraVersions
class About(MethodView):
def __init__(self, *args, **kwargs... | StarcoderdataPython |
94499 |
import pandas as pd
# data from https://archive.ics.uci.edu/ml/datasets/Computer+Hardware
df = pd.read_csv('../data/machine.data', header=None)
df.columns = [
'VENDOR', 'MODEL', 'MYCT', 'MMIN', 'MMAX',
'CACH', 'CHMIN', 'CHMAX', 'PRP', 'ERP'
]
# print(df.head())
import matplotlib.pyplot as plt
import seaborn... | StarcoderdataPython |
3327953 | #-*- coding: utf-8 -*-
from resources.lib.handler.requestHandler import cRequestHandler
from resources.lib.parser import cParser
from resources.hosters.hoster import iHoster
from resources.lib.comaddon import dialog
from resources.lib.util import cUtil
import json
UA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:61.0) Gec... | StarcoderdataPython |
3277583 | <reponame>Slow-Rain/NPTEL-The-Joy-of-Computing-using-Python<gh_stars>10-100
l, b = map(int, input().split())
print(l*b, end="") | StarcoderdataPython |
4826103 | <reponame>abelgonzalez/ajustes<gh_stars>1-10
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.db import models
from django.contrib.auth.models import User
from persona.nomencladores.nomencladorPersona import Ubicacion as Ubicacion
from persona.nomencladores.nomencladorPersona import Naci... | StarcoderdataPython |
3251473 | <reponame>osoco/better-ways-of-thinking-about-software<filename>Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/lti_provider/tests/test_signature_validator.py<gh_stars>1-10
"""
Tests for the SignatureValidator class.
"""
from unittest.mock import patch
import ddt
from django... | StarcoderdataPython |
139830 | <filename>leetcode/0590_nary_tree_postorder_traversal.py
"""
Given an n-ary tree, return the postorder traversal of its nodes' values. Nary-Tree input serialization
is represented in their level order traversal, each group of children is separated by the null value
(See examples).
Follow up: Recursive solution is t... | StarcoderdataPython |
1783935 | from django.apps import AppConfig
class NoirConfig(AppConfig):
name = 'noir'
| StarcoderdataPython |
1639778 | """AyudaEnPython: https://www.facebook.com/groups/ayudapython
Para preparar aperitivos, un barman almacena en tres baldes distintas
medidas de vino, ginebra y jugo de limón, según la siguiente tabla:
+-------+------+---------+---------------+
| Balde | Vino | Ginebra | <NAME> |
+-------+------+---------+-... | StarcoderdataPython |
3328310 | import pandas as pd
import numpy as np
import os
import re
import sys
from os.path import join, expanduser
import json
import warnings
warnings.filterwarnings(action='ignore')
def load_json(path):
"""
Load json files
Parameters
----------
path: str
Filepath of json file
"""
w... | StarcoderdataPython |
3293720 | #!/usr/bin/env python3
"""Read a training log file and then dump out all rep maxes for all lifts.
My training log file is formatted like this:
2021-07-17
low-bar squat 5x290 3x325 0x365 3x345 3x325 3x310 5x290 5x270 20x250 FAIL
sumo deadlift 5x165 5x195 (3,5,7,4,6)x230 0x320
RDL (12,12,12)x175
kneeling ab wheel rol... | StarcoderdataPython |
159284 | <reponame>vshagur/stepik-selenium-final
from stepik_selenium_final.locators import ProductPageLocators
from stepik_selenium_final.pages import BasePage
class ProductPage(BasePage):
def __init__(self, browser, url):
super().__init__(browser, url)
self.title = None
self.price = None
def... | StarcoderdataPython |
4824313 | """AppConfig for webmail."""
from django.apps import AppConfig
class WebmailConfig(AppConfig):
"""App configuration."""
name = "modoboa_webmail"
verbose_name = "Simple webmail for Modoboa"
def ready(self):
from . import handlers
| StarcoderdataPython |
1641961 | <reponame>dattv/PyOptim<filename>GeneticAlgorithms.py
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import numpy as np
from utils.sort_utils import sort_ascent, sort_descent
class GA():
def __init__(self, init_pop, cost_func, go_min=True):
""... | StarcoderdataPython |
3356731 | """
Plugin annotation and partitioning. This determines according to a set of
rules which plugin to use for which operation.
"""
from __future__ import absolute_import, division, print_function
from collections import defaultdict
import datashape
from ..ir import FuncArg
from ...strategy import CKERNEL
from ....io.s... | StarcoderdataPython |
1605299 | import socket
import ustruct
import uasyncio as asyncio
import machine
import utime
# (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
NTP_DELTA = 3155673600
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
host = "pool.ntp.org"
async def time():
NTP_QUERY = bytearray(48)
... | StarcoderdataPython |
3292358 | import numpy as np
import librosa
# io utils
class ReadAudio:
def __init__(self, sr=None, mono=True, res_type='kaiser_best'):
'''
Read img
sr: float. None for native sampling rate
mono : bool. Convert signal to mono
res_type: str. resampy resamp... | StarcoderdataPython |
1739378 | import numpy
from assignment_2_3_4.config import Config
from assignment_2_3_4.line_searches import make_line_search, WolfeLineSearch
from assignment_2_3_4.optimizers import (
GradientDescentOptimizer,
HessianFreeNewtonOptimizer,
LBFGSOptimizer,
LassoOptimizer,
)
from assignment_2_3_4.oracles import Abs... | StarcoderdataPython |
1627102 | import xlrd
book = xlrd.open_workbook("StagingGroups Data.xlsx")
print("The number of worksheets is {0}".format(book.nsheets))
print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
#Group Number
print(sh.cell_value(0,0))
#Stage ... | StarcoderdataPython |
3210745 | <reponame>Nivdob/sandbox<gh_stars>0
#!/usr/bin/python
import dnaseq
import bm_preproc
import kmer_index
mystery_virus_reads, _ = dnaseq.read_fastq("ads1_week4_reads.fq")
mystery_virus_genom = dnaseq.assemble(mystery_virus_reads, 30)
def question_01():
ss = ["CCT", "CTT", "TGC", "TGG", "GAT", "ATT"]
s, _ = dnaseq.s... | StarcoderdataPython |
1718683 | __all__ = ["Barb"]
from .barb import Barb
| StarcoderdataPython |
112847 | <filename>backend/run_dace.py<gh_stars>0
# Copyright 2020-2021 ETH Zurich and the DaCe-VSCode authors.
# All rights reserved.
import aenum
from argparse import ArgumentParser
import ast, astunparse
import dace
from dace.sdfg import propagation
from dace.symbolic import pystr_to_symbolic
from dace.libraries.blas import... | StarcoderdataPython |
197162 |
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,SubmitField,BooleanField,SubmitField,TextAreaField,RadioField
from wtforms.validators import Required,Email,EqualTo
from wtforms import ValidationError
class PitchForm(FlaskForm):
title = StringField('Title', validators=[Required()])
de... | StarcoderdataPython |
3364742 | <reponame>ragibson/ModularityPruning
# Generates figures 5.3, 5.4, 5.5, and 5.6
from random import random, randint
from collections import Counter
import igraph as ig
import os
from time import time
import pickle
import matplotlib.pyplot as plt
import numpy as np
from modularitypruning.champ_utilities import CHAMP_3D
... | StarcoderdataPython |
3306970 | <filename>papiea-sdk/python/e2e_tests/sdk_test.py
import asyncio
import pytest
import time
import e2e_tests as papiea_test
import e2e_tests.provider_setup as provider
import e2e_tests.utils as test_utils
from papiea.core import AttributeDict, IntentfulStatus, Spec
# Includes all the entity ops related tests
class T... | StarcoderdataPython |
3214584 | <reponame>splintercat/cerberus-python-client
"""
Copyright 2020-present Nike, Inc.
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 |
1680796 | # coding=utf-8
from __future__ import division, absolute_import, print_function, unicode_literals
from urllib.parse import urljoin
import ssl
import logging
import requests
import websockets
class IRCCloudHTTPError(Exception):
pass
class RateLimitedError(Exception):
pass
class IRCCloudHTTPClient(object):
... | StarcoderdataPython |
3304590 | <filename>blog/admin.py
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
fields = ['author', 'date_posted', 'title', 'content']
list_display = ['title', 'author', 'date_posted']
list_filter = ['author', 'date_posted']
search_fields = ['content', 'title']
a... | StarcoderdataPython |
1778486 | import asyncio
import random
from utilities import *
async def twinkle(lights):
background_color = rgb(32, 32, 255)
twinkle_colors = [pretty, warm_white, blue_snowy, good_purple]
for light in lights:
light.set_state(background_color)
states = [None for light in lights]
time_step = 0.1
... | StarcoderdataPython |
1780766 | <reponame>KellyGriffin/kalc
import pytest
import yaml
from kalc.model.kubernetes import KubernetesCluster
from kalc.model.kinds.Pod import Pod
from kalc.model.kinds.Node import Node
from kalc.model.kinds.Service import Service
from kalc.model.kinds.Deployment import Deployment
from kalc.model.kinds.PriorityClass import... | StarcoderdataPython |
3206242 | from players.player import *
class FirstBot(Player):
def select_move(self, game, player) -> int:
"""
If the bot has winning move: play it. Else play the first possible move
"""
pos = self.has_direct_winning_move(game, player)
if pos is not None:
return pos
... | StarcoderdataPython |
3281877 | #!/usr/bin/env python3
import rospy
import time
from numpy import around
from geometry_msgs.msg import Wrench
def am_die():
print('die')
if __name__ == '__main__':
rospy.init_node('keyboard_pub')
p = rospy.Publisher('/nautilus/thruster_manager/input', Wrench, queue_size=10)
w = Wrench()
print('c... | StarcoderdataPython |
119198 | <reponame>pinax/pinax-documents
from django.template import Library
from django.utils.html import conditional_escape
from ..utils import convert_bytes
register = Library()
@register.filter
def can_share(member, user):
if member is None:
return False
return member.can_share(user)
@register.filter
d... | StarcoderdataPython |
3328001 | <filename>redis-cb/cb.py
#
# Simple sample module showing a way to register a callback
# dynamically. This is the same as in ncc-establish-subscription.py.
#
from lxml import etree
import json
import jxmlease
import redis
import time
#
# the redis connection
#
conn = redis.Redis()
#
# log an "event"
#
def log_items... | StarcoderdataPython |
193447 | <gh_stars>1000+
"""Small NumPy datasets for debugging/testing."""
| StarcoderdataPython |
3376081 | <filename>src/win/bootDeviceWin_FDCB.py
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Oct 26 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
##########################################... | StarcoderdataPython |
149163 | <filename>ref.neo/sys/linux/process.py
#!/usr/bin/env python
# process stdin into an M4 macro definition file
# recognize three keyword qgl qwgl qglX
#
# output
# global macros keep track of the three intervals for function types:
# gl_start gl_end wgl_start wgl_end glX_start glX_end
# NOTE: will we need similar thing ... | StarcoderdataPython |
3206461 |
import os
import sys
## if you got module not found errors, uncomment these. PyCharm IDE does not need it.
# add .. and . to path, depending on what cwd was when python process was created, one of these might help find librf
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('.'))
#print... | StarcoderdataPython |
1759111 | # Refs:
# "Serial Wire Debug and the CoreSightTM Debug and Trace Architecture"
# Note: ACK is transmitted LSB first, so patterns
# below are reversed comparing to ARMDIv5 diagrams, but matches
# values used in text (sec. 5.4.2 and on)
ACK_OK = 0b001
ACK_WAIT = 0b010
ACK_FAULT = 0b100
# Additional code not defined in A... | StarcoderdataPython |
3206643 |
from django.contrib.auth import views as auth_views
from django.urls import path
from web import views
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('register/', views.RegisterView.as_view(), name='register'),
path('login/', views.LoginView.as_view(), name='login'),
path('logout/', ... | StarcoderdataPython |
3304577 | '''
diamond2counts.py - count alignments to reference
===================================================
:Author: <NAME>
:Release: $Id$
:Date: |today|
:Tags: Python
Purpose
-------
Count the number of alignments to each reference in outfmt6.
Counts are based on various options specified by --method.
best Th... | StarcoderdataPython |
3268398 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 1 20:16:49 2018
@author: CPEGM
"""
# Petites corrections par rapport au programme donné dans le livre
import tkinter as tk
from random import randrange
def drawline():
" Tracé d'une ligne dans le canvas 1"
global x1, y1, x2, y2, coul
can1.create_line(x1, y1,... | StarcoderdataPython |
1695898 | from skopt import Optimizer
import numpy as np
def dbtime(p1,p2,p3,p4,p5,p6,p7,p8,p9,p10):
return np.sin(p1)*10+np.sin(p2)*5+np.sin(p3)+np.sin(p4)+np.sin(p5)+np.sin(p6)+np.sin(p7)+np.sin(p8)+np.sin(p9)+np.sin(p10)+3*8+10+5
search_space = {
'param_1': (0.0, 6.0),
'param_2': (0.0, 6.0),
'param_3'... | StarcoderdataPython |
3325385 | <reponame>Richert/BrainNetworks<filename>CMC/analysis/EIC_efficacies.py
from pyrates.utility import plot_timeseries, grid_search, plot_psd, plot_connectivity, create_cmap
import numpy as np
import matplotlib.pyplot as plt
__author__ = "<NAME>"
__status__ = "Development"
# parameters
dt = 1e-5
T = 5.
inp = 3. + np.ra... | StarcoderdataPython |
122591 | <filename>mve/learner.py<gh_stars>1-10
"""
This module defines the learner interface.
"""
class Learner:
"""
A learner ingests data, manipulates internal state by learning off this
data, supplies agents for taking further actions, and provides an opaque
interface to internal evaluation.
"""
d... | StarcoderdataPython |
3214731 | <reponame>arthurhero/Swin-Transformer
import math
import torch
import torch.nn.functional as F
import numpy as np
import cv2
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
import matplotlib.pyplot as plt
from torch_scatter import scatter_mean
imgs = torch.load('attns/images0.pt', map_loca... | StarcoderdataPython |
1751521 | <reponame>Nuuttu/Koulu_PythonWeppiAppi
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms.ext.sqlalchemy.orm import model_form
app=Flask(__name__)
app.secret_key = "<KEY>"
db = SQLAlchemy(app)
class Comment(db.Model):
id = db.Column(db.In... | StarcoderdataPython |
1727935 | <filename>junos_rest/actions.py<gh_stars>1-10
"""Supported Interactions with JunOS Devices."""
# Standard Library Imports
import ujson
# Project Imports
from junos_rest.connection import Connection
from junos_rest.constants import CONFIG_JSON
from junos_rest.util import build_config
from junos_rest.util import find_d... | StarcoderdataPython |
155630 | <gh_stars>0
import tensorflow as tf
class SamplingGrid(tf.keras.layers.Layer):
def __init__(self, height, width):
super(SamplingGrid, self).__init__()
self.height = height
self.width = width
# create normalized 2D grid
x = tf.linspace(-1.0, 1.0, width)
y = t... | StarcoderdataPython |
1694190 | <reponame>llaske/sugarizer-deployment-tool-desktop<filename>adb/windows/platform-tools/systrace/catapult/telemetry/third_party/pyfakefs/pyfakefs/fake_filesystem_unittest_test.py
#! /usr/bin/env python
#
# Copyright 2014 Altera Corporation. All Rights Reserved.
# Author: <NAME>
#
# Licensed under the Apache License, Ver... | StarcoderdataPython |
3207397 | #!/usr/bin/env python
import socket
host1 = socket.gethostbyname('gitpush.ml')
# host1 = socket.gethostbyname('pythonforbeginners.com')
# host2 = socket.gethostbyname('www.163.com')
print host1
# print (host1, host2)
| StarcoderdataPython |
3322584 | """
Copyright Government of Canada 2020
Written by:
<NAME>
University of Manitoba
National Microbiology Laboratory, Public Health Agency of Canada
<NAME>
National Microbiology Laboratory, Public Health Agency of Canada
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this ... | StarcoderdataPython |
167789 | <reponame>jonathanHuwP/CrystalGrowthTracker
# -*- coding: utf-8 -*-
'''
Created on Tue December 08 2020
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
Un... | StarcoderdataPython |
1792572 | <gh_stars>1-10
# iterative solution
def sumOfNumbersIterative(number):
sum = 0
for item in range(number + 1):
sum += item
return sum
print(sumOfNumbersIterative(5))
# non-iterative solution
def sumOfNumbersNonIterative(number):
return number * (number + 1) / 2
print(sumOfNumbersNonIterative... | StarcoderdataPython |
3269629 | <filename>sugar_crm/models.py<gh_stars>0
from sqlalchemy import CHAR, Column, Date, DateTime, Float, Index, String, Table, Text, Time, text
from sqlalchemy.dialects.mysql import BIGINT, INTEGER, LONGTEXT, SMALLINT, TINYINT
from sqlalchemy.ext.declarative import declarative_base
from .database import Session_crm
Base... | StarcoderdataPython |
52376 | <reponame>eggfly/pycomet<gh_stars>0
#! /usr/bin/env python3
from conf import HOST
import urllib.request
import time
URL_ASYNC = HOST + "async"
def get_loop_url(channel_id):
return "%s/loop/%s" % (HOST, channel_id)
def request(url):
t = time.time()
while True:
print("before open")
fp = u... | StarcoderdataPython |
1788114 | import configparser
import os
import logging.config
import pandas as pd
import seaborn as sns
from .catalogs import Catalogs
from .equipment import Equipment
from .notify import Notify
from .observations import Observation
from .place import Place
from .utils import Utils
from .weather import Weather
# Init config
c... | StarcoderdataPython |
107875 | <reponame>vincentlaucsb/sqlify
from .parser import get_tables_from_file as from_file, \
get_tables_from_url as from_url, \
get_tables_from_string as from_string | StarcoderdataPython |
78394 | <filename>scripts/ckp_average.py<gh_stars>10-100
import argparse
import functools
from state import *
def average_parameters(states):
models = [s['model'] for s in states]
for k, v in models[0].items():
vs = [model['k'] for model in models[1:]] + [v]
v = functools.reduce(torch.add, vs)
... | StarcoderdataPython |
94289 | <gh_stars>1000+
from color import Color
from itertools import product
from geometry import Vector
import random
class SceneObject:
def draw(self, image):
raise NotImplementedError("Undefined method")
class Shape(SceneObject):
def __init__(self, color=None):
self.color = color if color is not N... | StarcoderdataPython |
1762115 | <reponame>chuanhao01/Python_Expression_Evaluator<filename>src/basic/expression_evaluator/nodes/__init__.py
from .ast import AST
from .binary_op_node import BinaryOp_Node
from .number_node import Number_Node
from .node_visitor import NodeVisitor | StarcoderdataPython |
1785146 | <reponame>damm89/django-camunda<gh_stars>1-10
"""
Public Python API to interact with Activiti.
"""
from typing import Any, Dict, Iterable, List, Optional
import requests
from .camunda_models import ProcessDefinition, Task, factory
from .client import get_client
from .types import CamundaId, ProcessVariables
from .uti... | StarcoderdataPython |
1754228 | <reponame>KarrLab/Kinetic-Datanator
import pymongo
from bson.binary import Binary
import pickle
from datanator_query_python.util import mongo_util
import datanator.config.core
from pathlib import Path
def main():
db = 'test'
collection_str = 'brenda_constants'
username = datanator.config.core.get_config()... | StarcoderdataPython |
4812364 | from pathlib import Path
from datetime import datetime, timedelta
from dateutil.parser import parse
import numpy as np
from pandas import read_csv
from xarray import DataArray
def read_mgs_occultation(imgfn):
imgfn = Path(imgfn).expanduser()
lblfn = imgfn.with_suffix(".lbl")
srtfn = imgfn.with_suffix(".s... | StarcoderdataPython |
3359874 | # -*- coding: utf-8 -*-
"""
Tests for various autodetection magics for CSV imports
"""
import codecs
from odoo.tests import common
class ImportCase(common.TransactionCase):
def _make_import(self, contents):
return self.env['base_import.import'].create({
'res_model': 'base_import.tests.models.c... | StarcoderdataPython |
187754 | <reponame>brauliotegui/DEMAND
"""
this is an app for the dashboard running a linear regression
model to estimate the demand of bike rentals for Bike Share in Washington D.C.
"""
import pandas as pd
from scipy import stats
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import P... | StarcoderdataPython |
3630 | from pylab import *
from numpy import *
from numpy.linalg import solve
from scipy.integrate import odeint
from scipy.stats import norm, uniform, beta
from scipy.special import jacobi
a = 0.0
b = 3.0
theta=1.0
sigma=sqrt(theta/(2*(a+b+2)))
tscale = 0.05
invariant_distribution = poly1d( [-1 for x in range(int(a))], ... | StarcoderdataPython |
26276 | <gh_stars>0
from accent_analyser.rules.IpaRule import IpaRule
def replace(word: str):
return word.replace("v", "w")
class VoicedFricative1(IpaRule):
def __init__(self, likelihood=0.51):
super().__init__(likelihood)
self.name = "Voiced Fricative: [w] instead of /v/"
def _convert_core(self, words: list... | StarcoderdataPython |
165950 | <reponame>kkkkv/tgnms
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import json
from datetime import datetime
from functools import partial
from typing import Any
from aiohttp import web
from sqlalchemy import select
from tglib.clients import APIServiceClient, MySQLClient
from .model... | StarcoderdataPython |
1631751 | <filename>tests/mxnet/test_hook_save_config.py<gh_stars>100-1000
# Standard Library
import os
import shutil
from datetime import datetime
# First Party
from smdebug.mxnet import SaveConfig
from smdebug.mxnet.hook import Hook as t_hook
# Local
from .mnist_gluon_model import run_mnist_gluon_model
def test_save_config... | StarcoderdataPython |
166355 | <filename>majority-element-ii/majority_element_ii.py<gh_stars>0
from typing import List
class Solution:
def majority_element(self, nums: List[int]) -> List[int]:
size = len(nums)
times = size // 3
counter = {}
result = []
for num in nums:
counter[num] = counter.... | StarcoderdataPython |
3224862 | <reponame>leipzig/gatk-sv<gh_stars>10-100
import os
import argparse
import numpy
import random
def filein_readin(filein, file_size):
fin = os.popen(r'''zcat %s''' % (filein))
header = []
header2 = []
info = []
for line in fin:
pin = line.strip().split()
if pin[0][:2] == '##':
... | StarcoderdataPython |
4821649 | <gh_stars>0
from .formatters import *
from .scraper import *
from .crawler import Crawler
| StarcoderdataPython |
33748 | """
:mod: `kanka.utils` - Helper functions
"""
from datetime import datetime
from requests_toolbelt.sessions import BaseUrlSession
from dacite import from_dict, Config
from .exceptions import KankaAPIError
API_BASE_ENDPOINT = 'https://kanka.io/api/1.0/'
class KankaSession(BaseUrlSession):
""" Store session data.... | StarcoderdataPython |
3385877 | from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(n_jobs=-1)
| StarcoderdataPython |
3395314 | <reponame>patryk-tech/summer-code-jam-2020
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser
admin.site.register(CustomUser, UserAdmin)
| StarcoderdataPython |
92673 | <filename>1.0-comenzando/ejercicios_alumnos/LeoGuanco/ejercicio7.py
aux = 0
num = int(input("Ingrese un numero entero positivo: "))
opc = int(input("1- Sumatoria, 2-Factorial: "))
if opc == 1:
for x in range(0,num+1):
aux = aux + x
print (aux)
elif opc == 2:
if num == 0:
print("1")
elif num > 0:
aux = 1
for... | StarcoderdataPython |
1716151 | # Generated by Django 2.0.7 on 2018-07-28 16:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('order', '0007_orderlist_pay_method'),
]
operations = [
migrations.AddField(
model_name='orderli... | StarcoderdataPython |
1627647 | <reponame>MrCubanfrog/NorDB
"""
This module contains the NordicRoot class and it's methods.
Functions and Classes
---------------------
"""
class NordicRoot:
"""
NordicRoot class.
"""
def __init__(self, root_id=-1, events = None):
self.events = []
self.root_id = root_id
if even... | StarcoderdataPython |
3303604 | <gh_stars>100-1000
from fastapi import APIRouter, Depends
from fastapi_admin.depends import get_current_admin
from .resources import router as resources_router
router = APIRouter()
router.include_router(resources_router, dependencies=[Depends(get_current_admin)])
| StarcoderdataPython |
1798486 | import sys
from PyQt5.QtWidgets import QWidget, QApplication
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = QWidget()
widget.setWindowTitle("Test Window")
widget.show()
sys.exit(app.exec_())
| StarcoderdataPython |
33900 | from typing import Tuple
class BaseTimer:
"""
A timer controls the time passed into the the render function.
This can be used in creative ways to control the current time
such as basing it on current location in an audio file.
All methods must be implemented.
"""
@property
... | StarcoderdataPython |
3318602 | <reponame>timgates42/tweetmotif<gh_stars>10-100
import sys
from collections import defaultdict
import twokenize
import bigrams
import lang_model
class LinkedCorpus:
" Hold tweets & indexes .. that is, ngrams are 'linked' to their tweets. "
def __init__(self):
self.model = lang_model.LocalLM()
self.index = ... | StarcoderdataPython |
49750 | __version__ = '0.1.73'
_MODEL_DIR = 'outputs'
| StarcoderdataPython |
176309 | <filename>src/bio2bel/sources/go.py
# -*- coding: utf-8 -*-
"""Tools for gene ontology."""
from typing import Optional
import pandas as pd
import pyobo
import requests
from protmapper.uniprot_client import get_hgnc_id
import pybel
__all__ = [
'enrich_graph',
]
URL = 'http://api.geneontology.org/api/bioentity... | StarcoderdataPython |
1702940 | <reponame>BA7JCM/grr
#!/usr/bin/env python
"""Classes for exporting memory-related data."""
from typing import Iterator
from grr_response_core.lib.rdfvalues import memory as rdf_memory
from grr_response_core.lib.rdfvalues import structs as rdf_structs
from grr_response_proto import export_pb2
from grr_response_server... | StarcoderdataPython |
3271317 | <filename>hic3defdr/util/filtering.py
import numpy as np
import scipy.sparse as sparse
from hic3defdr.util.banded_matrix import BandedMatrix
def filter_sparse_rows_count(matrix, min_nnz=25, k=300):
"""
Wipes the sparse bins (both rows and columns) of a matrix, where "sparse"
means that the bin has less t... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.