id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
107251
<reponame>LaudateCorpus1/llvm-project #!/usr/bin/env python #===- cppreference_parser.py - ------------------------------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0...
StarcoderdataPython
3397489
from ._graph import *
StarcoderdataPython
3229241
<reponame>OrangeUtan/MCMetagen import pytest from mcanitexgen.animation.parser import Duration, State, StateAction, Timeframe, Weight class Test_call: @pytest.mark.parametrize( "args, expected_action", [ ({}, StateAction(State(0), Duration(1))), ({"weight": 2}, StateAction...
StarcoderdataPython
1608916
import re import pandas LIBE_STATS_FIELDS = ["Worker", ": sim_id", ": sim Time:", "Start:", "End:", "Status:", "\n"] DATAFRAME_COLUMNS = ["worker", "sim_id", "time", "start", "end", "status"] LIBE_STATS_PATTERN = '(?<={})(.+?)(?={})' def create_empty_persis_info(libE_specs): """ Create `persis_info` for libE...
StarcoderdataPython
1748222
<filename>sample/usage/sample/how_to_use_init_answers.py # Copyright 2022 Recruit Co., Ltd. # # 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
1734703
<filename>tests/unit/test_persistent_routes.py import pytest from app.models import Resource, Language, Category from tests.conftest import module_client, module_db from configs import PaginatorConfig # TODO: We need negative unit tests (what happens when bad data is sent) def test_get_resources(module_client, module...
StarcoderdataPython
35272
<gh_stars>10-100 from typing import Any, Dict, Generator, List, Optional import torch from torch import nn, optim from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from probnmn.config import Config from probnmn.utils.checkpointing import CheckpointManager class _Trainer(object): r""...
StarcoderdataPython
34546
""" Data Transfer Objects """ from pydantic import BaseModel class WarehouseDto(BaseModel): name: str # this is our unique identifier! location: str capacity: int
StarcoderdataPython
58563
<reponame>toddnguyen47/utility-files import uuid import hashlib import getpass import argparse import sys hashed_password_file = "hashedPassword.txt" def hash_password(password: str): # uuid is used to generate a random number salt = uuid.uuid4().hex return hashlib.sha256(salt.encode() + password.encode(...
StarcoderdataPython
1749295
<reponame>apcarrik/kaggle def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaur...
StarcoderdataPython
103010
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( type='PoseDetDetector', pretrained='pretrained/dla34-ba72cf86.pth', # pretrained='open-mmlab://msra/hrnetv2_w32', backbone=dict( type='DLA', return_levels=True, levels=[1, 1, 1, 2, 2, 1], channel...
StarcoderdataPython
1726811
<gh_stars>100-1000 #No Trig paths defined import FWCore.ParameterSet.Config as cms process = cms.Process("PROD") import FWCore.Framework.test.cmsExceptionsFatalOption_cff process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True), Rethrow = FWCore.Framework.test.cmsExceptionsFatalOption_cff...
StarcoderdataPython
1793867
<filename>ahkpy/exceptions.py class Error(Exception): """The runtime error that was raised in the AutoHotkey. Contains the following attributes: .. attribute:: message The error message. .. attribute:: what The name of the command, function or label which was executing or about...
StarcoderdataPython
3322537
<gh_stars>0 # -*- coding: utf-8 -*- """? :copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function from rssynergia.base_diagnostics import options import math import matplotlib.pyplo...
StarcoderdataPython
101548
<gh_stars>0 import os import unittest from pynwb.form.data_utils import DataChunkIterator from pynwb.form.backends.hdf5.h5tools import HDF5IO from pynwb.form.build import DatasetBuilder import h5py import tempfile import numpy as np class H5IOTest(unittest.TestCase): """Tests for h5tools IO tools""" def se...
StarcoderdataPython
3322032
cursor1=conn.cursor(); cursor1.execute("SELECT department_id,department_name "+ " FROM departments") allrows=cursor1.fetchall() for row in allrows: print "%6d %-20s" % (row[0],row[1]) cursor1.close()
StarcoderdataPython
1689605
# Generated by Django 3.1.3 on 2020-12-07 21:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("peeringdb", "0012_peerrecord_visible"), ] def flush_peeringdb_tables(apps, schema_editor): apps.get_model("peeringdb", "Contact").objects.all().dele...
StarcoderdataPython
91235
import unittest from torchvision import transforms # (Ugly) Path hack. #TODO - get rid of it import sys, os; sys.path.insert(0, os.path.abspath('.')) from dataprocessor import MyDatasetDoc from dataprocessor.dataset import MyDatasetCorner, SmartDoc, SmartDocCorner from utils import draw_circle_pil, get_concat_h clas...
StarcoderdataPython
3236258
from __future__ import absolute_import from __future__ import unicode_literals from django.conf.urls import url from custom.m4change.views import update_service_status urlpatterns = [ url(r'^update_service_status/$', update_service_status, name='update_service_status'), ]
StarcoderdataPython
49814
<reponame>homeostasie/petits-pedestres # On est sur la première case. # On a un grain de blé sur la première case. # On a un grain de blé sur l'échéquier. # Nombre de grain de blé par case. # case est un nombre entier. case = 1 # Nombre de grain blé au total sur l'échiquier. # blé est un nombre entier. ble = 1 # Coe...
StarcoderdataPython
3233658
<reponame>nparkstar/nauta # # Copyright (c) 2019 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 # # Unless required by a...
StarcoderdataPython
3286244
from bakery.views import BuildableTemplateView from django.core.urlresolvers import reverse class MooView(BuildableTemplateView): template_name = "moo.html" @property def build_path(cls): return '/'.join((reverse('moo')[1:], "index.html",))
StarcoderdataPython
4801862
from collections import OrderedDict from rest_framework import status from django.core.urlresolvers import reverse from rest_framework.test import APITestCase from apps.common.tests import BaseTestCase, GetResponseMixin from apps.app.models import App from apps.auth.models import User class GrayTasksTests(BaseTestCas...
StarcoderdataPython
172457
"""https://code.google.com/codejam/contest/10284486/dashboard#s=p1&a=1""" def main(): T = int(input()) for i in range(1, T + 1): N, K, P = (int(s) for s in input().split()) A = [] B = [] C = [] for _ in range(K): a, b, c = (int(s) for s in input().split()) ...
StarcoderdataPython
4804996
import random as rand import matplotlib.pyplot as plt #initial position current = 0 # burst parameters m = [1, 10, 100] #burst length num_bursts = [1000, 100, 10] #number of bursts #total_length = m * num_bursts total_length = 1000 #bias parameters walk_probabilities = [.5, .51, .6, .7, .8] #unbiased/biase...
StarcoderdataPython
1657544
# -*- coding: utf-8 -*- from __future__ import unicode_literals # import default models from django-edw to materialize them from edw.models.defaults import mapping from edw.models.defaults.customer import Customer from edw.models.defaults.term import Term from edw.models.defaults.data_mart import DataMart from todo...
StarcoderdataPython
1712334
<filename>hotword.py import snowboydecoder import sys import signal import os.path class hotword: def __init__(self): self.interrupted = False self.model = ''.join([os.path.dirname(__file__), '/HARU.pmdl']) def signal_handler(self, signal, frame): self.interrupted = True def inter...
StarcoderdataPython
1731054
#!/usr/bin/env python3 # coding=utf-8 from __future__ import print_function import os import click from importlib.machinery import SourceFileLoader from inspect import getmembers from absl import logging from .test import cli as cli_test from .workflow import cli as cli_workflow from .server import cli as cli_server ...
StarcoderdataPython
3309138
from os import listdir from lxml import etree import json import time import numpy as np from scipy.stats import ttest_ind xmlPath = 'XML/' jsonPath = 'JSON/' def testBatchXML(): startTime = time.time() for file in listdir(xmlPath): with open(xmlPath+file, 'r') as xmlFile: xmlString = bytes(xml...
StarcoderdataPython
1784348
{ "targets": [ { "target_name": "Engine", "type": "none", "configurations": { "Debug": {}, "Release": {} }, "all_dependent_settings": { "include_dirs": [ "Inc" ] }, "direct_dependent_settings": { "conditions": [ ["OS == 'linux'", { "libraries": [ "-lEngine" ] }],...
StarcoderdataPython
32204
<gh_stars>10-100 """Views for Django Rest Framework Session Endpoint extension.""" from django.contrib.auth import login, logout from rest_framework import parsers, renderers from rest_framework.authtoken.serializers import AuthTokenSerializer from rest_framework.response import Response from rest_framework.views imp...
StarcoderdataPython
113601
<filename>scripts/extract_single_mode_races.py # -*- coding=UTF-8 -*- # pyright: strict """. """ if True: import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) from typing import Iterator, Text, Tuple import sqlite3 import argparse import os import contextlib from auto_der...
StarcoderdataPython
1710079
<gh_stars>1-10 import datetime import json import os import time import snap from db_interface import get_edge_number, get_all id_pkg_dict = {} def get_id_from_package(graph, package): node_id = id_pkg_dict.get(package, -1) if node_id == -1: node_id = graph.AddNode(-1) id_pkg_dict[package] ...
StarcoderdataPython
3304032
<reponame>cetinibs/vercel from flask import Flask, Response, request app = Flask(__name__) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return Response(request.full_path, mimetype="text/plain") if __name__ == '__main__': app.run(debug=True, port=8002)
StarcoderdataPython
4804123
<gh_stars>10-100 import json import os from urllib import request, parse THRESHOLD = 3000000000000000000 # 3 ETH FAUCET_ADDRESS = os.environ['FAUCET_ADDRESS'] INFURA_API_TOKEN = os.environ['INFURA_API_TOKEN'] GITHUB_BOT_TOKEN = os.environ['GITHUB_BOT_TOKEN'] def get_faucet_balance(): url = f'https://rinkeby.infur...
StarcoderdataPython
3360226
<reponame>zoho/zohocrm-python-sdk-2.0 from abc import ABC, abstractmethod class DeletedRecordsHandler(ABC): def __init__(self): """Creates an instance of DeletedRecordsHandler""" pass
StarcoderdataPython
147138
<reponame>lorenanda/Supermarket_MCMC_simulation<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Customer class that simulates the paths of new customers in the supermarket. """ import time import numpy as np import pandas as pd import cv2 import astar as at from animation_template import SupermarketMap...
StarcoderdataPython
3226953
import sqlite3 import logging from weight_unit import WeightUnit class Database: weight_units = [] def __init__(self, path): self.db = sqlite3.connect(path) cursor = self.db.cursor() for row in cursor.execute('SELECT id, name, language_id FROM nutrition_weightunit'): self....
StarcoderdataPython
1601115
<filename>lexer_token_map.py # Map generic token type string to STC lexer constants. # The entry for STC_LEX_NULL is a template containing all possible token types. from wx import stc lexer_token_description = { "assembly": "Assembly Code", "character": "Character", "comment": "Block Comment",...
StarcoderdataPython
4821615
""" The main functionality for the Telegram bot """ from libdev.cfg import cfg from libdev.gen import generate from libdev.aws import upload_file from lib._variables import ( languages, languages_chosen, tokens, user_ids, user_logins, user_statuses, user_names, user_titles, ) from lib._api import auth, api fr...
StarcoderdataPython
1684392
<filename>plotting.py from matplotlib import pyplot as plt from matplotlib.patches import Circle import matplotlib.lines as lines from math import sin from math import cos from math import radians #--- FUNCTIONS ----------------------------------------------------------------+ def plot_organism(x1, y1, theta, ax): ...
StarcoderdataPython
1676984
<reponame>crappyoats/eclipse_vision # <NAME> # Illinois State Geological Survey, University of Illinois # 2015-05-31 from __future__ import print_function from PRTEntry import PRTEntry from collections import defaultdict from tqdm import tqdm import sys class PRTController(object): """class for parsing PRT file ...
StarcoderdataPython
101614
''' prep_dev_notebook: pred_newshapes_dev: Runs against new_shapes ''' import os import sys import random import math import re import gc import time import numpy as np import cv2 import matplotlib import matplotlib.pyplot as plt import tensorflow as tf import keras import keras.backend as KB import mrcnn.model_mod ...
StarcoderdataPython
4046
# Generated by Django 3.0.3 on 2020-03-24 09:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('exercises', '0018_photo_file'), ] operations = [ migrations.CreateModel( na...
StarcoderdataPython
1693417
# Uses Python3 # Greatest divisor common import sys def GCDNaive(a, b): best = 0 if(b == 0 or a == 0): return 0 if(b > a): [a, b] = [b, a] for i in range(1, a + 1): if(a % i == 0 and b % i == 0): best = i return best # Euclidean Algorithm def EuclideanGCD(a, b):...
StarcoderdataPython
18957
""" Code for working with data. In-memory format (as a list): - board: Tensor (8, 8, 2) [bool; one-hot] - move: Tensor (64,) [bool; one-hot] - value: Tensor () [float32] On-disk format (to save space and quicken loading): - board: int64 - move: int64 - value: float32 """ from typing import Dict, Tuple import ...
StarcoderdataPython
3263889
palavras = ('Curso', 'Video', 'Internet', 'Gratis', 'Futuro', 'Eeeeduardooooooo') for p in palavras: print(f'\nNa palavra {p.upper():_^12} temos as vogais:', end=' ') for letra in p: if letra.lower() in 'aeiou': print(letra.lower(), end=' ')
StarcoderdataPython
1718679
import logging from types import MethodType from assembly_line.expections import AssemblyLineDataHelperNotReturnedError from assembly_line.data_helper import DataHelper logger = logging.getLogger(__name__) def _do_pre_process(this, data_helper): if hasattr(this, 'pre_process'): res = this.pre_process(da...
StarcoderdataPython
3279359
<reponame>rahulkmr/cookiecutter-flask<filename>{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/settings.py<gh_stars>0 """ Application configuration. Most configuration are set via environment variables. Use a .env file in the project root to change configuration. """ from environs import Env env = Env() e...
StarcoderdataPython
1655908
<reponame>cfc603/coming-soon<gh_stars>0 from unittest.mock import Mock, patch from django.test import TestCase from model_bakery import baker from .models import Entry from .views import EntryCreate class EntryTest(TestCase): def test_str(self): # setup entry = baker.make(Entry, email="<EMAIL>...
StarcoderdataPython
49910
<reponame>mgbin088/vaex<gh_stars>1-10 __version__ = '0.7.0' __version_tuple__ = (0, 7, 0)
StarcoderdataPython
3338970
<reponame>lxl0928/learning_python<filename>flask/19_user_authentication_1/app/auth/__init__.py #! usr/bin/python3 # -*- coding: utf-8 -*- from flask import Blueprint auth = Blueprint('auth', __name__) from . import views
StarcoderdataPython
1606406
"""Support for Rointe Climate.""" from __future__ import annotations from datetime import timedelta import logging import async_timeout from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESE...
StarcoderdataPython
3234955
from os import mkdir, walk, remove from os.path import exists, join as joinpath from pickle import PicklingError, UnpicklingError from collections import namedtuple from redlib.api.py23 import pickledump, pickleload from . import const AutocompInfo = namedtuple('AutocompInfo', ['command', 'access', 'version']) c...
StarcoderdataPython
55809
from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from django.core.exceptions import PermissionDenied from django.db import transaction from django.db.models import Count, Sum, F, Func from datetime import date...
StarcoderdataPython
1626762
<filename>Ex_loops.py<gh_stars>0 import random print("program for user enter names and print random name") people = [] for x in range(0,8): person = input("Please enter a name: ") people.append(person) index = random.randint(0,7) random_person = people[index] print("Picked random person is:"...
StarcoderdataPython
1702399
<filename>meerk40t/balor/sender.py # Balor Galvo Laser Control Module # Copyright (C) 2021-2022 Gnostic Instruments, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
StarcoderdataPython
129154
<reponame>ziransun/wpt<filename>websockets/cookies/support/set-cookie.py import urllib def main(request, response): response.headers.set('Set-Cookie', urllib.unquote(request.url_parts.query)) return [("Content-Type", "text/plain")], ""
StarcoderdataPython
3258589
from genericpath import isdir import multiprocessing from os import listdir from os.path import isfile, join from typing import Any, Dict, List from analyzer.src.statistics import Statistics from analyzer.src.utils import get_analyzer_res_path, get_collector_res_path, load_json_file, remove_keys, save_json_file from a...
StarcoderdataPython
40571
<filename>launch/full_recording.launch.py import launch from launch.substitutions import Command, LaunchConfiguration from launch_ros.actions import LifecycleNode from launch.actions import EmitEvent from launch.actions import RegisterEventHandler from launch_ros.events.lifecycle import ChangeState from launch_ros.even...
StarcoderdataPython
1786748
<gh_stars>1-10 from pyvultr.base_api import SupportHttpMethod from pyvultr.v2 import BareMetalPlanItem, Plan from tests.v2 import BaseTestV2 class TestPlan(BaseTestV2): def test_list(self): """Test list plan.""" with self._get("response/plans") as mock: _excepted_result = mock.python_b...
StarcoderdataPython
180396
#!/usr/bin/python # -*- coding: utf-8 -*- from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.dokku_utils import subprocess_check_output import subprocess import re DOCUMENTATION = """ --- module: dokku_ps_scale short_description: Manage process scaling for a given dokku application options:...
StarcoderdataPython
4836254
<filename>data_processing/EMScompare_resources.py import os import pandas as pd import matplotlib.pyplot as plt import sys sys.path.append('../') from load_paths import load_box_paths import matplotlib as mpl import matplotlib.dates as mdates from datetime import date, timedelta, datetime import seaborn as sns from pro...
StarcoderdataPython
3307349
import sys, requests from datetime import datetime,timedelta import pandas as pd loc = ["47.964718", "7.955852"] d_from_date = datetime.strptime('2017-10-01' , '%Y-%m-%d') d_to_date = datetime.strptime('2018-08-10' , '%Y-%m-%d') delta = d_to_date - d_from_date latitude = loc[0] longitude = loc[1] with open('/home...
StarcoderdataPython
3323678
<filename>python-ml-book/ch02/perceptron.py """ Implementation of perceptron algorithm from Chapter 2 of "Python Machine Learning" """ import numpy as np def train_perceptron(observations, labels, learning_rate=0.1, max_training_iterations=10): """ Trains a (binary) perceptron, returning a function that can p...
StarcoderdataPython
3281956
#!/usr/bin/python -u # -*- coding: latin-1 -*- # # A programming puzzle from Einav in Z3 # # From # 'A programming puzzle from Einav' # http://gcanyon.wordpress.com/2009/10/28/a-programming-puzzle-from-einav/ # ''' # My friend Einav gave me this programming puzzle to work on. Given # this array of positive and negativ...
StarcoderdataPython
3368806
import logging from viadot.tasks import AzureSQLCreateTable, AzureSQLDBQuery logger = logging.getLogger(__name__) SCHEMA = "sandbox" TABLE = "test" def test_azure_sql_create_table(): create_table_task = AzureSQLCreateTable() create_table_task.run( schema=SCHEMA, table=TABLE, dtype...
StarcoderdataPython
1621067
<gh_stars>1-10 import numpy as np import xarray as xr import cmocean import cartopy import cartopy.crs as ccrs import matplotlib as mpl import matplotlib.ticker as mticker import matplotlib.pyplot as plt import matplotlib.patches as mpatches from paths import path_results from regions import boolean_mask, SST_index_bo...
StarcoderdataPython
1625248
<reponame>patpio/drf_images_api<gh_stars>1-10 from django.db import models class ExpiringLink(models.Model): url = models.URLField() token = models.UUIDField() created_at = models.DateTimeField(auto_now_add=True) duration = models.IntegerField() def __str__(self): return f'{self.url}'
StarcoderdataPython
3203476
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- import torch def assert_values_are_close(input, other, rtol=1e-05, ato...
StarcoderdataPython
112581
<reponame>nybrandnewschool/review4d import contextlib __all__ = [ 'suppress_messages', 'messages_suppressed', ] @contextlib.contextmanager def suppress_messages(ui): previous_value = getattr(ui, 'messages_suppressed', False) try: ui.messages_suppressed = True yield finally: ...
StarcoderdataPython
65780
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copyright (c) 2019, Linear Labs Technologies 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 Unles...
StarcoderdataPython
1778605
<reponame>erpnext/foundation # -*- coding: utf-8 -*- # Copyright (c) 2017, EOSSF and contributors # For license information, please see license.txt from __future__ import unicode_literals from frappe.website.website_generator import WebsiteGenerator class FrappeApp(WebsiteGenerator): def validate(self): if not sel...
StarcoderdataPython
3215618
from rest_framework.permissions import BasePermission class IsSelfUser(BasePermission): def has_object_permission(self, request, view, obj) -> bool: return request.user == obj class IsAdminOrSelfUser(IsSelfUser): def has_object_permission(self, request, view, obj) -> bool: is_self_user: bool...
StarcoderdataPython
174566
<gh_stars>0 TAIGA_USER = '<EMAIL>' TAIGA_PASSWORD = '<PASSWORD>' PROJECT_SLUG = 'test_taiga_user-fake-project-1' DONE_SLUG = 'Done'
StarcoderdataPython
188904
from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets, mixins, status from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import TokenAuthentication from core.models import Tag, Ingredient, Recipe from .seria...
StarcoderdataPython
1776615
<reponame>ChrisLR/BasicDungeonRL from bflib import units from bflib.characters import classes from bflib.spells import listing from bflib.spells.base import Spell from bflib.spells.duration import SpellDuration from bflib.spells.range import SpellRange @listing.register_spell class BladeBarrier(Spell): name = "Bl...
StarcoderdataPython
119832
# Copyright (c) 2013 python-gerrit Developers. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
StarcoderdataPython
1749941
class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: minSum = triangle[-1] for i in range(len(triangle) - 2, -1, -1): for j in range(i + 1): minSum[j] = min(minSum[j], minSum[j + 1]) + triangle[i][j] return minSum[0]
StarcoderdataPython
3328075
""" The predicting pipeline """ import sys import logging import pandas as pd import click from src.data.make_dataset import read_data from src.features.make_features import full_transform from src.models.fit_predict_model import predict_model from src.models.model_dump import load_model from src.entit...
StarcoderdataPython
3394365
<gh_stars>0 import abc from collections import defaultdict import datetime import uuid class BaseController(object): __metaclass__ = abc.ABCMeta def __init__(self): """Must set: self.queue: list of app_models to sync self.messages: list of controller messages self.app_models: ...
StarcoderdataPython
1706938
<gh_stars>0 import asyncio import typing from queue import Empty, Queue from starlette.requests import Request from tartiflette import Resolver, Subscription from ._utils import Dog, PubSub @Resolver("Query.hello") async def hello(parent, args, context, info) -> str: name = args.get("name", "stranger") retu...
StarcoderdataPython
3375175
<reponame>berland/resqpy import pytest import os import numpy as np import resqpy.model as rq import resqpy.grid as grr import resqpy.fault as rqf import resqpy.derived_model as rqdm import resqpy.olio.transmission as rqtr def test_fault_connection_set(tmp_path): gm = os.path.join(tmp_path, 'resqpy_test_fgcs.epc...
StarcoderdataPython
3288075
from django.urls import path from . import views urlpatterns = [ path('movies/', views.MoviesListApi.as_view()), path('movies/<uuid:pk>/', views.MoviesDetailApi.as_view()) ]
StarcoderdataPython
3236440
<filename>gumiyabot/bancho.py # -*- coding: utf-8 -*- """ <NAME> (osu!) irc3 plugin. """ import asyncio import irc3 # Bancho does not comply with the IRC spec (thanks peppy) so we need to account # for that or else the irc3 module will not read any data class BanchoConnection(irc3.IrcConnection): """asyncio prot...
StarcoderdataPython
3352881
from numpy import sqrt from pandas import DataFrame from sklearn.datasets import make_friedman1 from sklearn.feature_selection import SelectFromModel, RFE from sklearn.linear_model import LinearRegression, Lasso, Ridge from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error from sklearn.model_sele...
StarcoderdataPython
1788300
<gh_stars>1-10 # -*- encoding:utf-8 -*- """ 量化波动程度模块 """ from __future__ import division from __future__ import print_function from __future__ import absolute_import import matplotlib.pyplot as plt import numpy as np import pandas as pd from ..TLineBu.ABuTLine import AbuTLine from ..CoreBu.ABuPdHelper import pd_...
StarcoderdataPython
4829854
<reponame>dvjr22/StockPicker<filename>ProjectCode/002_stock_miner.py #!/usr/bin/env python # coding: utf-8 # # References # http://theautomatic.net/yahoo_fin-documentation/ # http://theautomatic.net/2020/05/05/how-to-download-fundamentals-data-with-python/ # https://algotrading101.com/learn/yahoo-finance-api-guide/> #...
StarcoderdataPython
1771076
import unittest from base import testlabel from cqparts.utils.test import CatalogueTest from cqparts.catalogue import JSONCatalogue catalogue = JSONCatalogue('test-files/thread_catalogue.json') cls = testlabel('complex_thread')(CatalogueTest.create_from(catalogue)) # FIXME: when #1 is fixed, remove this so tests ar...
StarcoderdataPython
65024
<filename>garminexport/garminclient.py<gh_stars>0 #! /usr/bin/env python """A module for authenticating against and communicating with selected parts of the Garmin Connect REST API. """ import json import logging import os import re import requests from io import BytesIO import sys import zipfile import dateutil impor...
StarcoderdataPython
34810
<reponame>UsterNes/OnlineSchemaChange """ Copyright (c) 2017-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same direc...
StarcoderdataPython
1700135
<gh_stars>0 class HTTPError(Exception): pass class VersionSpecificationError(Exception): pass class SchedulerException(Exception): pass class CandidateNodeNotFoundException(SchedulerException): pass class LowResourceException(SchedulerException): pass class AbortInstanceStartException(Sche...
StarcoderdataPython
1650916
<reponame>geofft/multiprocess # # Module supporting finaliztion using weakrefs # # processing/finalize.py # # Copyright (c) 2006-2008, <NAME> --- see COPYING.txt # import weakref import itertools from processing.logger import subDebug __all__ = ['Finalize', '_runFinalizers'] _registry = {} _counte...
StarcoderdataPython
175458
<filename>training/src/tests/tests/python/gaussian_upsampling.py # Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. # # 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 witho...
StarcoderdataPython
83056
<filename>actor/urls.py<gh_stars>1-10 # Copyright 2009 Google 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 by ap...
StarcoderdataPython
1731022
# SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2017, Arm Limited and contributors. # # 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
1661213
<reponame>IvanNardini/2-Engineering<filename>MachineLearningPlatforms/Kubeflow/applications/base/pipelines/conditionals/component.py #!/usr/bin/env python3 # This is an example for testing conditions in Kubeflow # Steps: # 1 - Define functions # 2 - Define lightweight python components # 3 - Write the component to a f...
StarcoderdataPython
121386
<reponame>henakauser/resume-api<gh_stars>0 """PostgreSQL utilities""" def pg_result_to_dict(columns, result, single_object=False): """Convert a PostgreSQL query result to a dict""" resp = [] for row in result: resp.append(dict(zip(columns, row))) if single_object: return resp[0] ...
StarcoderdataPython
3216774
<reponame>grantmcconnaughey/django-related-entities from django.test import TestCase from relatedentities.models import RelatedEntity from relatedentities.utils import add_related from .models import Cat, Dog class RelatedEntitiesUtilsTests(TestCase): def setUp(self): self.cat = Cat.objects.create(name="...
StarcoderdataPython
1602711
import numpy as np from pandas import DataFrame from tensorflow.keras.preprocessing.sequence import pad_sequences import csv import os class ECGDataIterator: def __init__(self, f, subsample=1): self.ifd = open(f, "rb") self._ss = subsample self._offset = 2048 def __next__(self): ...
StarcoderdataPython