id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3202713
__author__ = '<NAME>' __email__ = '<EMAIL>' __date__ = '9/3/2020 8:12 AM' def get_sub(param1, param2): return abs(param1 - param2) def get_val(arr, i, j): n = len(arr) if 0 <= i < n and 0 <= j < n: return arr[i][j] else: return float('inf') def get_min(arr, i, j): return min(ab...
StarcoderdataPython
185811
<filename>vio/vio/pub/msapi/extsys.py # Copyright (c) 2017-2018 VMware, 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 r...
StarcoderdataPython
52857
<gh_stars>0 #!/usr/bin/env python3 import unittest.mock from unittest.mock import call import draw class TestDraw(unittest.TestCase): def test_parse_command_1(self): self.assertEqual([("F", 100), ("T", 90), ("F", 100), ("T", 90), ("F", 100), ("T", 90), ("F", 100)], draw.parse_com...
StarcoderdataPython
1797807
#!/usr/bin/env python3 # import logging # from scipy.special import comb import gmpy2 logging.basicConfig(format="%(message)s", level=logging.INFO) logger = logging.getLogger() MODULUS = pow(2, 15) # MODULUS = 0 class IterationError(Exception): pass def r0_3_r1_n(n, r7): result = r7 * (r7 + n + 3) % MODUL...
StarcoderdataPython
3389869
<filename>src/sw/src/simulation/gen_image.py #!/usr/bin/env python import numpy as np; import matplotlib.pyplot as plt import argparse #===================================================================================================== # defaul values VGA_HEIGHT = 480 VGA_WIDTH = 640 OUTPUT_IMG...
StarcoderdataPython
60649
<filename>configs/egohands/egohands_dataset.py _base_ = '../_base_/datasets/coco_detection.py' data_root = 'data/egohands/' classes = ('myleft', 'myright', 'yourleft', 'yourright') # クラスラベル data = dict( train=dict( classes=classes, # COCOデータセットのクラスをオーバーライド ann_file=data_root+'annotations/train.jso...
StarcoderdataPython
145043
<filename>ingest/importer/conversion/metadata_entity.py import copy from ingest.importer.data_node import DataNode from ingest.importer.spreadsheet.ingest_worksheet import IngestRow TYPE_UNDEFINED = 'undefined' class MetadataEntity: # TODO enforce definition of concrete and domain types for all MetadataEntity ...
StarcoderdataPython
3352809
<filename>memberaudit/tests/testdata/esi_test_tools/tests.py from datetime import datetime from bravado.exception import HTTPNotFound from django.test import TestCase from .main import EsiClientStub, EsiEndpoint testdata = { "Alpha": { "get_cake": {"1": "cheesecake", "2": "strawberrycake"}, "get...
StarcoderdataPython
3292587
from aerosandbox.dynamics.point_mass.common_point_mass import _DynamicsPointMassBaseClass from aerosandbox.weights.mass_properties import MassProperties import aerosandbox.numpy as np from typing import Union, Dict, Tuple class DynamicsPointMass3DSpeedGammaTrack(_DynamicsPointMassBaseClass): """ Dynamics inst...
StarcoderdataPython
3394957
<reponame>cajomferro/marine-robotics-pacific #!/usr/bin/python from pacific import ms5837 from dataclasses import dataclass @dataclass class Pressure: sensor = None BAR_CONST: float = 0.0689475729 def read(self): """ Read tempeature (ºC) and pressure (bar) """ # We have t...
StarcoderdataPython
3351760
class WrappaText: def __init__(self, text): self._text = text @property def text(self): return self._text
StarcoderdataPython
1659708
#Импортируем нужные модули import json import requests import time import urllib import logging import signal import sys #Переменные для получение и отправка данные через TelegramApi и OpenWeatherApi TOKEN = "<KEY>" OWM_KEY = "<KEY>" POLLING_TIMEOUT = None #Функция для анализа обновлений из TelegramApi def getText(up...
StarcoderdataPython
182070
from datetime import datetime, timezone from roll import AbilityRoll, DamageRoll, DiceRoll, SimpleRoll, parse_roll_content import re # TODO: refactor classes into some kind of parent-child relationship once we've established a reasonable # inheritance model def parse_attack_name(content): attack_name_patterns = (...
StarcoderdataPython
26634
import numpy as np import pandas as pd import seaborn as sns from nninst.backend.tensorflow.model import AlexNet from nninst.backend.tensorflow.trace.alexnet_imagenet_inter_class_similarity import ( alexnet_imagenet_inter_class_similarity_frequency, ) from nninst.op import Conv2dOp, DenseOp np.random.seed(0) sns....
StarcoderdataPython
52521
<reponame>gentildf/Python #Faça um programa em Python que abra e reproduza o áudio de um arquivo MP3. import pygame print('\033[1mPlayer de música') pygame.mixer.init() pygame.mixer.music.load("desafio023.mp3") pygame.mixer.music.play() while(pygame.mixer.music.get_busy()):pass
StarcoderdataPython
4808504
from django.core.exceptions import PermissionDenied from django.http.response import Http404, HttpResponseForbidden, HttpResponseNotAllowed from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets, generics from rest_framework import permissions as rest_permissi...
StarcoderdataPython
1757031
from nose.tools import set_trace import logging import sys import os import base64 import random import uuid import json import re import urllib import urlparse import flask from flask import ( Response, redirect, ) from flask.ext.babel import lazy_gettext as _ from sqlalchemy.exc import ProgrammingError from ...
StarcoderdataPython
3276818
<reponame>mikepyne/RotaGenerator import pytest from unittest.mock import Mock from spiders.loew import LiturgyOffice @pytest.fixture() def lo(): return LiturgyOffice() class TestMass_init(object): def test_build_url(self, lo): assert lo._build_url(2017, 7) == 'https://www.liturgyoffice.org.uk/Calend...
StarcoderdataPython
105912
<reponame>MontyThibault/centre-of-mass-awareness<gh_stars>0 '''OpenGL extension NV.vertex_program1_1 This module customises the behaviour of the OpenGL.raw.GL.NV.vertex_program1_1 to provide a more Python-friendly API ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper...
StarcoderdataPython
176165
from django.apps import AppConfig class TemplatesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'templates'
StarcoderdataPython
1640225
<reponame>melvinkcx/graphql-core-next from graphql.language import Source def describe_source(): def can_be_stringified(): source = Source("") assert str(source) == "<Source name='GraphQL request'>" source = Source("", "Custom source name") assert str(source) == "<Source name='Cus...
StarcoderdataPython
1602508
<filename>examples/benchmark/bench_modem.py # Copyright: (c) 2021, <NAME> """ Benchmark the SDR and measure BER See README.md for instructions on how to run Parameters can be edited in main. Remember to match the config file used for the SDR """ import numpy as np import asyncio import zmq import zmq.asyncio zmq.a...
StarcoderdataPython
1656845
<reponame>technolingo/AlgoStructuresPy ''' Write a program that console prints the numbers from 1 to n. But for multiples of three print “fizz” instead of the number and for the multiples of five print “buzz”. For numbers which are multiples of both three and five print “fizzbuzz”. --- Example fizzBuzz(5); 1 2 ...
StarcoderdataPython
1625521
<filename>pyscript/apps/getdata_afldraw/__init__.py #!/usr/bin/env python import json import requests from requests.exceptions import HTTPError @service def getdata_afldraw( entity_id="sensor.getdata_afl_draw", unit_of_measurement=None, friendly_name="AFL Draw", icon="mdi:football-australian", ): ...
StarcoderdataPython
1746989
<filename>openstack-dashboard/openstack_dashboard/dashboards/project/instances/workflows/__init__.py # Importing non-modules that are not used explicitly from create_instance import LaunchInstance
StarcoderdataPython
3307075
<reponame>spidezad/python-pptx<gh_stars>1-10 # -*- coding: utf-8 -*- # # testdata.py # # Copyright (C) 2013 <NAME> <EMAIL> # # This module is part of python-pptx and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Test data for unit tests""" from pptx.oxml import nsdecls, ox...
StarcoderdataPython
3376035
<reponame>anhp95/forest_attr_segment<gh_stars>0 # %% import os import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns dir_ = r"D:\Publication\IGARSS 2021\tree_spec\material" csv_dir = "loss_acc_performance" figure_dir = "figure" attr = "spec" csv_file = os.path.join(dir_, csv_dir...
StarcoderdataPython
3355050
<reponame>Cajivah/nlp-information-extraction import glob import json import os attributes = ['subject', 'flatMeterage', 'roomMeterage', 'rent', 'bills', 'deposit', 'internetSpeed', 'district', 'street', 'roomsCount', 'flatmatesCount', 'flatmatesGenders', 'flatmatesOccupation', 'preferredOc...
StarcoderdataPython
1659865
# # @package elementpropertiesvalidation # This module exists to pair with element.py and validate anything that is # being attempted to set as a value for one of an Element's properties from . import content_options as content # used for tuplifying import string import ast # # A listing of the available options fo...
StarcoderdataPython
192794
#!/usr/bin/env python #################### # Required Modules # #################### # Generic/Built-in import logging # Libs # Custom ################## # Configurations # ################## ################################### # Response Parser Class - Results # ################################### class Resu...
StarcoderdataPython
199401
import unittest import subprocess import capitals class TestCapitals(unittest.TestCase): def test_correct_capital_returned(self): city = capitals.capital("Central African Republic") self.assertEqual("Bangui", city) city = capitals.capital("Hungary") self.assertEqual("Budapest", c...
StarcoderdataPython
1790371
<gh_stars>1-10 from Owner import Owner from Tenant import Tenant from Apartment import Apartment def create_owner(name, address, phone): return Owner(name, address, phone) def create_apartment(apartment_type, size, no_rooms, bau_year, address, apartment_owner): return Apartment(apartment_type, size, no_room...
StarcoderdataPython
115037
<filename>backend/apps/utils/api_views.py from django.shortcuts import render_to_response # Import the tastypie.api.Api object with which your api resources are registered. from backend.urls import v1_api as api def api_profile(request, resource): """ Allows easy profiling of API requests with django-debug-toolba...
StarcoderdataPython
10199
<gh_stars>0 import datetime from app.models import Log from flask_login import current_user from app.extensions import db # https://stackoverflow.com/questions/6558535/find-the-date-for-the-first-monday-after-a-given-date def next_weekday( d: datetime.datetime = datetime.datetime.utcnow(), weekday: int = 0, )...
StarcoderdataPython
106696
<reponame>fhvilshoj/ECINN # convenience file to load ibinn model with or without pretrained weights. import os # This is the local model file, to override GenerativeClassifier from IB-INN module # in order to add Celeba and FakeMNIST datasets. from model import GenerativeClassifier def load_model(args, cfg): N_...
StarcoderdataPython
3345246
from phenotype.Core import ( __op_attr_getter__, __op_item_getter__, __return_as__, __try_except__,) #2 LOCAL GLOBALS __try__ = __try_except__.Unary #2 PUBLIC INTERFACE def Item(index): return __op_item_getter__(index) def Sliced(*indices): return __op_attr_getter__(tuple(indices)) def Name(name,default...
StarcoderdataPython
1686974
<filename>main.py import configparser from twisted.internet.task import LoopingCall from twisted.internet import reactor from scrapy.crawler import CrawlerRunner from websites.amazon import Amazon from websites.ebay import Ebay from websites.facebook import Facebook from websites.kijiji import Kijiji from websites.lesp...
StarcoderdataPython
3307202
#!/usr/bin/env python3 # Copyright 2021 Battelle Energy Alliance, LLC # Python std library imports import argparse import os import pkg_resources import pickle import sys from math import ceil # package imports from navv import utilities from navv import spreadsheet_tools from navv import _version DATA_PATH = pkg_r...
StarcoderdataPython
1762788
import re import unittest from scrubadub.filth import Filth, MergedFilth from scrubadub.exceptions import InvalidReplaceWith, FilthMergeError class FilthTestCase(unittest.TestCase): def test_disallowed_replace_with(self): """replace_with should fail gracefully""" filth = Filth() with self...
StarcoderdataPython
1613499
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin import logging from flask import jsonify from sqlalchemy.orm.exc import NoResultFound from flexget.api import api, APIResource from flexget.plugins.filter.retry_failed import ...
StarcoderdataPython
134830
from typing import List import numpy as np import segmentation_models_pytorch as smp from segmentation_models_pytorch.base.modules import Activation import torch from torch import nn from torch.nn import functional as F from torchvision import datasets from torchvision.transforms import transforms from baal import Ac...
StarcoderdataPython
1777534
# -*- coding: utf-8 -*- """ :author: T8840 :tag: Thinking is a good thing! 纸上得来终觉浅,绝知此事要躬行! :description: 用来统计埋点数据出现个数 """ from pprint import pprint def count(f): Count = {} with open(f,'r',encoding='utf-8') as file: for line in file.readlines(): Count[lin...
StarcoderdataPython
1629074
import random from typing import Any, List, Optional import numpy as np import numpy.typing as npt import pytorch_lightning as pl import torch import torch.utils.data from nuplan.planning.training.modeling.types import FeaturesType, TargetsType, move_features_type_to_device from nuplan.planning.training.preprocessing....
StarcoderdataPython
193855
import datetime import pathlib import unittest from signify.authenticode import TRUSTED_CERTIFICATE_STORE, TRUSTED_CERTIFICATE_STORE_NO_CTL from signify.certificates import Certificate from signify.context import VerificationContext, FileSystemCertificateStore from signify.exceptions import VerificationError from sign...
StarcoderdataPython
45878
<gh_stars>10-100 from django.conf.urls import patterns, url from rest_framework import routers from accounts.api import UserViewSet, LostKeyViewSet, AuthView, MemberViewSet from nodes.api import NodeViewSet, NodePathView, NodeDataView, PolicyViewSet from news.api import NewsApiView from search.api import SearchView fr...
StarcoderdataPython
3202024
""" Pre-processing Functions """ import cv2 import torch import numpy as np import torch.nn.functional as F from torchvision.transforms import ToTensor def resize(image, size): """Resize images""" image = F.interpolate(image.unsqueeze(0), size=size, mode="nearest").squeeze(0) return image def pad_to_sq...
StarcoderdataPython
50327
<filename>Data-Structures/Arrays & LinkedLists/SinglyLinkedList.py class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: """ Class to create a linked list and perform some basic operations such as: append, display, prepend, convert, insert, remove...
StarcoderdataPython
4823091
class StandardClassifier_1D: def __init__(self, model_name, **model_params): self.model_name = model_name self.model = None if self.model_name == 'KNN': from sklearn.neighbors import KNeighborsClassifier self.model = KNeighborsClassifier(**model_params) elif...
StarcoderdataPython
3295438
""" Vectorize text field """ from sklearn.base import BaseEstimator, TransformerMixin from sklearn.feature_extraction.text import TfidfVectorizer import pandas as pd class VectorizeText(BaseEstimator, TransformerMixin): """ Class for altering sklearn.feature_extraction.text.TfidfVectorizer so that its tra...
StarcoderdataPython
1667240
<reponame>nuzcraft/RLTut<filename>helpers/target_monster.py # function to target a specific monster from helpers.target_tile import target_tile import variables as var def target_monster(max_range = None): # returns a clicked monster inside FOV up to a range, or Non if right-clicked while True: (x, y)...
StarcoderdataPython
3379889
# -*- coding: utf-8 -*- # standard libraries import csv import logging from pathlib import Path from typing import List # third-party libraries from bs4 import BeautifulSoup import pandas as pd import pendulum # my libraries import src.helpers as hlp logger = logging def filter_download_contents(contents): """...
StarcoderdataPython
1753125
from ..biotools import windows_overlap import itertools import numpy as np class MutationChoice: """Represent a segment of a sequence with several possible variants. Parameters ---------- segment A pair (start, end) indicating the range of nucleotides concerned. We are applying Python ra...
StarcoderdataPython
3367988
<filename>kete_hs21/lesson/apps.py from django.apps import AppConfig class LessonConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'lesson'
StarcoderdataPython
113830
#! /usr/bin/env python3 import os import sys import time import notify2 from datetime import datetime from pprint import pprint from daterelate.daterelate import relate from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, TimeoutException from selenium.webdriver.chrome.options ...
StarcoderdataPython
3284255
# Copyright (c) 2020, <NAME>, Honda Research Institute Europe GmbH, and # Technical University of Darmstadt. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code mus...
StarcoderdataPython
4824888
<reponame>lukepfister/scico import operator as op import numpy as np from jax.config import config import pytest # enable 64-bit mode for output dtype checks config.update("jax_enable_x64", True) from typing import Optional import jax import scico.numpy as snp from scico import linop from scico.random import rand...
StarcoderdataPython
3399890
import time import pytest from he.decorators import ( timer, debug, throttle, singleton, repeat, count_calls, CountCalls, ) # GIVEN any decorator @pytest.mark.parametrize( 'decorator', [timer, debug, throttle(rate=0.01), singleton, repeat, count_calls, CountCalls], ) def test_con...
StarcoderdataPython
72923
<reponame>code-impactor/arque<filename>main.py<gh_stars>1-10 import signal import random import logging import asyncio import aioredis import time from functools import wraps from arque import Arque logger = logging.getLogger(__name__) async def shutdown(signal, loop): """Cleanup tasks tied to the service's shut...
StarcoderdataPython
3213842
<reponame>ffreemt/gpt3-api """Test gpt3_api.""" from gpt3_api import __version__ from gpt3_api import gpt3_api def test_version(): """Test version.""" assert __version__ == "0.1.0" def test_sanity(): """Sanity check.""" try: assert not gpt3_api() except Exception: assert True
StarcoderdataPython
3369621
<filename>backend/api/login.py from typing import List from datetime import timedelta from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from backend import schemas, crud, config from backend.utils import get_db, get_current_user, create_access_token from backend.models import Us...
StarcoderdataPython
4827137
<gh_stars>10-100 """ Install the following dependencies: html-sanitizer==1.9.1 bleach==3.2.1 lxml==4.6.2 html5lib==1.1 """ from bleach.sanitizer import Cleaner as BleachSanitizer from html_sanitizer import Sanitizer as HTMLSanitizerSanitizer from lxml.html import html5parser, tostring from lxml.html.clean import Clea...
StarcoderdataPython
3339730
from os.path import join from django.conf import settings from django.forms import TextInput, Textarea from django.utils.safestring import mark_safe from django.template.loader import render_to_string from cms.settings import CMS_MEDIA_URL from cms.models import Page from django.forms.widgets import Widget class Plug...
StarcoderdataPython
31177
"""Module containing definitions of arithmetic functions used by perceptrons""" from abc import ABC, abstractmethod import numpy as np from NaiveNeurals.utils import ErrorAlgorithm class ActivationFunction(ABC): """Abstract function for defining functions""" label = '' @staticmethod @abstractmeth...
StarcoderdataPython
80518
"""This module handles all operations involving the user's settings.""" import json from os import path from PyQt5.QtWidgets import QWidget from PyQt5.QtCore import QObject, pyqtSignal from ui import SettingsTab import ManageDB from Constants import * import GeneralUtils from GeneralUtils import JsonModel class Sett...
StarcoderdataPython
6345
# -*- coding: utf-8 -*- # # Tencent is pleased to support the open source community by making QT4C available. # Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. # QT4C is licensed under the BSD 3-Clause License, except for the third-party components listed below. # A copy of the BSD 3-Cla...
StarcoderdataPython
3313069
# -*- coding: utf-8 -*- """window.py A module implementing the Window class, which allows drawing and the saving of images and video. License: http://www.apache.org/licenses/LICENSE-2.0""" import enum import os import pathlib from typing import Any, Tuple import cv2 import numpy as np # noinspection PyUnresol...
StarcoderdataPython
3238682
<reponame>aminhp93/learning_python from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import ( CreateView, ListView, DetailView, DeleteView, UpdateView ) from .models import Comment # Create your views here. # class CommentListView(ListView): # model = Comme...
StarcoderdataPython
1790079
<gh_stars>1-10 #!/usr/bin/python2.7 import ConfigParser import optparse import os import re import sys import time import engine import data import genautodep APPDIR_RE = re.compile(r"(/app)($|/)") def RegisterJavaLibrary(module, f): name = "lib%s" % f.name lib = data.JavaLibrary( module.name, f.pa...
StarcoderdataPython
1623992
from zabbix_enums.common import _ZabbixEnum class MacroType(_ZabbixEnum): TEXT = 0 SECRET = 1
StarcoderdataPython
1612520
<filename>apisummariser/preprocessing.py import numpy as np from sklearn import manifold from tqdm import tqdm from apisummariser.helper import sequences_metrics class Preprocessor: def __init__(self, callers_file, callers_package, callers, calls): ''' :type callers: list :param callers:...
StarcoderdataPython
71211
<filename>tokenfile.py token = "<PASSWORD>" #Looks like MjM4NDk0NzU2NTIxMzc3Nzky.CunGFQ.wUILz7z6HoJzVeq6pyHPmVgQgV4
StarcoderdataPython
14248
import requests from utils import loginFile, dataAnalysis import os import datetime from dateutil.relativedelta import relativedelta import json from utils.logCls import Logger dirpath = os.path.dirname(__file__) cookieFile = f"{dirpath}/utils/cookies.txt" dataFile = f"{dirpath}/datas" class DevopsProject: def...
StarcoderdataPython
1608004
<reponame>xuefeicao/snorkel from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import * import re import sys import numpy as np import scipy.sparse as sparse class ProgressBar(object): def __init__(sel...
StarcoderdataPython
4841359
import skimage.io as io import skimage.transform as skt import numpy as np from PIL import Image from src.models.class_patcher import patcher from src.utils.imgproc import * from skimage.color import rgb2hsv, hsv2rgb, rgb2gray from skimage.filters import gaussian class patcher(patcher): def __init__(self, body='....
StarcoderdataPython
3362479
import pathlib import tempfile import os import ray from ray import workflow from ray.workflow.storage import set_global_storage _GLOBAL_MARK_FILE = pathlib.Path(tempfile.gettempdir()) / "__workflow_test" def unset_global_mark(): if _GLOBAL_MARK_FILE.exists(): _GLOBAL_MARK_FILE.unlink() def set_global_...
StarcoderdataPython
1617143
import pytest import multiprocessing import contextlib import redis from rediscluster.connection import ClusterConnection, ClusterConnectionPool from redis.exceptions import ConnectionError from .conftest import _get_client @contextlib.contextmanager def exit_callback(callback, *args): try: yield fi...
StarcoderdataPython
1722609
<gh_stars>10-100 from __future__ import absolute_import import email.utils from .base import URLSettingsBase, is_importable class EmailSettings(URLSettingsBase): CONFIG = { 'smtp': {'EMAIL_BACKEND': 'django.core.mail.backends.smtp.EmailBackend', 'EMAIL_USE_TLS': False}, 'smtps': {'E...
StarcoderdataPython
3387041
<reponame>gcewing/PyGUI # # Python GUI - Scrollable Views - Gtk # import gtk from GUI import export from GUI import Scrollable from GUI.GScrollableViews import ScrollableView as GScrollableView, \ default_extent, default_line_scroll_amount, default_scrolling class ScrollableView(GScrollableView, Scrollable): def...
StarcoderdataPython
67863
from distutils.core import setup from setuptools import find_packages setup( name='pyrelate', version='1.0.0', author='sendwithus', author_email='<EMAIL>', packages=find_packages(), scripts=[], url='https://github.com/mrmch/pyrelate', license='LICENSE.txt', description='Python API c...
StarcoderdataPython
1754389
import sys, os sys.path.append('../python_packages_static') import zipfile import numpy as np import pandas as pd import pyemu import flopy.utils as fu from get_endpoints import get_endpoints # set path run_dir = '.' # get the run index from the command line runindex = int(sys.argv[1]) # get the correct q ratio from...
StarcoderdataPython
3366789
from .base_encoder import * from .encoder import *
StarcoderdataPython
1775008
<filename>oct/reconstruct/structure.py from oct.utils import * import logging from ..load.metadata import Metadata cp, np, convolve, gpuAvailable, freeMemory, e = checkForCupy() class Structure: """ Structure contrast OCT reconstruction """ def __init__(self, mode='log'): acceptedModes = 'log+linear'...
StarcoderdataPython
3372212
import os import re from flask import Response, redirect from subprocess import PIPE, Popen from wsgi_utils import PipeWrapper TRANSCODABLE_FORMATS = ['mp3', 'ogg', 'flac', 'm4a', 'wav'] def _format_of_file(filename): return re.search('\.([^.]+)$', filename).group(1) class Transcoder(object): def __init__(se...
StarcoderdataPython
4826258
import os os.rename("/home/simon/Programming/python/foo/test.py", "/home/simon/Programming/python/bar/bar/test1.py")
StarcoderdataPython
3347511
<gh_stars>0 """ CORE APP This module provides an interface to the app's managers. """ from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify # from polymo...
StarcoderdataPython
3399382
<reponame>jorgemauricio/python #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 17 16:17:25 2017 @author: jorgemauricio Instrucciones 1. Ordenar la siguiente lista de valores por medio de ciclos y/o validaciones arreglo = [54,26,93,17,77,31,44,55,20] Resultado arreglo = [54,26,93,17,77,31...
StarcoderdataPython
3352729
<filename>python/testData/resolve/UserPyInsteadProvidedPyi/main.py from pkg import foo foo.bar("a", "b") # <ref>
StarcoderdataPython
1694313
<filename>algo/spectral/SlidingWindow.py # -*- coding: utf-8 -*- import numpy as np # Based on: http://stackoverflow.com/a/4947453 # with some adjusts for noverlap """ Examples of use: 1-D: ==== a = np.array(range(100), dtype=np.int) b = SlidingWindow(a, 10, 0) # window_size=10, no overla...
StarcoderdataPython
94625
<reponame>bmcs-group/bmcs_beam from .ex_run import ExRun from .ex_run_view import ExRunView
StarcoderdataPython
4808924
<reponame>PitPietro/pascal-triangle """ > Task Given a string, find out if its characters can be rearranged to form a palindrome. > Example For inputString = "aabb", the output should be true. We can rearrange "aabb" to make "abba", which is a palindrome. > Input/Output - execution time limit: 4 seconds (py3) - input...
StarcoderdataPython
3238613
<reponame>rmed/akamatsu<filename>akamatsu/views/admin/profile.py # -*- coding: utf-8 -*- # # Akamatsu CMS # https://github.com/rmed/akamatsu # # MIT License # # Copyright (c) 2020 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated document...
StarcoderdataPython
3330250
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """NuvlaBox Peripheral Manager Bluetooth This service provides bluetooth device discovery. """ import bluetooth as bt import logging import sys import time import os import json import requests #from bluetooth.ble import DiscoveryService from threading impor...
StarcoderdataPython
1722290
# Generated by Django 3.1.6 on 2021-03-01 11:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('website', '0003_mgrssquare'), ] operations = [ migrations.RemoveField( model_name='mgrssquare', name='precision', ),...
StarcoderdataPython
3267463
import numpy print(dir(numpy))
StarcoderdataPython
1686780
<reponame>MarkGhebrial/advent-of-code-2021 def binaryToInt (string: str, oneChar = "1", zeroChar = "0"): out = 0 for i in range(len(string)): currentDigit = None if string[len(string) - 1 - i] == oneChar: currentDigit = 1 elif string[len(string) - 1 - i] == zeroChar: ...
StarcoderdataPython
1796228
from django.db import models # from django.template.defaultfilters import slugify ''' def app_source_path(instance, filename): return '{0}/app_{1}/{2}/{3}'.format(slugify(instance.app.author), slugify(instance.app.name), instance.version, filename) def app_destiny_path(instance, filename): return '{0}/app_{1...
StarcoderdataPython
1682003
import sqlite3 conn = sqlite3.connect('spider.sqlite') cur = conn.cursor() cur.execute('SELECT * FROM Twitter') count = 0 for row in cur : print row count = count + 1 print count, 'rows.' cur.close()
StarcoderdataPython
3335456
<reponame>taku-ito/nlp100.github.io<filename>tools/extract_country_names.py<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import json import sys import re d = json.load(sys.stdin) lines = d['text'].split('\n') for line in lines: # |{{flagicon|...} [[ ... ]] for Japanese Wikipedia # | {{flagdeco|......
StarcoderdataPython
122041
<reponame>geostarling/duct<filename>duct/protocol/sflow/protocol/protocol.py """ .. module:: protocol :synopsis: SFlow protocol .. moduleauthor:: <NAME> <<EMAIL>> """ import xdrlib from duct.protocol.sflow.protocol import flows, counters class Sflow(object): """SFlow protocol stream decoder """ def _...
StarcoderdataPython
59876
from __future__ import print_function, absolute_import import os.path as osp import numpy as np from ..utils.data import Dataset from ..utils.osutils import mkdir_if_missing from ..utils.serialization import write_json, read_json from ..utils.data.dataset import _pluck class SynergyReID(Dataset): md5 = '05050b5d...
StarcoderdataPython