id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
1656881
<reponame>dued/dued import os from os import name import sys import imp from sys import path from . import Config from .excepciones import ColeccionNoEcontrada from .util import debug class Cargador(object): """ Clase abstracta que define cómo buscar/importar una `.Coleccion` basada en sesión(es). ....
StarcoderdataPython
9759113
<filename>methods/call.py<gh_stars>0 # __call__ tutorial class Pay: total_hours = 0 total_pay = 0 def __init__(self, hourly_wage): self.hourly_wage = hourly_wage def __call__(self, hours_worked): self.total_hours += hours_worked self.total_pay += hours_worked * self.hourly_wag...
StarcoderdataPython
4857564
import os from argparse import Namespace from tqdm import tqdm import time import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader import sys sys.path.append(".") sys.path.append("..") from configs import data_configs from datasets.inference_dataset import InferenceDataset from e...
StarcoderdataPython
1919553
from shallowflow.api.source import AbstractSimpleSource from shallowflow.api.config import Option from shallowflow.api.vars import VariableName from shallowflow.api.compatibility import Unknown class GetVariable(AbstractSimpleSource): """ Outputs the value of the specified variable. """ def descripti...
StarcoderdataPython
1832122
import numpy as np def coco_contour_to_cv2(contour, dtype): """ translate coco format [x_1,y_1,x_2,y_2,...] to opencv contour [[[x_1,y_1]], [[x_2,y_2]],...] args: contour: list, the coco format contour dtype: the dtype of output needed, cv2 is a little bit weird on the dtype """ ...
StarcoderdataPython
1720505
<reponame>glennmatthews/aagen<gh_stars>0 # JSON encoding/decoding for AAGen from json import JSONEncoder from .map import SortedSet, DungeonMap, Region, Connection, Decoration from .direction import Direction import aagen.geometry class MapEncoder(JSONEncoder): def default(self, obj): """Convert AAGen obj...
StarcoderdataPython
1942673
<gh_stars>1-10 """ Fixer that changes zip(seq0, seq1, ...) into list(zip(seq0, seq1, ...) unless there exists a 'from future_builtins import zip' statement in the top-level namespace. We avoid the transformation if the zip() call is directly contained in iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or for V...
StarcoderdataPython
11250701
<filename>strings/anagram.py def valid_anagram(val1: str, val2: str) -> bool: if len(val1) != len(val2): return False char_counter = {} for char in val1: if char in char_counter: char_counter[char] += 1 else: char_counter[char] = 1 for char in val2: ...
StarcoderdataPython
12807859
<reponame>rom1504/embedding-reader """ This is an example on how to use embedding reader to do an inference over a set of billion of clip vit-l/14 embeddings to predict whether the corresponding images are safe or not """ from embedding_reader import EmbeddingReader import fire import os os.environ["CUDA_VISIBLE_DEV...
StarcoderdataPython
9615062
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @name - regularflow @contains - API to use regularflow. You can create and delete Agents that communicate beetwen each other to regulate circulation by a training @autor - <NAME> """ from .apiFlow import newAgent from .apiFlow import cycleManager from .apiFlow import...
StarcoderdataPython
6614713
<reponame>coreybobco/setlistspy-api<filename>setlistspy/app/models.py import os from django.db import models from setlistspy.app.base_model import BaseSetSpyModel from playhouse.postgres_ext import * # def get_db(): # return PostgresqlExtDatabase( # os.getenv('POSTGRES_HOST'), # user=os.getenv('PO...
StarcoderdataPython
159287
<reponame>SupremaLex/UO-test-funcs from .test_function import * from .support_funcs import * from .exceptions import * def FLETCBV3(n): name = "FLETCBV3 function (CUTE)" print(name) p, h = 1e-8, 1 / (n + 1) # move last n-member of second series to f and and create one series from 1 to n-1 f = lamb...
StarcoderdataPython
9745443
# The local version of the Process object from pathlib import Path from typing import Dict, List, Union from openghg.store import ObsSurface from openghg.types import DataTypes __all__ = ["process_files"] def process_files( files: Union[str, List], data_type: str, site: str, network: str, inlet: ...
StarcoderdataPython
9639772
#-*- coding: utf-8 -*- #!/usr/bin/python3 """ Copyright (c) 2020 LG Electronics Inc. SPDX-License-Identifier: MIT """ import os import json import logging from distutils.spawn import find_executable import re from ..context import WrapperContext LOGGER = logging.getLogger('SAGE') WRAPPER_MAP = {} def load_tools(...
StarcoderdataPython
4993082
import DBCon import DataReduction import sklearn.preprocessing import numpy as np import matplotlib.pyplot as plt import Constants import ClusterUtil import pandas as pd import Cluster from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import silhouette_score from sklearn.decomposition imp...
StarcoderdataPython
269466
<gh_stars>1-10 #!/usr/bin/env python #coding:utf-8 import sys from PyQt4 import QtGui from PyQt4 import QtCore class Button(QtGui.QWidget): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) x, y, w, h = 500, 200, 300, 400 self.setGeometry(x, y, w, h) ...
StarcoderdataPython
1671422
<filename>data/codeup/template/problem.py """ Problem URL: {Please provide the problem url} """ from io import TextIOWrapper from typing import Tuple def read_input(file: TextIOWrapper) -> Tuple[int, int]: # You can use 'input()' to get inputs input = lambda: file.readline().rstrip() solution_arg1 = in...
StarcoderdataPython
3304435
<gh_stars>10-100 from numpy import linspace # version VERSION = '0.3.0' # constants IDEAL_GAS_CONSTANT_KCAL = 1.987204118E-3 TEMPERATURE_CELSIUS = 25. # calculated constants ZERO_KELVIN = 273.15 TEMPERATURE_KELVIN = ZERO_KELVIN + TEMPERATURE_CELSIUS RT = IDEAL_GAS_CONSTANT_KCAL * TEMPERATURE_KELVIN # error FITTING_...
StarcoderdataPython
4936431
<filename>kernel/scrum.py import requests from config.settings import BACKLOG_AUTH __author__ = '<NAME>' class UnknownEnabler(Exception): pass class InvalidConection(Exception): pass class ScrumServer: def __init__(self, url): url = url or 'backlog.fiware.org' self.url = 'http://{}'.f...
StarcoderdataPython
5025926
''' _ _ _ _ _ _ _ _ _ _ _ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ ( P | O | L | Y | G | O | N | S | O | U | P ) \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ Plotter-friendly graphics utilities © <NAME> (@colormotor) 2021 - ... plut - visualization utils (matplotlib-based) ''' import matpl...
StarcoderdataPython
9667786
<gh_stars>0 # -*- encoding: utf-8 -*- """ Autorzy """ from datetime import date, datetime, timedelta from autoslug import AutoSlugField from django.core.exceptions import ValidationError from django.core.validators import RegexValidator from django.db import IntegrityError, models, transaction from django.db.models i...
StarcoderdataPython
34154
<filename>pyxb/binding/content.py # Copyright 2009, <NAME> # # 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
8060179
<gh_stars>0 """ a module to convert between the old (Python script) segment format, and the new (JSON) one """ from typing import Dict, Tuple # noqa: F401 import os import ast import json def assess_syntax(path): with open(path) as file_obj: content = file_obj.read() syntax_tree = ast.parse(content...
StarcoderdataPython
1892771
<gh_stars>0 import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.ensemble import GradientBoostingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import r2_score import numpy as np from sklearn.metrics import confusion_matrix from sklearn.metrics import rec...
StarcoderdataPython
3576991
<reponame>code-review-doctor/pythondotorg # Generated by Django 2.2.24 on 2021-12-23 13:09 from django.db import migrations from django.utils.text import slugify def populate_packages_slugs(apps, schema_editor): SponsorshipPackage = apps.get_model("sponsors", "SponsorshipPackage") qs = SponsorshipPackage.obj...
StarcoderdataPython
6500890
#!/usr/bin/env python import unittest import numpy as np from arte.types.slopes import Slopes class SlopesTest(unittest.TestCase): def setUp(self): self._n_slopes = 1600 self._mapx = np.ma.masked_array( np.arange(self._n_slopes, dtype=np.float32)) self._mapy = np.ma.masked_arr...
StarcoderdataPython
6401337
from django import forms from django.contrib.auth.models import User from .models import Participar class ParticiparForm(forms.ModelForm): class Meta: model = Participar fields = ['asistir']
StarcoderdataPython
8111771
# Copyright 2004 <NAME>. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) from pyplusplus.decl_wrappers import default_call_policies from pyplusplus.decl_wrappers import return_arg from pyplusplus.decl_wrappe...
StarcoderdataPython
276409
import base64 import hashlib import bencodepy def create_magnet_uri(data: bytes): # noinspection PyTypeChecker metadata: dict = bencodepy.decode(data) subj = metadata[b'info'] hashcontents = bencodepy.encode(subj) digest = hashlib.sha1(hashcontents).digest() b32hash = base64.b32encode(digest)...
StarcoderdataPython
1832107
<gh_stars>0 def solution(s, n): answer = '' for c in s: if c != ' ': if (ord(c) >= ord('a') and ord(c) <= ord('z')) and ord(c) + n > ord('z'): answer += chr(ord(c) + n - 26) elif (ord(c) >= ord('A') and ord(c) <= ord('Z')) and ord(c) + n > ord('Z'): ...
StarcoderdataPython
4859204
import sublime import webbrowser from .common import log, hh_syntax from .view import find_help_view, update_help_view, focus_on from .help_index import _load_help_index, _scan_help_packages from .help import _post_process_links, _resource_for_help from .help import _load_help_file, _display_help_file, _reload_help_...
StarcoderdataPython
3302546
#!/bin/env python # # Features.py: classes for handling feature data # Copyright (C) University of Manchester 2011-2019 <NAME>, <NAME> # & <NAME> # """ Features.py Classes for handling feature data. """ import logging import io from .distances import closestDistanceToRegion from .utils import make_errlin...
StarcoderdataPython
112722
import numpy as np import torch.optim as optim import networks.networks as net from networks.gtsrb import * from networks.svhn import * import torchvision as tv from torchvision import transforms from torch.utils.data import DataLoader from data.idadataloader import DoubleDataset from config import get_transform from d...
StarcoderdataPython
3300727
<gh_stars>0 class StatusModel: is_error = None is_processed = None is_income = None is_info = None is_outcome = None is_reverted = None message = None def __init__(self, processed: bool, move: str, message: str = None): self.is_error = not processed self.is_processed = p...
StarcoderdataPython
74442
<reponame>j-varun/enas import sys import os import time import numpy as np import tensorflow as tf from enas.controller import Controller from enas.utils import get_train_ops from enas.common_ops import stack_lstm from tensorflow.python.training import moving_averages class ConvController(Controller): def __init_...
StarcoderdataPython
3328620
from __future__ import annotations import typing from .. import spec from .. import exceptions from .. import crud_utils from . import table_utils def row_to_dict(row: spec.SARow) -> dict[str, typing.Any]: return row._asdict() def replace_row_foreign_keys( *, row: spec.Row, conn: spec.SAConnection...
StarcoderdataPython
148951
# This file is automatically generated by the rmf-codegen project. # # The Python code generator is maintained by Lab Digital. If you want to # contribute to this project then please do not edit this file directly # but send a pull request to the Lab Digital fork of rmf-codegen at # https://github.com/labd/rmf-codegen ...
StarcoderdataPython
4896705
"""The various views and routes for MapRoulette""" from flask import render_template, redirect, session from maproulette import app from maproulette.helpers import signed_in from maproulette.models import Challenge, Task, db @app.route('/') def index(): return render_template('index.html') @app.route('/logout'...
StarcoderdataPython
6632977
<gh_stars>10-100 # -*- coding: utf-8 -*- from unittest import TestCase from sqlalchemy.future import create_engine from sqlalchemy.orm import sessionmaker from eventsourcing_sqlalchemy.datastore import SQLAlchemyDatastore class TestDatastore(TestCase): def test_should_be_created_with_url(self) -> None: ...
StarcoderdataPython
3226598
# esi.py import requests import threading import uuid import webbrowser from .server import StoppableHTTPServer, AuthHandler from shortcircuit.model.logger import Logger class ESI: ''' ESI We are bad boys here. What should have been done is proxy auth server with code request, storage and all that stuff. ...
StarcoderdataPython
239196
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) x = read().rstrip().decode()[::-1] p = 0 m = 0 for xx in x: if xx == 'S' and m != 0: m -= 1 p += 1 if xx == 'T': m += 1 print(len(x) - 2 * p...
StarcoderdataPython
336640
<filename>ts/model_service/__init__.py<gh_stars>1-10 """ Model services code """ from . import model_service
StarcoderdataPython
11277755
<gh_stars>10-100 from alphavantage._version import version_info, __version__
StarcoderdataPython
12810154
<reponame>Lukeeeeee/FISDNN<filename>src/model/inputs/inputs.py import tensorflow as tf class Inputs(object): def __init__(self, config): self.input_dict = {} for key, value in config.items(): if type(value) is list: self.input_dict[key] = tf.placeholder(tf.float32, sha...
StarcoderdataPython
3407998
<reponame>aashiq075/PepeBot """Type `.df` or `.df <1-9>` reply to a photo or sticker """ from telethon.errors.rpcerrorlist import YouBlockedUserError from uniborg.util import admin_cmd @borg.on(admin_cmd(pattern='df(:? |$)(.*)?')) async def _(event): await event.edit("`Destroying Image...`") level = event.pat...
StarcoderdataPython
11249996
<reponame>loafbaker/-django_ecommerce1- """ Django settings for django_ecommerce1 project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the...
StarcoderdataPython
4876733
import tempfile import os import subprocess import shutil import sys import numpy from ase import Atoms, Atom def feff_edge_number(edge): edge_map = {} edge_map['k'] = 1 edge_map['l1'] = edge_map['li'] = 1 edge_map['l2'] = edge_map['lii'] = 3 edge_map['l3'] = edge_map['liii'] = 4 return edge...
StarcoderdataPython
3238476
<gh_stars>0 from pyspark.sql import Row import networkx as nx from splink_graph.cluster_metrics import ( cluster_main_stats, cluster_basic_stats, cluster_eb_modularity, cluster_lpg_modularity, cluster_avg_edge_betweenness, cluster_connectivity_stats, number_of_bridges, cluster_graph_hash...
StarcoderdataPython
216676
<reponame>kmoskovtsev/HOOMD-Blue-fork from hoomd import * from hoomd import deprecated from hoomd import hpmc import unittest import math # this script needs to be run on two ranks # initialize with one rank per partitions context.initialize() class muvt_updater_test(unittest.TestCase): def setUp(self): ...
StarcoderdataPython
8088014
class color(): def __init__(self,r,g,b): self.r = float(r) self.g = float(g) self.b = float(b) def __str__(self): return ("rgb(%d, %d, %d)" % (self.r, self.g, self.b)) def __repr__(self): return ("rgb(%d, %d, %d)" % (self.r, self.g, self.b)) def __add__(self, o...
StarcoderdataPython
391503
<reponame>sgg10/CIFO """User models admin.""" # Django from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin # Models from cifo.users.models import User @admin.register(User) class UserAdmin(BaseUserAdmin): list_display = ( 'identification', 'email', 'name', ...
StarcoderdataPython
1854041
<gh_stars>10-100 import os import pytest def pytest_addoption(parser): parser.addoption( "-E", action="store", metavar="NAME", help="only run tests matching the environment NAME.", ) parser.addoption( "--with-tox", default=False, action="store_true"...
StarcoderdataPython
6598514
<filename>Python-code-snippets-001-100/054-Awesome GUI date picker.py ''' 54-Awesome GUI Date Picker Modified (shambleized)from example code at: https://github.com/j4321/tkcalendar#documentation You may need to "pip install tkcalendar" <NAME>, feb 16th 2019. https://stevepython.wordpress.com ''' i...
StarcoderdataPython
250246
<reponame>MaxGSEO/Entity-Swissknife import requests import textrazor from google.cloud import language_v1 class TextRazorAnalyzer: def __init__(self, api_key): """ Initializes TextRazorAnalyzer Args: api_key (str): The API key for TextRazor """ textrazor.api_key = api_...
StarcoderdataPython
77824
<reponame>heinervdm/MysticMine #!/usr/bin/env python import random import pygame from koon.geo import Vec2D import koon.geo as geo from koon.gfx import SpriteFilm, Font, LoopAnimationTimer, PingPongTimer, Timer from koon.res import resman import pickups import event import tiles class PickupView: def __init__( ...
StarcoderdataPython
4956915
<gh_stars>0 import numpy as np import pandas as pd import timely_beliefs as tb from process_analytics.utils import data_utils from process_analytics.utils import forecast_utils def naive_forecaster( current_bdf: tb.BeliefsDataFrame, current_time: pd.Timestamp, FREQ: str, MAX_FORECAST_HORIZO...
StarcoderdataPython
6563366
<gh_stars>1-10 #!/usr/bin/env python3 -B import unittest from cromulent import vocab from tests import TestSalesPipelineOutput, classified_identifiers vocab.add_attribute_assignment_check() class PIRModelingTest_AR89(TestSalesPipelineOutput): def test_modeling_ar89(self): ''' AR-89: Naming of gr...
StarcoderdataPython
224361
import http from openbrokerapi.service_broker import LastOperation, OperationState from tests import BrokerTestCase class LastBindingOperationTest(BrokerTestCase): def setUp(self): self.broker.service_id.return_value = 'service-guid-here' def test_last_operation_called_just_with_required_fields(self...
StarcoderdataPython
27744
from ..utils.util import ObnizUtil class ObnizMeasure: def __init__(self, obniz): self.obniz = obniz self._reset() def _reset(self): self.observers = [] def echo(self, params): err = ObnizUtil._required_keys( params, ["io_pulse", "pulse", "pulse_width", "io_ec...
StarcoderdataPython
4880237
<gh_stars>1-10 from django import forms class SamlRequestForm(forms.Form): next = forms.CharField(widget=forms.HiddenInput)
StarcoderdataPython
204777
""" Created on Tue May 14, 2019 @author: <NAME> """ import tensorflow as tf import gc from parameters import * from process_data_text import * from process_data_audio import * from process_data_multimodal import * from model_text import * from model_multimodal_attention import * from evaluate_multimodal_attention i...
StarcoderdataPython
1961768
<reponame>Ali-Nawed/RLProjects from simulation_code.simulation_logic import * if __name__ == '__main__': runAndSaveSimulation()
StarcoderdataPython
12803207
from forecaster.mediate.telegram import TelegramMediator from forecaster.utils import get_conf from raven import Client def test_validate_tokens(): """validate tokens""" config = get_conf() telegram = config['TOKENS']['telegram'] sentry = config['TOKENS']['sentry'] bot = TelegramMediator(telegram,...
StarcoderdataPython
1798126
# -*- coding: utf-8 -*- from .xmlquery import XMLQuery class Parser(object): def __init__(self): pass def load(self, filename): pass def run(self): pass def parse(self, filename): self.load(filename) return self.run() class XMLParser(Parser): def __init__(self): super(XMLParser, self).__init__() ...
StarcoderdataPython
154512
<gh_stars>1-10 # coding: utf-8 # 学習したSSDモデルにinput_xを追加して、./model/以下に保存する import os import tensorflow as tf slim = tf.contrib.slim import sys sys.path.append('/home/ubuntu/notebooks/github/SSD-Tensorflow/') sys.path.append('../') from nets import ssd_vgg_300 from preprocessing import ssd_vgg_preprocessing from lib.ssd...
StarcoderdataPython
11281927
import pandas as pd import numpy as np import os import csv from tqdm import tqdm import argparse from glob import glob import faiss from multiprocessing import Pool, cpu_count from math import ceil def train_embedding_to_gpt2_data( data_path='qa_embeddings/bertffn_crossentropy.pkl', output_path='gpt2_train_d...
StarcoderdataPython
3222759
<filename>qualifier/qualifier.py<gh_stars>0 from typing import Any, List, Optional def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str: T = [] Li = [] Lb = [] C = [] B = [] x = 0 rows_length = [] for n in rows[0]: rows_it...
StarcoderdataPython
3465802
<gh_stars>1-10 from django.contrib import admin from .models import Squad_Article,Newsletter # Register your models here. class Squad_Article_Admin(admin.ModelAdmin): list_display=["author","role","server","min_rank","min_kd","publish",] admin.site.register(Squad_Article,Squad_Article_Admin) admin.site.register(Ne...
StarcoderdataPython
3438453
<reponame>zimolzak/wav-in-python import numpy as np import matplotlib.pyplot as plt import wave # so we can refer to its classes in type hint annotations from scipy import signal from typing import Generator import collections from printing import pretty_hex_string, ints2dots def bytes2int_list(byte_list: bytes) ->...
StarcoderdataPython
1915892
from model import Generator, Discriminator from torch.autograd import Variable from torchvision.utils import save_image import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import os import time import datetime from sys import exit from vgg import VGG16FeatureExtractor from loss import...
StarcoderdataPython
1867017
<reponame>YuTao0310/deepLearning # coding: UTF-8 """ @author: <NAME> """ from torch.autograd import Variable from torch.autograd import grad import torch.autograd as autograd import torch.nn as nn import torch import numpy as np def gradient_penalty(x, y, f): # interpolation shape = [x.size(0)] + [1] * (...
StarcoderdataPython
3586640
import pytest from subprocess import check_output from unittest.mock import Mock from ..client_config import ClientConfig def test_mariadb_server_logs_error_when_serverbin_invalid(mariadb_server): mocklog = Mock() server_bin = "invalid_mysqld" cfg = ClientConfig(mocklog, name="nonexistentcfg.json") # d...
StarcoderdataPython
3405317
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- from evenz.events import observable, event @observable class Dog(object): """ This is a dog that can bark. We can also listen for a 'barked' event. """ __test__ = False # Don't test the class. def __init__(self, name: str): sel...
StarcoderdataPython
96287
import os.path from bt_utils.console import Console from bt_utils.get_content import content_dir SHL = Console("BundestagsBot Template Command") # Use SHL.output(text) for all console based output! settings = { 'name': 'template', # name/invoke of your command 'mod_cmd': True, # if this cmd is only useabl...
StarcoderdataPython
1717970
from decimal import Decimal class Product: def __init__(self, productId = None, code = None, name = None, price = None, in_stock = None): self.productId = productId self.code = code self.name = name self.price = price self.in_stock = in_stock def printData(self): ...
StarcoderdataPython
12810381
# # Copyright 2016-2019 Crown Copyright # # 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 agreed to i...
StarcoderdataPython
328510
from argparse import Namespace from ml4ir.base.config.keys import TFRecordTypeKey from ml4ir.applications.classification.config.keys import LossKey, MetricKey from ml4ir.base.config.parse_args import RelevanceArgParser from typing import List class ClassificationArgParser(RelevanceArgParser): """ States de...
StarcoderdataPython
1894836
<reponame>rparini/cxroots<filename>cxroots/Derivative.py from __future__ import division import math import numpy as np from numpy import pi import numdifftools.fornberg as ndf @np.vectorize def CxDerivative(f, z0, n=1, contour=None, absIntegrationTol=1e-10, verbose=False): r""" Compute the derivaive of an a...
StarcoderdataPython
11261037
import os import sys import igraph as ig def read_sif(path, directed=True): ''' ''' nodes = set() edges = set() interactions = dict() with open(path, 'r') as sif: for line in sif: items = [item.strip() for item in line.split('\t') if item] print(items) ...
StarcoderdataPython
6454529
<gh_stars>0 # Enter your code here. Read input from STDIN. Print output to STDOUT import statistics n=int(input()) p=list(map(float,input().split())) q=list(map(float,input().split())) x=statistics.mean(p) y=statistics.mean(q) z=0 for i in range(n): z+=(p[i]-x)*(q[i]-y) M=0 N=0 for i in range(n): M+=(p[i]-x)...
StarcoderdataPython
3309248
"""Find REAPER resource path without ``reapy`` dist API enabled.""" import os import sys import reapy from .shared_library import is_windows, is_apple if not reapy.is_inside_reaper(): # Third-party imports crash REAPER when run inside it. import psutil def get_candidate_directories(detect_portable_install=...
StarcoderdataPython
1887383
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """ ================== prospect.utilities ================== Utility functions for prospect. """ import os, glob from pkg_resources import resource_string, resource_listdir import numpy as np import astropy.io.fits from astropy.t...
StarcoderdataPython
4847031
<reponame>Rohan-Raj-1729/myPackage #Imports from PIL import Image import numpy as np import matplotlib.pyplot as plt #from my_package.model import ObjectDetectionModel #from my_package.data import DataSet #from my_package.analysis import show_boxes from my_package.data.transforms import FlipImage, RescaleImage, BlurIma...
StarcoderdataPython
86619
pytest_plugins = ("pytester",) def test_help_message(testdir): result = testdir.runpytest("--help") # fnmatch_lines does an assertion internally result.stdout.fnmatch_lines( [ "stress:", "*--delay=DELAY*The amount of time to wait between each test loop.", "*--ho...
StarcoderdataPython
6505795
from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from .forms import * from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from .forms import CustomUserCreationForm # Create your views here. @login_...
StarcoderdataPython
1827637
<filename>buddymove_holidayiq.py from sqlalchemy import create_engine engine = create_engine('sqlite://', echo=False) import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/LambdaSchool/DS-Unit-3-Sprint-2-SQL-and-Databases/master/module1-introduction-to-sql/buddymove_holidayiq.csv') print(df....
StarcoderdataPython
6543303
""" RPC Provider using Requests Library """ __author__ = 'VMware, Inc.' __copyright__ = 'Copyright 2015-2017 VMware, Inc. All rights reserved. -- VMware Confidential' # pylint: disable=line-too-long import requests from vmware.vapi.lib.log import get_vapi_logger from vmware.vapi.protocol.client.http_lib import HT...
StarcoderdataPython
3461355
<gh_stars>0 def main(): """ testing to see how the assignment's datafile is organized: zip,eiaid,utility_name,state,service_type,ownership,comm_rate,ind_rate,res_rate zip = [0] name = [2] state = [3] comm_rate = [6] """ cumulative_rate_sum = 0 num_of_rates = 0 file_to_use = '...
StarcoderdataPython
157546
<gh_stars>100-1000 # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch class Stage2(torch.nn.Module): def __init__(self): super(Stage2, self).__init__() self.layer1 = torch.nn.Conv2d(192, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) self.layer2...
StarcoderdataPython
1809967
#! /usr/bin/python3 # # Copyright (c) 2019 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # # """.. _conf_00_lib_capture: Configuration API for capturing audio and video ----------------------------------------------- These capture objects are meant to be fed to the capture interface declaration of a targe...
StarcoderdataPython
11305250
from petroleum import PetroleumObject from petroleum.json_encoder import ToJSONMixin class ConditionalTask(PetroleumObject, ToJSONMixin): def __init__(self, task, condition, default=False): self.task = task self.condition = condition self.default = default
StarcoderdataPython
9641374
from __future__ import print_function from invoke import task from pprint import pformat @task def myfunc(ctx, *args, **kwargs): """ Note there is a bug where we couldn't do def mine(ctx, mypositionalarg, *args, **kwargs): pass But something is better than nothing :) Search "TODO 531" ...
StarcoderdataPython
1830748
<gh_stars>0 import enum class Orientation(enum.Enum): orthogonal = "orthogonal" isometric = "isometric" staggered = "staggered" hexagonal = "hexagonal" class RenderOrder(enum.Enum): right_down = "right-down" right_up = "right-up" left_down = "left-down" left_up = "left-up" class Stagg...
StarcoderdataPython
4935099
# Copyright 2020-2022 OpenDR European Project # # 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
3588936
from os import path from setuptools import setup HERE = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(HERE, 'README.md'), encoding='utf-8') as f: LONG_DESCRIPTION = f.read() setup( name='storm-indicator-pyqt', version='1.2.1', description='...
StarcoderdataPython
4826781
<gh_stars>1-10 import click import os import yaml import logging def execute(): add_subcommands() entry_point(obj={}) @click.group() @click.option('--log-level', default='info', help='Set the logging level. (default: info, options: debug|info|warning|error)') @click.option('--config-file', default='config/d...
StarcoderdataPython
11296485
"""Check live state management command.""" from datetime import datetime, timedelta, timezone import json import re from django.conf import settings from django.core.management.base import BaseCommand import boto3 from dateutil.parser import isoparse from marsha.core.defaults import RUNNING, STOPPING from marsha.cor...
StarcoderdataPython
1673458
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import json import gidgethub.sansio import importlib_resources import pytest from __app__.github import labels, news from . import samples class FakeGH: def __init__(self, *, getiter_=[]): self.post_ = [] ...
StarcoderdataPython
6404185
import argparse import h5py import json import os import scipy.misc import sys import zipfile import numpy as np import cv2 from os.path import join def get_pixels(mask): return np.sum(mask) def find_bbox(mask): contour, _ = cv2.findContours(im, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) x0, y0 = np.min(...
StarcoderdataPython
5032153
from lib import action class ListBulbsAction(action.BaseAction): def run(self): bulbs = {} lights = self.hue.state['lights'] for light_id, light in lights.iteritems(): bulbs["l%s" % light_id] = light['name'] return bulbs
StarcoderdataPython