id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1688070
# -*- coding: utf-8 -*- """ Created on Sun Jan 7 14:08:39 2018 @author: Alankar """ import numpy as np import matplotlib.pyplot as plt profile = np.loadtxt('stm.txt') x = np.arange(0,len(profile[0,:])+1,1) y = np.arange(0,len(profile[:,0])+1,1) plt.axis([0,len(x),0,len(y)]) plt.pcolormesh(profile,cmap...
StarcoderdataPython
133738
"""Jobs for performing electron phonon calculations in VASP.""" from __future__ import annotations import logging from dataclasses import dataclass, field from pathlib import Path from typing import Dict, List, Tuple import numpy as np from jobflow import Flow, Response, job from pymatgen.core import Structure from ...
StarcoderdataPython
61603
import logging import click from kfp import dsl from typing import List, Dict, Callable import kfp.dsl as dsl from hypermodel.hml.hml_pipeline import HmlPipeline from hypermodel.hml.hml_container_op import HmlContainerOp from hypermodel.platform.abstract.services import PlatformServicesBase @click.group(name="pipel...
StarcoderdataPython
1796207
import numpy as np from tqdm import trange from chapter04.car_rental_mine import cartesian_prod np.random.seed(5) class WindyWorld(object): def __init__(self, hight, width, start, end, wind_force): self.hight = hight self.width = width self.start = start self.end = end s...
StarcoderdataPython
1792494
<reponame>liamhiley/3D-ResNets-PyTorch<filename>edl.py import torch import torch.nn as nn import numpy as np def relu_evidence(logits): return torch.nn.ReLU(logits) def KL(alpha): beta = torch.from_numpy(np.ones((1, alpha.shape()[1]))) S_alpha = alpha.sum(axis=1, keep_dims=True) S_beta = beta.sum(axi...
StarcoderdataPython
110264
#!/usr/bin/env python import sys def main(number): result = 0 for i in range(1, number): if i % 3 == 0 or i % 5 == 0: result += i return result if __name__ == '__main__': print(main(int(sys.argv[1])))
StarcoderdataPython
3333480
from app.decorators import * from .models import Tag, Task __all__ = [ 'test_can_manage_task', 'test_can_manage_tag', 'can_change_task', 'can_insert_child_task' ] def test_can_manage_task(user, *args, **kwargs): """ タスクにアクセスする権限(表示, 編集, 削除)があるかを判定する関数 """ task = Task.objects.get(pk=kwargs['p...
StarcoderdataPython
123894
<filename>FrequencyQueries/Queries_SVK_On2.py #!/bin/python3 import os import sys from array import array def operation1(dic, word, dic_c): if (word in dic) and (dic[word] in dic_c): #if dic_c[dic[word]] > 0: dic_c[dic[word]] -= 1 dic[word] = dic.get(word, 0) + 1 dic_c[dic[word]] = dic_c....
StarcoderdataPython
131247
<filename>data_loader/rrd_storage.py # # Hubblemon - Yet another general purpose system monitor # # Copyright 2015 NAVER Corp. # # 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.a...
StarcoderdataPython
3310509
from collections.abc import AsyncIterator, Callable, Sequence from datetime import datetime, timezone from typing import Any from unittest import mock import pytest from platform_monitoring.logs import S3LogReader class TestS3LogReader: @pytest.fixture def s3_client(self) -> mock.Mock: return mock.M...
StarcoderdataPython
1708665
# WAP to demo Popen function of subprocess module import subprocess def foo(): print("Executed...") def main(): subprocess.call(['echo', '"to stdout"'], preexec_fn=foo) if __name__ == "__main__": main()
StarcoderdataPython
3304781
<filename>prestashop/scripts/prestashop.py # /usr/bin/python from sh import ls, printenv, Command, echo, chown, mkdir, wget, unzip, rm, php, chmod, mv from sh.contrib import git import sh, contextlib, os from releases import RELEASES, release_filename, REPO, release_extract_dir from config import CACHE_DIR, TMP_DIR, ...
StarcoderdataPython
18151
<gh_stars>1-10 import glob import os import re import sys import time import yaml def tail(thefile, past): if not past: thefile.seek(0, 2) while True: line = thefile.readline() if not line: time.sleep(0.5) continue line = line.rstrip("\n").rstrip("\r") ...
StarcoderdataPython
83861
import csv import json from reporting.utils import get_value_by_pattern from reporting.constants import LATENCY_ATTRIBUTE_MAPPING def parse_res_file(path): """Read data from file ends with ".res". Args: path (str): The position of the res file. Returns: incremental_metrics (list, json a...
StarcoderdataPython
94480
<gh_stars>1-10 from part1 import ( gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new, ) """ scenario: test_random_actions uuid: 613566861 """ """ random actions, total chaos """ board = gamma_new(7, 5, 4, 7) ...
StarcoderdataPython
3293519
import os from compile_utils import _remove_files_conflicting_with_decompile, _replace_renamed_files from decompilation_method import S4PyDecompilationMethod from settings import custom_scripts_for_decompile_source, game_folder, decompile_method_name, custom_scripts_for_decompile_destination, should_decompile_ea_scrip...
StarcoderdataPython
3398181
import numpy as np from tqdm import tqdm import module_split as module def make_unique_synth(set_t, images_set): '''Generates synthetic data for 191 channels using the seen images from the training map. set_t: Input the parameter set_t for indicating training or testing. images_set: Can be eithe...
StarcoderdataPython
1728885
<filename>settings/settings.py<gh_stars>0 # Settings file for the library import yaml from datetime import datetime class SurveySettingsError(Exception): pass class Settings(): def __init__(self): self.token = None self.valid_months = ["January", "February", "March", "April", "May", "June", ...
StarcoderdataPython
3369179
import argparse import torch parser = argparse.ArgumentParser(description='Removes the optimizer parameter.') parser.add_argument('--model', default='', type=str, metavar='PATH', required=True, help='path to the model in which the optimizer parameter will be removed.') def main(): args...
StarcoderdataPython
1750771
<reponame>E3SM-Project/acme_processflow import argparse import os import sys from Util import SUCCESS, FAILURE from Util import run_cmd parser = argparse.ArgumentParser(description="install conda", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("-w", "--w...
StarcoderdataPython
3285487
<reponame>QtonSolutions/sessh<gh_stars>0 import argparse import os if __name__ == '__main__': parser = argparse.ArgumentParser(description="Write the version number to __init__.py so it is available in sessh") parser.add_argument('version', help="version tag") args = parser.parse_args() init_path = o...
StarcoderdataPython
1625687
<gh_stars>1-10 from sqlalchemy import Column, Integer, String from sqlalchemy.orm import relationship from address import Address from base import Base class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(...
StarcoderdataPython
1732594
<reponame>DallasMorningNews/ardbeg from collections import OrderedDict defaults = { 'templatePath': "template", 'templateVersion': "", 'staticPath': "static", 'outputPath': "rendered", 'contentPath': "content", 'dataPath': "data", 'AWS_TEMPLATE_BUCKET':None, 'AWS_ACCESS_KEY_ID':None, 'AWS_SECRET_ACCESS_KEY':None,...
StarcoderdataPython
1720165
<reponame>tecknicaltom/home-assistant """Support for functionality to have conversations with Home Assistant.""" import logging import re import voluptuous as vol from homeassistant import core from homeassistant.components import http from homeassistant.components.http.data_validator import RequestDataValidator from...
StarcoderdataPython
3397328
<gh_stars>1-10 from types import SimpleNamespace import sys import traceback from unittest.mock import patch from filesystem_tree import FilesystemTree from pytest import raises, fixture from state_chain import StateChain, FunctionNotFound, IncompleteModification # fixtures # ======== @fixture def fs(): fs = F...
StarcoderdataPython
118219
<filename>core/commands_emitter.py<gh_stars>1-10 "Источник событий управления сервером (DServer)" from __future__ import annotations from rx.subject.subject import Subject from .atypes_emitter_decorator import AtypesEmitterDecorator class CommandsEmitter(AtypesEmitterDecorator): "Контейнер потоков команд" d...
StarcoderdataPython
1796298
from acconeer_utils.clients.reg.client import RegClient, RegSPIClient from acconeer_utils.clients.json.client import JSONClient from acconeer_utils.clients import configs from acconeer_utils import example_utils def main(): args = example_utils.ExampleArgumentParser().parse_args() example_utils.config_logging...
StarcoderdataPython
1628812
""" Utility functions and mixins used in tests. """ from PIL import Image from django.contrib.sessions.backends.base import SessionBase from django.core.files import File from django.test import RequestFactory from django.urls import resolve from io import BytesIO from unittest.mock import MagicMock class RouteTeste...
StarcoderdataPython
1679086
<filename>openGaussBase/testcase/SQL/DDL/group/drop_group/Opengauss_Function_DDL_Drop_Group_Case0001.py<gh_stars>0 """ Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of ...
StarcoderdataPython
199809
int1 = input("Enter first integer: ") int2 = input("Enter second integer: ") sum = int(int1) + int(int2) if sum in range(105, 201): print(200)
StarcoderdataPython
1771520
"""Module for communicating with the Arduino via I2c and a custom function buffer""" __author__ = "<NAME>" __copyright__ = "Copyright (c) 2020 <NAME>. All rights reserved." __license__ = "MIT" __version__ = "0.1" from enum import IntEnum, unique from typing import Any, Dict, List, Tuple from simple_i2c import read_by...
StarcoderdataPython
1745215
#!/usr/bin/env python # coding=utf-8 try: import mock except ImportError: import unittest.mock as mock from marvin_iris_h2o_automl.prediction import PredictionPreparator class TestPredictionPreparator: def test_execute(self, mocked_params): ac = PredictionPreparator() ac.execute(input_m...
StarcoderdataPython
3290457
<reponame>Delaney6/clusterfuzz<filename>src/python/bot/minimizer/basic_minimizers.py<gh_stars>1-10 # Copyright 2019 Google LLC # # 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://...
StarcoderdataPython
3233239
import requests r = requests.post('http://12172.16.31.10:8001/test/command', json={'params': 'Hello'}) print(r.json())
StarcoderdataPython
133711
<filename>guild/commands/remote_impl_support.py<gh_stars>1-10 # Copyright 2017-2019 TensorHub, 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-...
StarcoderdataPython
3240002
from healthcheck.settings.base import * # noqa: F403 SECRET_KEY = env.str("SECRET_KEY", "testsecretkey") # noqa: F405 DEBUG = env.bool("DEBUG", True) # noqa: F405 DATABASES = { "default": env.db( # noqa: F405 default="postgres://postgres:postgres@localhost:5432/healthcheck" ), } ALLOWED_HOSTS = env...
StarcoderdataPython
1607191
# # Copyright 2004,2005 <NAME> <<EMAIL>> # # This file forms part of Infotrope Polymer. # # Infotrope Polymer 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 2 of the License, or # (at your opti...
StarcoderdataPython
1668207
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2018, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
StarcoderdataPython
1766555
<reponame>learning310/U-Time import matplotlib.pyplot as plt import numpy as np import os def get_hypnogram(y_pred, y_true=None, id_=None): def format_ax(ax): ax.set_xlabel("Period number") ax.set_ylabel("Sleep stage") ax.set_yticks(range(6)) ax.set_yticklabels(["Wake", "N1", "N2",...
StarcoderdataPython
3244926
<reponame>mahmuuud/pip-accel # Simple Python script that helps to understand the AppVeyor environment. # # Author: <NAME> <<EMAIL>> # Last Change: November 11, 2015 # URL: https://github.com/paylogic/pip-accel """Introspection of the AppVeyor CI environment ...""" # Standard library modules. import os # External dep...
StarcoderdataPython
105707
<filename>modules.py def rm_duplicates(df): subset_status = str(input("Do you want to specify a subset of columns?(Y/N): ")) if subset_status.capitalize() == "N": num_of_duplicates = str(df.duplicated().sum()) print("There is " + num_of_duplicates + " duplicated rows.\n") remov...
StarcoderdataPython
1730818
<filename>contracts/migrations/0022_remove_piid.py # -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-05-18 11:10 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('contracts', '0021_idv_piid_verbose_name'), ]...
StarcoderdataPython
3354275
#!/usr/bin/env python """ convertlog: Read ASCII trailer file and convert it to a waivered-FITS file. License: http://www.stsci.edu/resources/software_hardware/pyraf/LICENSE Usage: convertlog.py [OPTIONS] trailer_filename :Options: -h print the help (...
StarcoderdataPython
1762381
<reponame>Noah-Huppert/salt """ tests.integration.conftest ~~~~~~~~~~~~~~~~~~~~~~~~~~ Integration tests PyTest configuration/fixtures """ import logging import pytest log = logging.getLogger(__name__) @pytest.fixture(scope="package", autouse=True) def salt_master(salt_master_factory): """ A run...
StarcoderdataPython
126768
<reponame>da1107/python2a import sys import time FILENAME = "eng_vocab.txt" #FILENAME = "dogcat.txt" class MyFileContextManager(): def __init__(self,filename,operation): try: self._file=open(filename,operation) except: print('File not found') sys.exit() ...
StarcoderdataPython
23498
import pygame FPS = 60 BLOCK_SIZE = 48 COLOR_BACKGROUND = pygame.Color(0, 0, 0)
StarcoderdataPython
3364953
<filename>homework_3/viola_jones.py<gh_stars>0 import numpy as np import numpy.linalg as linalg import skimage.color as skimage import PIL from PIL import Image, ImageDraw import timeit D = 64 TRAINING_SIZE = 1000 class WeakLearner: """A simple container class to store information defining a given weak learner"...
StarcoderdataPython
3215891
<reponame>mohnbroetchen2/cykel_jenarad # Generated by Django 2.2.4 on 2020-03-17 19:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("bikesharing", "0018_auto_20200204_2147"), ] operations = [ migration...
StarcoderdataPython
3362255
<reponame>rgraebert/skia #!/usr/bin/python """ Copyright 2013 Google Inc. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. Calulate differences between image pairs, and store them in a database. """ import contextlib import csv import logging import os import re impo...
StarcoderdataPython
1677456
<gh_stars>1-10 import json import unittest import hcl2 # This group of tests is used to confirm assumptions about how the hcl2 library parses into json. # We want to make sure important assumptions are caught if behavior changes. class TestHCL2LoadAssumptions(unittest.TestCase): def test_ternary(self): #...
StarcoderdataPython
54238
#!/usr/bin/env python3 #-*- coding: utf-8 -*- # # PlayonCloud recorder # # update-alternatives --install /usr/bin/python python /usr/bin/python3.7 2 # sudo apt-get install chromium-chromedriver # sudo apt-get install libxml2-dev libxslt-dev python-dev # which python3 (make sure that path is /usr/bin/python3) # # Fin...
StarcoderdataPython
3290732
<reponame>chaitanya-ycr/arduino #! /usr/bin/env python # -*- coding: utf-8 -*- # # GUI module generated by PAGE version 6.2 # in conjunction with Tcl version 8.6 # Jul 13, 2021 11:30:50 AM IST platform: Windows NT import sys try: import Tkinter as tk except ImportError: import tkinter as tk try: im...
StarcoderdataPython
4834932
import pandas as pd import numpy as np df = pd.read_csv('apktool/country-codes.csv') country_dial = 0 # Return 0 if no country matched country = 'cHiNa' columns = ['CLDR display name','ISO3166-1-Alpha-2','ISO3166-1-Alpha-3'] country_match = np.where(df[columns].apply(lambda x: x.astype(str).str.lower()).eq(country.l...
StarcoderdataPython
1648984
<gh_stars>0 #!/usr/bin/env python # Copyright (c) <NAME> <<EMAIL>> # Copyright (c) <NAME> <<EMAIL>> # # 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/LICEN...
StarcoderdataPython
3331698
<filename>xclim/testing/__init__.py """Helpers for testing xclim.""" from ._utils import *
StarcoderdataPython
48151
<filename>src/aws_environments/migrations/0019_environmentvariable.py<gh_stars>0 # Generated by Django 3.0.2 on 2020-03-18 18:28 from django.db import migrations, models import django.db.models.deletion import fernet_fields.fields class Migration(migrations.Migration): dependencies = [ ("organizations",...
StarcoderdataPython
165052
from copy import copy from typing import List, Optional from didcomm.common.types import DID_URL, DID from didcomm.did_doc.did_doc import DIDDoc, VerificationMethod, DIDCommService from didcomm.did_doc.did_resolver import DIDResolver from didcomm.secrets.secrets_resolver import SecretsResolver, Secret class TestDIDD...
StarcoderdataPython
3388683
# -*- coding: utf-8 -*- """Generate a default configuration-file section for fn_cisco_umbrella_inv""" from __future__ import print_function def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = ...
StarcoderdataPython
24134
<reponame>kkraus14/cuspatial<filename>python/cuspatial/cuspatial/utils/traj_utils.py def get_ts_struct(ts): y=ts&0x3f ts=ts>>6 m=ts&0xf ts=ts>>4 d=ts&0x1f ts=ts>>5 hh=ts&0x1f ts=ts>>5 mm=ts&0x3f ts=ts>>6 ss=ts&0x3f ts=ts>>6 wd=ts&0x8 ts=ts>>3 yd=ts&0x1ff ts=ts>>9 ms=ts&0x3ff ts=ts>>10 pid=ts&0x3ff ...
StarcoderdataPython
1770715
from setuptools import setup, find_packages import os import io with io.open(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", 'README.rst')), encoding="utf-8") as f: long_description = f.read() with io.open(os.path.abspath(os.path.join(os.pat...
StarcoderdataPython
3204916
<reponame>Indexical-Metrics-Measure-Advisory/watchmen-data-processor<filename>watchmen/pipeline/core/context/unit_context.py from watchmen.monitor.model.pipeline_monitor import UnitRunStatus from watchmen.pipeline.core.context.stage_context import StageContext from watchmen.pipeline.model.pipeline import ProcessUnit ...
StarcoderdataPython
3310778
from model.group import Group testdata = [ Group(name = "name1", footer="footer1", header = "header1"), Group(name = "name2", footer="footer2", header = "header2") ]
StarcoderdataPython
3259620
from datetime import date, datetime, time, timedelta from pathlib import Path from typing import List, cast import pytest from _pytest.monkeypatch import MonkeyPatch from dateutil.tz import UTC from articat.artifact import EXECUTION_URL_ENV_NAME, ID, Metadata from articat.fs_artifact import FSArtifact from articat.te...
StarcoderdataPython
4810893
<reponame>EspaceNetworks/pygooglevoice from googlevoice import Voice def test_delete(): voice = Voice() # voice.login() #for message in voice.sms().messages: # if message.isRead: # message.delete() assert 1 == 1
StarcoderdataPython
3264030
<reponame>LeandroLFE/capmon from db.connect.instanciaAtualDB import atualDB from db.scripts.script_select.select_canais import select_canais_ativos class Event_Ready_DB_Connect(): def __init__(self) -> None: pass @atualDB.select_table_many_data async def consulta_canais_ativos(self, dados = {}): ...
StarcoderdataPython
4803121
from django.shortcuts import render, get_object_or_404, reverse from django.http import Http404, HttpResponseRedirect from django.template import loader from .models import Question # Create your views here. def index(request): # return HttpResponse("<h1> Hello World </h1>") latest_q = Question.objects.order...
StarcoderdataPython
117985
from __future__ import absolute_import, division, print_function, unicode_literals from keras import backend as K import tensorflow as tf from tensorflow.keras import layers import os import time import matplotlib.pyplot as plt from nc_loader import ERA5Dataset def Unet(): concat_axis = 3 inputs = layers.In...
StarcoderdataPython
18056
from rest_framework.pagination import LimitOffsetPagination, PageNumberPagination class CategoryLimitPagination(PageNumberPagination): page_size = 20 page_size_query_param = 'page_size' max_page_size = 40 class ProductLimitPagination(PageNumberPagination): page_size = 20 page_size_query_param = ...
StarcoderdataPython
12233
# -*- coding: utf-8 -*- """ setup.py script """ import io from collections import OrderedDict from setuptools import setup, find_packages with io.open('README.md', 'rt', encoding='utf8') as f: README = f.read() setup( name='reportbuilder', version='0.0.1', url='http://github.com/giovannicuriel/report...
StarcoderdataPython
3246500
<reponame>icannistraci/nerfmm import torch import torch.nn as nn import torch.nn.parallel import torch.utils.data class OfficialNerf(nn.Module): def __init__(self, pos_in_dims, dir_in_dims, D): """ :param pos_in_dims: scalar, number of channels of encoded positions :param dir_in_dims: scal...
StarcoderdataPython
3366136
""" OrderedDict variants of the default base classes. """ from collections import OrderedDict from .graph import Graph from .multigraph import MultiGraph from .digraph import DiGraph from .multidigraph import MultiDiGraph __all__ = [] __all__.extend([ 'OrderedGraph', 'OrderedDiGraph', 'OrderedMultiGraph...
StarcoderdataPython
92654
<reponame>zengxinzhy/HiDT<filename>grid.py<gh_stars>0 import torch import sys import coremltools as ct class Grid(torch.nn.Module): def __init__(self): super().__init__() def forward(self, content): [c, h, w] = content.shape h = h // 4 w = w // 4 return content.reshape...
StarcoderdataPython
3249755
<filename>src/ralph_assets/history/receivers.py # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from ralph_assets.history.utils import HistoryContext def pre_save(sender, instance, **kwargs):...
StarcoderdataPython
1644892
<reponame>bounty030/Coursera import matplotlib as mpl import matplotlib.pyplot as plt import pandas as pd import numpy as np mpl.style.use('ggplot') # optional: for ggplot-like style #--------------------------pandas Basics path = '/home/tbfk/Documents/VSC/Coursera/Applied_Data_Science_Specialization_IBM/Data_Visuali...
StarcoderdataPython
4807665
<reponame>fredrikwahlberg/das2018 # -*- coding: utf-8 -*- """ Writer identification based of shape context codebook features and a shared kernel GP classifier. This file covers feature extraction given the parameter distribution below. @author: <NAME> <<EMAIL>> """ from __future__ import print_function, division imp...
StarcoderdataPython
181446
<filename>chanjo/store/models.py<gh_stars>0 # -*- coding: utf-8 -*- from collections import namedtuple from datetime import datetime from alchy import ModelBase, make_declarative_base from sqlalchemy import Column, types, ForeignKey, UniqueConstraint, orm Exon = namedtuple('Exon', ['chrom', 'start', 'end', 'completen...
StarcoderdataPython
4813361
'''input internationalization i18n ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem B if __name__ == '__main__': s = input() print(s[0] + str(len(s) - 2) + s[-1])
StarcoderdataPython
3355816
<reponame>matt-peters/jiant ## # Helper libraries for #datascience on Edge-Probing data. import sys import os import io import json import collections import itertools import logging as log import pandas as pd import numpy as np from sklearn import metrics from src import utils from allennlp.data import Vocabulary ...
StarcoderdataPython
3344869
""" pandaspyomo: read data from coopr.pyomo models to pandas DataFrames Pyomo is a GAMS-like model description language for mathematical optimization problems. This module provides functions to read data from Pyomo model instances and result objects. Use list_entities to get a list of all entities (sets, params, vari...
StarcoderdataPython
37635
import torch, math, copy import scipy.sparse as sp import numpy as np from torch.nn.modules.module import Module import torch.nn as nn from torch.nn.parameter import Parameter def normalize(adj, device='cpu'): if isinstance(adj, torch.Tensor): adj_ = adj.to(device) elif isinstance(adj, sp.c...
StarcoderdataPython
3343218
import logging from pathlib import Path import altair as alt import pandas as pd import requests import streamlit as st import streamlit.components.v1 as components st.set_page_config(layout="wide") st.title("Bundes-Notbremse Ampel") pd.set_option('precision', 2) def is_covid_file_up_to_date(): covid_path = Path...
StarcoderdataPython
76503
import alleviate mode = 'r' def main(): try: open('text.py', mode) except Exception as e: alleviate.exception(e)#, output=alleviate.Output.JSON) main()
StarcoderdataPython
1707223
# -*- coding: utf-8 -*- # # Copyright (C) 2003-2009 Edgewall Software # Copyright (C) 2013 <NAME> <<EMAIL>> # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # import difflib import re import unittest from trac.util.text import to_unicode fr...
StarcoderdataPython
192621
<reponame>dhakal0kushal/Website-API from rest_framework.viewsets import ModelViewSet from v1.third_party.rest_framework.permissions import IsStaffOrReadOnly from ..models.slack_channel import SlackChannel from ..serializers.team import SlackChannelSerializer class SlackChannelViewSet(ModelViewSet): queryset = Sl...
StarcoderdataPython
173300
<gh_stars>0 """ 130. Heapify""" class Solution: """ @param: A: Given an integer array @return: nothing """ def heapify(self, A): # write your code here for i in range(len(A) // 2, -1, -1): self.siftdown(A, i) def siftdown(self, A, k): while k < len(A): ...
StarcoderdataPython
80367
# A file containing mappings of CC -> MC file names # Pack version 3 VER3 = { 'char.png': 'minecraft/textures/entity/steve.png', 'chicken.png': 'minecraft/textures/entity/chicken.png', 'creeper.png': 'minecraft/textures/entity/creeper/creeper.png', 'pig.png': 'minecraft/textures/entity/pig/pig.png', ...
StarcoderdataPython
182284
import unittest import os import shutil import installer_utils class TestInstallerUtils(unittest.TestCase): def test_modify_ram(self): datadir = os.path.join( os.path.dirname(__file__), 'data') batfile = os.path.join(datadir, 'gpt.bat') vmoptionsfile = os.path.join(data...
StarcoderdataPython
3236888
import os import glob print("Files from the parent dir : " + str(glob.glob("*"))) FDP_URL = os.environ['FDP_URL'] FDP_USERNAME = os.environ['FDP_USERNAME'] FDP_PASSWORD = os.environ['FDP_PASSWORD'] FDP_PERSISTENT_URL = os.environ['FDP_PERSISTENT_URL'] INPUT_FILE = os.environ['INPUT_FILE']
StarcoderdataPython
1707412
# -*- coding: utf-8 -*- class Tokenizer: def __init__(self, lang='en'): import stanza try: self.pipeline = stanza.Pipeline(lang=lang, processors='tokenize', verbose=False, tokenize_no_ssplit=True) except Exception: stanza.download(lang=lang, resources_url='stanford...
StarcoderdataPython
176369
<reponame>Rydeness/ptychogpu import time import numpy as np import acc_image_utils_piotr as acc ori_size = 64 new_size = 32 n1 = np.zeros((ori_size,ori_size,ori_size,ori_size),dtype=np.float32) loop_tester = 3 tsum = 0.0 for ii in range(loop_tester): t1 = -time.time() n2 = acc.cupy_jit_resizer4D(n1,(new_size,n...
StarcoderdataPython
196871
from __future__ import unicode_literals import json from .common import InfoExtractor from ..utils import ( float_or_none, int_or_none, sanitized_Request, ) class CollegeRamaIE(InfoExtractor): _VALID_URL = r'https?://collegerama\.tudelft\.nl/Mediasite/Play/(?P<id>[\da-f]+)' _TESTS = [ { ...
StarcoderdataPython
3226074
from django import forms from django.utils.translation import gettext as _ from dcim.models import DeviceRole, Platform, Region, Site, SiteGroup from extras.forms import CustomFieldModelFilterForm, LocalConfigContextFilterForm from tenancy.forms import TenancyFilterForm, ContactModelFilterForm from utilities.forms imp...
StarcoderdataPython
1640304
<reponame>ahillbs/minimum_scan_cover<gh_stars>0 from os import cpu_count from typing import List, Dict, Union, Optional import math from fractions import Fraction import numpy as np from ortools.sat.python import cp_model from .. import Solver from utils import Multidict, get_angles, convert_graph_to_angular_abstract...
StarcoderdataPython
5183
<reponame>freehackquest/libfhqcli-py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2020-2021 FreeHackQuest Team <<EMAIL>> """This file was automatically generated by fhq-server Version: v0.2.47 Date: 2022-01-01 07:15:35 """ from freehackquest_libclient_py.freehackquest_client import FreeHackQuestClient...
StarcoderdataPython
3394430
"""Support for EvoHome HeatingSetPoint.""" from typing import Any, Dict, Optional from homeassistant.components.climate import SUPPORT_TARGET_TEMPERATURE, ClimateEntity from homeassistant.components.climate.const import HVAC_MODE_HEAT from homeassistant.const import ( ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_F...
StarcoderdataPython
3278906
from fts.backends.base import InvalidFtsBackendError raise InvalidFtsBackendError("MySQL FTS backend not yet implemented")
StarcoderdataPython
3375025
<reponame>gleybersonandrade/kytos-challenge """Defines Packet classes and related items.""" # System imports from enum import IntEnum class Type(IntEnum): """Enumeration of Packet Types.""" OFPT_HELLO = 0 OFPT_ERROR = 1 OFPT_ECHO_REQUEST = 2 OFPT_ECHO_REPLY = 3 OFPT_VENDOR = 4 OFPT_FEATUR...
StarcoderdataPython
4825795
'''Animal Shelter. An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis. People must adopt either the "oldest" (based on arrival time) of all animals in the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of th...
StarcoderdataPython
4825331
# 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
1781649
from unittest import mock import responses from django.test import TestCase, Client from django.urls import reverse from model_mommy import mommy from battles.models import Battle from common.constants import POKEAPI_BASE_URL from users.models import User class BattleListViewTests(TestCase): def setUp(self): ...
StarcoderdataPython