id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1712789
# # Adapter for com.vividsolutions.jts.geom.Envelope # # # SOFTWARE HISTORY # # Date Ticket# Engineer Description # ------------ ---------- ----------- -------------------------- # 05/29/13 2023 dgilling Initial Creation. # from dynamicserialize.dstype...
StarcoderdataPython
1764472
<filename>office365/runtime/client_object.py import importlib from office365.runtime.odata.odata_metadata_level import ODataMetadataLevel # Fixes some issues with TLS import os os.environ['REQUESTS_CA_BUNDLE'] = 'ca.pem'; class ClientObject(object): """Base client object""" def __init__(self, context, resou...
StarcoderdataPython
3331079
<gh_stars>1-10 import os import os.path import pypandoc import codecs # Navigation table appended to the end of every page _BOTTOM_TABLE = 'Indices and Tables\n'\ '==================\n\n'\ '* :ref:`genindex`\n'\ '* :ref:`modindex`\n'\ '* :ref:`search`\n'\...
StarcoderdataPython
1753290
"""Tests for the models of the activeusers app.""" from django.test import TestCase from activeusers.models import Visitor class VisitorModelTestCase(TestCase): """Tests for the ``Visitor`` model.""" def test_model(self): self.assertTrue(True)
StarcoderdataPython
1734256
<reponame>webbyfox/tasklist from django.http import HttpResponse # from django.views.decorators.csrf import csrf_exempt # from rest_framework.renderers import JSONRenderer # from rest_framework.parsers import JSONParser # from .models import Task # from .serializers import TaskSerializer from rest_framework import st...
StarcoderdataPython
1726451
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, <NAME> (@vasilyprokopov) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
StarcoderdataPython
37935
<reponame>didi/MeetDot """ The main responsibilites of PostTranslation class are: 1) initialize given strategy 2) take API request 3) remove profanity 4) return translation text after these processes Post-translation API input: { "session_id": unique session ID, "strategies": list of strategies want to be app...
StarcoderdataPython
3277735
import numpy as np def calc_episode_return(rewards, gamma: float = 1.0): rewards = np.array(rewards) gammas = gamma * np.ones_like(rewards) gammas[0] = 1.0 gammas = np.cumprod(gammas) return np.sum(rewards * gammas) def calc_average_return(rewards_batch, gamma: float = 1.0): return np.mean...
StarcoderdataPython
3325649
<gh_stars>1-10 from bento.commands.core \ import \ HelpCommand from bento.commands.configure \ import \ ConfigureCommand from bento.commands.build \ import \ BuildCommand from bento.commands.install \ import \ InstallCommand from bento.commands.parse \ import \ ...
StarcoderdataPython
3299820
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ The :mod:`autostopwordgen.generator` module implements a research paper published by Olatunde et al., https://www.researchgate.net/publication/318969652_AN_AUTO-GENERATED_APPROACH_OF_STOP_WORDS_USING_AGGREGATED_ANALYSIS Created on Sat Feb 2 20:50:34 2019 @author: <N...
StarcoderdataPython
1723503
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class Payload_Protocol_Type(Base): __slots__ = () _SDM_NAME = 'payloadProtocolType' _SDM_ATT_MAP = { 'Payload Protocol Id (EtherType)': 'payloadProtocolType.header.payloadProtocolId', } def __init__(self, pare...
StarcoderdataPython
1711258
<filename>tests/test_core/test_bessel.py # from volust.volgpu import * # from volust.volgpu.oclalgos import * # # import itertools # import numpy as np # # import time # # # import os # import sys # # from numpy import * # from scipy.special import * # # def absPath(myPath): # """ Get absolute path to resource, wor...
StarcoderdataPython
1754334
<filename>menpo3d/rasterize/cpu.py import numpy as np from menpo.transform.piecewiseaffine.base import barycentric_vectors from menpo.image import BooleanImage, MaskedImage def _pixels_to_check_python(start, end, _): pixel_locations = [] tri_indices = [] for i, ((s_x, s_y), (e_x, e_y)) in enumerate(zip(s...
StarcoderdataPython
1673239
<reponame>achaiah/pywick from pywick.optimizers.lookahead import * from torch.optim import SGD class LookaheadSGD(Lookahead): def __init__(self, params, lr, alpha=0.5, k=6, momentum=0.9, dampening=0, weight_decay=0.0001, nesterov=False): """ Combination of SGD + LookAhead :param params: ...
StarcoderdataPython
43546
""" Use this file to configure pluggable app settings and resolve defaults with any overrides set in project settings. """ from django.conf import settings as project_settings class Settings: pass Settings.SECRET_KEY = getattr( project_settings, "SLACKFORMS_SECRET_KEY", "a-bad-secret-key" ) Settings.SLACK...
StarcoderdataPython
92823
# Copyright (C) 2008-today The SG++ project # This file is part of the SG++ project. For conditions of distribution and # use, please see the copyright notice provided with SG++ or at # sgpp.sparsegrids.org from Learner import Learner, LearnerEvents from pysgpp import DataVector, SurplusRefinementFunctor from math...
StarcoderdataPython
3340079
<reponame>zarghamabbas/python-learning-hackerrank import re def checkIfValid(regex): is_valid = False try: re.compile(regex) is_valid = True except re.error: is_valid = False return is_valid num = int(input()) result = [] if(num > 0 and num < 100): for i in range(0, num): regexToCheck = in...
StarcoderdataPython
1735452
from setuptools import setup, find_packages import re with open('README.md', 'r') as fh: long_description = fh.read() setup( name='dilltorch', # this is the name of the package as you will import it i.e import package-name version=0.1, author='<NAME>', author_email='<EMAIL>', description='Dee...
StarcoderdataPython
1611815
<filename>forest_encounter.py<gh_stars>0 from roll import roll # Source: http://dndspeak.com/2018/02/100-forest-encounters/ table = [ ( "A great elk is seen watching the party from a distance. It almost looks as if the elk is wearing a crown made of twigs and vines.", 1, ), ( "A pa...
StarcoderdataPython
3372977
import scipy.misc, numpy as np, os, sys def save_img(out_path, img): img = np.clip(img, 0, 255).astype(np.uint8) scipy.misc.imsave(out_path, img) def scale_img(style_path, style_scale): scale = float(style_scale) o0, o1, o2 = scipy.misc.imread(style_path, mode='RGB').shape scale = float(style_scal...
StarcoderdataPython
65330
<reponame>kelvin-wahome/Instaclone from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from . import views urlpatterns=[ url('^$',views.index,name = 'indexpage'), url(r'^profile/',views.profile,name ='profile'), url(r'^user/(\d+)$', views.profile, nam...
StarcoderdataPython
148123
import tensorflow as tf weight = tf.Variable(1.0,name="weight") input_value = tf.constant(0.5,name="input_value") expected_output = tf.constant(0.0,name="expected_output") model = tf.multiply(input_value,weight,"model") loss_function = tf.pow(expected_output - model,2,name="loss_function") optimizer = tf.train.Gradie...
StarcoderdataPython
4804477
# coding: utf-8 # MIT License # # Copyright (c) 2018 <NAME>, 4IF, INSA Lyon # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to...
StarcoderdataPython
13280
from pathlib import Path from typing import Dict from eodatasets3 import serialise from .common import assert_same, dump_roundtrip def test_valid_document_works(tmp_path: Path, example_metadata: Dict): generated_doc = dump_roundtrip(example_metadata) # Do a serialisation roundtrip and check that it's still ...
StarcoderdataPython
4828939
<reponame>ifsheldon/billiard_game<gh_stars>0 import os import numpy as np import pyverilator from . import to_float, to_fix_point_int def normalize_vector(vector): return vector / np.sqrt((vector ** 2).sum()) def test_cross_product(): os.chdir("./pyverilog") sim = pyverilator.PyVerilator.build("cross_...
StarcoderdataPython
3240225
<reponame>whatnick/eo-datasets """ Make a HDF5 file much smaller by shrinking all embedded images. (Intended for creating test datasets where the pixels don't matter much but the structure does. The downsampling is dirty.) """ import re from pathlib import Path from typing import List, Optional import click import h5...
StarcoderdataPython
169106
<filename>BOJ2530.py<gh_stars>1-10 h,m,s = map(int, input().split()) s += (m*60 + h*3600 + int(input())) h = s//3600 m = (s%3600)//60 s = (s%3600)%60 if h>23: h %= 24 print(h,m,s)
StarcoderdataPython
3325522
#!/usr/bin/env python3 # pylama:ignore=E501 """Read JSON tweets from stdin and write CSV to stdout.""" import sys import csv from common import log, json_parse, read_time COLUMNS = [ "TweetID", # 64-bit int "UserID", # 64-bit int "UserScreenName", # string "UserName", # str...
StarcoderdataPython
3247413
<filename>summary.py """牌譜実況プログラム""" # -*- coding: utf-8 -*- import urllib.request import urllib.parse import xml.etree.ElementTree as ET import math import re from enum import Enum from functools import cmp_to_key # https://gist.github.com/nullpos/d6a10e1f4b1f906d8b6d import io import sys sys.stdin = io....
StarcoderdataPython
3367978
<gh_stars>0 from rest_framework import serializers from .models import * class UporabniDioSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UporabniDio fields = '__all__' class SlikaSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Slika ...
StarcoderdataPython
3393047
""" Entrypoint for the frontend modules flask.app """ from flask import Flask import os def create_flask_app(): app = Flask(__name__) return app app = create_flask_app() # Configure application logger from .logging import configure_logger configure_logger() # Apply configurations # to the Flask instance #...
StarcoderdataPython
1764213
<reponame>ec500-software-engineering/exercise-2-ffmpeg-shiluwu23<filename>ffprobe.py import subprocess import json from pathlib import Path def ffprobe_sync(filein: Path) -> dict: """ get media metadata """ meta_json = subprocess.check_output([ 'ffprobe', '-v', 'warning', '-print_format', 'jso...
StarcoderdataPython
3396321
<reponame>herrlich10/mripy<filename>setup.py<gh_stars>1-10 import setuptools import mripy from os import path setup_dir = path.dirname(path.realpath(__file__)) with open(f'{setup_dir}/README.rst', 'r') as f: long_description = f.read() setuptools.setup( name='mripy', version=mripy.__version__, author='he...
StarcoderdataPython
4807556
<filename>aws/logs_monitoring/tools/integration_tests/recorder/pb/trace_pb2.py # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: trace.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import refle...
StarcoderdataPython
1727492
<reponame>pablobesada/tw<filename>frontend/analytics.py #!/usr/bin/python import httplib2 from apiclient.discovery import build from oauth2client.client import flow_from_clientsecrets, OAuth2WebServerFlow from oauth2client.file import Storage from oauth2client.tools import run CLIENT_SECRETS = 'client_secrets.json'...
StarcoderdataPython
4805965
from datetime import datetime, timedelta import functools import os from typing import Callable, Dict, Hashable from bs4 import BeautifulSoup from dask.diagnostics import ProgressBar import fsspec from fsspec.implementations.local import LocalFileSystem from fsspec_reference_maker.hdf import SingleHdf5ToZarr import pa...
StarcoderdataPython
3302876
#!/usr/bin/env python 2.7 # -*- coding: utf-8 -*- # # Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved # """ brief Authors: panxu(<EMAIL>) Date: 2018/12/19 07:53:00 """ a = [[[1, 2], [3, 4]]] class A(object): def __call__(self, *input, **kwargs): print(input) print(*input) # pr...
StarcoderdataPython
3391486
# pylint: disable-msg=W0611, W0612, W0511,R0201 """Tests suite for MaskedArray & subclassing. :author: <NAME> & <NAME> :contact: pierregm_at_uga_dot_edu & mattknox_ca_at_hotmail_dot_com :version: $Id: test_filters.py 2819 2007-03-03 23:00:20Z pierregm $ """ __author__ = "<NAME> & <NAME> ($Author: pierregm $)" __revisi...
StarcoderdataPython
198116
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # Copyright 2017 ROBOTIS CO., LTD. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
StarcoderdataPython
106621
from numpy import array def scigrid_2011_01_04_13(): ppc = {"version": '2'} ppc["baseMVA"] = 100.0 ppc["bus"] = array([ [586, 3, 0, 0, 0, 0, 0, 1.0, 0, 220.0, 0, 1.1, 0.9 ], [589, 2, 0, 0, 0, 0, 0, 1.0, 0, 380.0, 0, 1.1, 0.9 ], [590, 2, 0, 0, 0, 0, 0, 1.0, 0, 380.0, 0, 1.1,...
StarcoderdataPython
129001
<reponame>jasperro/core<gh_stars>1-10 """The DirecTV integration.""" import asyncio from datetime import timedelta from typing import Dict from DirectPy import DIRECTV from requests.exceptions import RequestException import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from hom...
StarcoderdataPython
3263895
import logging import os from cryptoxlib.CryptoXLib import CryptoXLib from cryptoxlib.Pair import Pair from cryptoxlib.clients.bitvavo import enums from cryptoxlib.clients.bitvavo.exceptions import BitvavoException from cryptoxlib.version_conversions import async_run LOG = logging.getLogger("cryptoxlib") LOG.setLevel...
StarcoderdataPython
3312657
<gh_stars>10-100 import sys from pydub import AudioSegment from gtts import gTTS import os f = open(sys.argv[1]) text = "" for item in f: text += item print(text) tts = gTTS(text) tts.save('test.mp3') sound2 = AudioSegment.from_mp3("test.mp3") sound1 = AudioSegment.from_mp3("bit.mp3") output = sound1.overlay(sound2,...
StarcoderdataPython
12367
''' Created on Sep 29, 2021 @author: thomas ''' import ImageNetTools import sys import getopt def main(argv): try: opts, args = getopt.getopt(argv,"hd:",["dataset="]) except getopt.GetoptError: printHelp() sys.exit(2) for opt, arg in opts: if opt in...
StarcoderdataPython
1759834
# -*- coding: utf-8 -* import pymongo client = pymongo.MongoClient("mongodb://localhost:27000/") data_base = client['test'] question = data_base['question'] finished_question = data_base['finished_question'] uid_col = data_base['uid'] global regret_uid try: while True: single = question.aggregate([{'$samp...
StarcoderdataPython
142033
from django.core import validators from django.db import models from ..app.models import App class WebhookURLField(models.URLField): default_validators = [ validators.URLValidator(schemes=["http", "https", "awssqs", "gcpubsub"]) ] class Webhook(models.Model): name = models.CharField(max_length=...
StarcoderdataPython
85667
<filename>src/get_ratings.py import itertools from datetime import datetime, timedelta from get_moves import get_color def ratings_daily_games(games, username='kewko', number=None): dates = [] ratings = [] daily_games = [] weekly_games = {} for game in itertools.islice(games, 0, number): ...
StarcoderdataPython
161467
""" Routines for Fourier transform. """ from __future__ import division from ..datatable.wrapping import wrap from ..datatable import column from . import waveforms, specfunc import numpy as np import numpy.fft as fft def truncate_len_pow2(trace, truncate_power=None): """ Truncate trace length to t...
StarcoderdataPython
1761246
<reponame>ieternalleo/AlgoCode<filename>Python/ZipAndUnzip/zipunzip.py<gh_stars>100-1000 # importing required modules from zipfile import ZipFile import os import sys def getAllFilePaths(directory): # initializing empty file paths list filePaths = [] # crawling through directory and subdirecto...
StarcoderdataPython
95766
# providers/starling/test_api_v2.py # # tests the functionality of the StarlingAPI class import uuid from datetime import datetime, timedelta import pytest from starling_server.providers.starling.api import StarlingProvider from starling_server.schemas import AccountSchema, AccountBalanceSchema from starling_server.s...
StarcoderdataPython
1623648
<gh_stars>1-10 # Resource object code (Python 3) # Created by: object code # Created by: The Resource Compiler for Qt version 6.2.2 # WARNING! All changes made in this file will be lost! from PySide6 import QtCore qt_resource_data = b"\ \x00\x00\x00a\ [\ Controls]\x0aStyle=\ Material\x0a\x0a[Unive\ rsal]\x0aTheme=Sys...
StarcoderdataPython
3249106
<filename>src/config/views.py from django.views.generic import TemplateView class HomepageView(TemplateView): template_name = 'config/home.html'
StarcoderdataPython
116792
from pwn import * context.arch="amd64" elf = ELF("./splaid-birch") libc = ELF("./libc.so.6") #p = process("./splaid-birch") p = remote("splaid-birch.pwni.ng", 17579) def sp_add(a, b): p.sendline("5") p.sendline(str(a)) p.sendline(str(b)) def delete(a): p.sendline("1") p.sendline(str(a)) for i i...
StarcoderdataPython
105998
<filename>files/migrations/0001_initial.py<gh_stars>1-10 # Generated by Django 3.1.2 on 2020-10-30 09:30 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="File", ...
StarcoderdataPython
1717539
<reponame>rcbops-qe/monster<filename>monster/features/base.py """Base feature.""" class Feature(object): def __repr__(self): return 'class: ' + self.__class__.__name__ def __str__(self): """Prints out class name in lower case. :rtype: str """ return self.__class__.__na...
StarcoderdataPython
1650118
""" Fonction (-a)^x = exp(x*ln(-a)) """ import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from cmath import * from math import pi fig = plt.figure() ax = fig.add_subplot(111, projection='3d') i = complex(0, 1) a = -0.8 pas = 0.01 max = 30 plt.title("$f(x) = \,(" + str(a) + ")^x = \, a + ib$...
StarcoderdataPython
3386845
<filename>duat/config.py # -*- coding: UTF-8 -*- """Model OSIRIS configuration files.""" import copy import re from itertools import product from functools import reduce # py3 needs from operator import mul import numpy as np from duat.common import ifd, logger def _prod(iterable): return reduce(mul, iterable...
StarcoderdataPython
1765527
<gh_stars>0 import json import re import joblib import pandas as pd import plotly from flask import Flask from flask import render_template, request from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.tokenize import word_tokenize from plotly.graph_objs import Bar, Scatter from ...
StarcoderdataPython
3306608
# Copyright 2017 PerfKitBenchmarker Authors. All rights reserved. # # 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 appli...
StarcoderdataPython
1695072
<gh_stars>0 #!/usr/bin/env python3 """Find sites which have extreme read depth across samples. Takes a set of readcount files produced by mpileup2readcounts and finds sites in which the median read depth is not between `min_depth` and `max_depth`. Outputs tsv file with 2 columns: [Chromosome/Contig, Position]. """ imp...
StarcoderdataPython
3359317
import bpy from bpy.types import Panel class FE_PT_Panel(Panel): bl_space_type = "VIEW_3D" bl_region_type = "UI" bl_label = "Test Panel" bl_category = "Test Panel" def draw(self, context): layout = self.layout row = layout.row() col = row.column() c...
StarcoderdataPython
1710865
################################################################################ # Utility folder for collecting data # ################################################################################ import os import hashlib import requests import subprocess import zipfile ##########################################...
StarcoderdataPython
3376767
<gh_stars>10-100 from submission import Submission class SilvestreSubmission(Submission): def run(self, s): group_score = 1 total_score = 0 cl = list(s) for i, c in enumerate(cl): if c == '!': del cl[i+1] while '!' in cl: cl.remove('!...
StarcoderdataPython
3337538
<reponame>ninchat/ninchat-python # Copyright (c) 2014, <NAME> # 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 must retain the above copyright # notice, thi...
StarcoderdataPython
93852
from loris.compliance.helpers import ComparableMixin from loris.compliance.helpers import st class AbstractFeatureSet(ComparableMixin): # Override these in implementations LEVEL_2 = () LEVEL_1 = () LEVEL_0 = () # Only necessary to overide if value are listed in the profile ALL = () def __ini...
StarcoderdataPython
3214588
<gh_stars>0 import pygame import random from pygame.locals import * from os import path #######################################加载声音####################################### #获取声音库和声音路径 sound_folder = path.join(path.dirname(__file__),'sounds') #加载炮弹、导弹发射声音 shooting_sound = pygame.mixer.Sound(path.join(sound_folder,'pew...
StarcoderdataPython
1792481
<filename>pythonProject/05al133OS_SHUTIL-MOVER-COPIAR-APAGAR-ARQUIVOS/MOVER.py<gh_stars>0 import os import shutil caminho_original = '/home/dwolter/Music/novaPub' caminho_novo = '/home/dwolter/Music/2 Pub Bar' try: os.mkdir(caminho_novo) except FileExistsError as e: print(f'Pasta {caminho_novo} já existe. '...
StarcoderdataPython
1744468
from flask import Flask from flask import jsonify from flask import request from flask_pymongo import PyMongo app = Flask(__name__) app.config['MONGO_DBNAME'] = 'restdb' app.config['MONGO_URI'] = 'mongodb://localhost:27017/restdb' mongo = PyMongo(app) @app.route("/", methods=["GET"]) def index(): return "Hello ...
StarcoderdataPython
134719
# coding=utf-8 # # created by kpe on 28.Mar.2019 at 12:33 # from __future__ import absolute_import, division, print_function import tensorflow as tf import params_flow as pf from tensorflow import keras from tensorflow.keras import backend as K import bert class PositionEmbeddingLayer(bert.Layer): class Param...
StarcoderdataPython
1635463
<reponame>naseemkullah/seldon-core import grpc from concurrent import futures from flask import jsonify, Flask, send_from_directory from flask_cors import CORS import numpy as np import os import logging from google.protobuf import json_format from seldon_core.proto import prediction_pb2, prediction_pb2_grpc from sel...
StarcoderdataPython
1751861
import os import sys import csv import pandas as pd import numpy as np from sklearn.cluster import AgglomerativeClustering from sklearn.model_selection import KFold import random #random.seed(1) def get_samples(df, nClusters): model = AgglomerativeClustering(n_clusters=nClusters) model.fit(df) labels_idx ...
StarcoderdataPython
4840433
<filename>docs/Advanced_development/zh/QuecPythonSub/code/image.py ''' 通过工具将图片转换为数组的形式保存在一个元组中, 下面是像素为 99x100 的四叶草图片 ''' image_buf = ( 0X31,0XA8,0X31,0XA8,0X31,0XA8,0X31,0XA8,0X31,0XA8,0X31,0XA8,0X31,0XA8,0X31,0XA8, 0X31,0XA8,0X31,0XA8,0X31,0XA8,0X31,0XA8,0X31,0XA8,0X31,0XA8,0X31,0XA8,0X31,0XA8, 0X31,0XA8,0X31,0XA8,0X3...
StarcoderdataPython
1759210
<reponame>apulis/RFCN-tensorflow #!/usr/bin/python # # Copyright 2017 <NAME>. All Rights Reserved. # # 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...
StarcoderdataPython
3356710
import math from astropy import units as u from speclite.filters import ab_reference_flux, load_filter from galcheat import available_surveys, get_survey speclite_survey_prefixes = { "DES": "decam2014-", "Euclid_VIS": "Euclid-", "HSC": "hsc2017-", "Rubin": "lsst2016-", } def calculate_zero_point(ba...
StarcoderdataPython
4818528
# encoding: utf-8 """ @author: liaoxingyu @contact: <EMAIL> """ import math import torch from torch import nn import logging from fastreid.modeling.backbones import build_backbone from projects.InterpretationReID.interpretationreid.modeling.heads import build_reid_heads from fastreid.modeling.losses import * from fast...
StarcoderdataPython
3297560
<filename>tests/tests.py #!/usr/bin/env python import unittest import os #import db_handler from jsondb.jsondb import JsonDB as jsondb class MyTests(unittest.TestCase): # pylint: disable=R0904 def setUp(self): self.db = jsondb("test.db") def tearDown(self): if os.path.exists("test.db")...
StarcoderdataPython
3292736
from numpy import * import os import numpy as np from PIL import Image from numpy import random import tensorflow as tf def conv(input, kernel, biases, k_h, k_w, c_o, s_h, s_w, padding="VALID", group=1): c_i = input.get_shape()[-1] assert c_i%group==0 assert c_o%group==0 convolve = lambda i, k: tf.nn....
StarcoderdataPython
193514
<reponame>ErickMM98/covid-ct-network-analysis from skimage.io import imread from skimage.exposure import equalize_adapthist import matplotlib.pyplot as plt import mfdfa import numpy as np from time import time """ GENERAL VALUES """ q = -10 nworkers = 30 img = imread('images/0018.jpg') parallel_mfdfa = mfdfa.MFDFA...
StarcoderdataPython
166486
<filename>flask_lesson/app.py from flask import Flask, render_template, request, redirect, url_for import flask_lesson.db as db app = Flask(__name__) @app.route("/") def home(): return render_template("posts_list.jinja2", posts=db.posts) @app.route("/posts/<int:post_id>") def get_post(post_id: int): post ...
StarcoderdataPython
132395
<filename>sdk/python/kfp/cli/diagnose_me/utility.py<gh_stars>1-10 # Copyright 2019 The Kubeflow Authors. All Rights Reserved. # # 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...
StarcoderdataPython
1722824
# -*- coding: utf-8 -*- # Copyright (c) 2020 Kumagai group. from itertools import groupby from pathlib import Path from typing import List, Optional, Dict from monty.serialization import loadfn from pydefect.chem_pot_diag.chem_pot_diag import CompositionEnergy, \ CompositionEnergies from pydefect.util.mp_tools im...
StarcoderdataPython
1776959
<filename>sustc-cas-login.py<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time import urllib import urllib2 import cookielib import socket import re __TIMEOUT__ = 2 # 10 min __PERIOD__ = 10 * 60 class NoRedirectHandler(urllib2.HTTPErrorProcessor): def http_response(self, reques...
StarcoderdataPython
15258
<gh_stars>1-10 '''Please write a program to read the scan and print out The maximum voxel intensity The mean voxel intensity The coordinates of the centre of the image volume, in the scanner coordinate system. ''' import pydicom import numpy as np import matplotlib.pyplot as plt import cv2 import glob import os import...
StarcoderdataPython
47908
from flask import render_template_string from werkzeug.test import EnvironBuilder, run_wsgi_app class TestTemplateGlobals: def test_static_mode(self, single_use_app): @single_use_app.route("/test-globals") def test_globals(): return render_template_string("""{{ static_mode }}""") ...
StarcoderdataPython
3326919
from ego.vectorize import set_feature_size, vectorize from ego.encode import make_encoder #from ego.decompose import concatenate, concatenate_disjunctive, compose, iterate, head_compose, abstract_compose from ego.decompose import compose, args, do_decompose, add, com # node relabeling from ego.decomposition.node_rela...
StarcoderdataPython
188070
<gh_stars>0 # Generated by Django 3.1.3 on 2021-04-09 18:31 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('web', '0009_auto_20210403_1822'), ] operations = [ migrations.DeleteModel( name='ApiData', ), ]
StarcoderdataPython
123829
<reponame>xylovedd/yangyang<gh_stars>10-100 # coding:utf-8 import datetime from util.logger import Logger from util.app_util import datetime_str_timestamp, current_timestamp import ticket_config as config log = Logger('debug') if __name__ == "__main__": start_time = datetime_str_timestamp('2019-12-27 12:01:00') ...
StarcoderdataPython
3254885
# Copyright 2020-2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
StarcoderdataPython
1693995
<filename>Stock/BackTesting/Ui/Basic/DyStockBackTestingResultWidget.py<gh_stars>100-1000 from PyQt5 import QtCore from PyQt5.QtWidgets import QTabWidget from PyQt5.QtGui import QCursor from .Strategy.DyStockBackTestingStrategyResultWidget import * from EventEngine.DyEvent import * from DyCommon.DyCommon import * from ...
StarcoderdataPython
4824789
30 mtime=1365496689.474878594 30 atime=1440176559.393245608 30 ctime=1440177385.049309059
StarcoderdataPython
3303593
#!/usr/bin/env python ## # This script indexes the Disease Ontology HumanDO.obo file. # import os import lucene import argparse import oboparser import ConfigParser from doexceptions import ExistingIndexDirectoryException __author__ = "<NAME>" __copyyright__ = "Institute for Genome Science - University of Ma...
StarcoderdataPython
88042
<gh_stars>1-10 import datetime import uuid from sqlalchemy import DateTime, Column, String from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import relationship, validates from models import Base class Organisation(Base): __tablename__ = "organisations" id = Column(UUID(as_uuid=True), pri...
StarcoderdataPython
179369
<gh_stars>1-10 def detectLoop(head): if head == None: return False start = head next_next_start = head.next if next_next_start == None: return False next_next_start = head.next.next while next_next_start != None: start = start.next next_next_sta...
StarcoderdataPython
1633361
#!/usr/bin/env python3 from __future__ import annotations import sys import tempfile from pathlib import Path from typing import Optional import pytest import pdoc import pdoc.render here = Path(__file__).parent.absolute() snapshot_dir = here / "testdata" class Snapshot: id: str path: Path render_opti...
StarcoderdataPython
4835775
<gh_stars>10-100 import os, glob, sys import argparse from termcolor import colored import matplotlib.pyplot as plt import numpy as np import gzip from sklearn import metrics from sklearn.externals import joblib from sklearn.model_selection import cross_val_score, train_test_split from skbayes.rvm_ard_models import RV...
StarcoderdataPython
3280302
<filename>remimi/segmentation/rgb_segmentation.py from typing import List from remimi.utils.file import get_model_file from mmseg.apis import inference_segmentor, init_segmentor import cv2 import numpy as np from pkg_resources import resource_filename class SemanticSegmenter: def __init__(self): # config_f...
StarcoderdataPython
3262801
<reponame>amitdev81296/tensorflow # This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. """Utility methods to create simple input_fns. """ from __future__ import print_function from tensorflow.python.estimator.inputs.inputs import numpy_input...
StarcoderdataPython
4825079
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import math class Embedding(nn.Module): def __init__(self, word_vec_mat, max_length, word_embedding_dim=50, pos_embedding_dim=5): nn.Module.__init__(self) self.max_length = max_length se...
StarcoderdataPython
4837581
#!/usr/bin/env impala-python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (...
StarcoderdataPython
1672281
#-*- coding: utf-8 -*- from py3wirecard.entities.lib.wireentity import * from py3wirecard.entities.amount import Amount from py3wirecard.entities.product import Product from py3wirecard.entities.checkoutpreferences import CheckoutPreferences from py3wirecard.entities.receiver import Receiver from py3wirecard.entities.c...
StarcoderdataPython