id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
217801
<reponame>ayushkalani/delightchat from django.contrib import admin from analytics.models import Accounts, Users, Conversations, Channels admin.site.register(Accounts) admin.site.register(Users) admin.site.register(Conversations) admin.site.register(Channels)
StarcoderdataPython
6662936
#! /bin/env python # # Protein Engineering Analysis Tool Structure Analysis (PEATSA) # Copyright (C) 2010 <NAME> & <NAME> # # Author: <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eit...
StarcoderdataPython
6627086
import requests, time, csv from bs4 import BeautifulSoup # listPageRootUrl is "https://www.pcmag.com/categories/mobile-phones?page=" # pageNumber is the page number on PCMag site to scrape # write=True writes scraped URLs to CSV file in format phoneName|url def getReviews(listPageRootUrl, pageNumber, write=Tru...
StarcoderdataPython
6511706
import tempfile import gnupg import pytest from django.conf import settings from snoop import emails, models, pgp pytestmark = pytest.mark.skipif(not settings.SNOOP_GPG_BINARY, reason="SNOOP_GPG_BINARY not set") PATH_HUSH_MAIL = 'eml-9-pgp/encrypted-hushmail-knockoff.eml' HEIN_PRIVATE_KEY = 'eml-9-pgp/keys/hein-...
StarcoderdataPython
12827576
# coding : UTF-8 from operator import methodcaller from test_image_embedding import * from test_pipeline import * from test_audio_embedding import * def pipeline_register(): pipeline_names = ["image-embedding", "towhee/image-embedding-efficientnetb5", "towhee/image-embedding-efficientnetb7",...
StarcoderdataPython
6566295
<gh_stars>0 # This file is part of gnome-tweak-tool. # -*- coding: utf-8 -*- # # Copyright (c) 2011 <NAME> # # gnome-tweak-tool is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
StarcoderdataPython
5110361
<gh_stars>1-10 # Generated by Django 2.0.10 on 2019-02-15 16:55 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('atriacalendar', '0007_auto_20190210_1240'), ] operations = [ ...
StarcoderdataPython
3264813
<gh_stars>0 from MachineHypermediaToolkit.server.http.HypermediaHttpServer import HypermediaHTTPServer, HypermediaHTTPRequestHandler from MachineHypermediaToolkit.resource.HypermediaCollection import HypermediaCollection import sys def test(HandlerClass = HypermediaHTTPRequestHandler, ServerClass = Hypermedia...
StarcoderdataPython
4836617
<filename>hanzo/warcvalid.py #!/usr/bin/env python """warcvalid - check a warc is ok""" from __future__ import print_function import os import sys import sys import os.path from optparse import OptionParser from .warctools import WarcRecord, expand_files parser = OptionParser(usage="%prog [options] warc warc warc...
StarcoderdataPython
238790
<reponame>4con/grpc-win-xp<filename>src/python/grpcio_tests/tests/unit/framework/interfaces/face/test_cases.py<gh_stars>10-100 # Copyright 2015 gRPC authors. # # 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 ...
StarcoderdataPython
9637694
from moonfire_tokenomics.data_types import Allocation, AllocationRecord, Blockchain, Category, CommonType, Sector, Token mbox = Token( name="MBOX", project="Mobox", sector=Sector.GAMING, blockchain=[Blockchain.BSC], category=[Category.PAYMENT, Category.GOV, Category.DIVIDEND], capped=True, ...
StarcoderdataPython
8174835
<reponame>matteo-rizzo/fc4-pytorch import math import torch from torch import Tensor from torch.nn.functional import normalize from classes.core.Loss import Loss class AngularLoss(Loss): def __init__(self, device: torch.device): super().__init__(device) def _compute(self, pred: Tensor, label: Tenso...
StarcoderdataPython
1829520
""" 10-15 一些关于学习正则的建议 """ # 正则表达式可以帮助我们完成一些字符串内置函数所无法完成的功能,提高工作效率,善用正则表达式解决字符串相关的问题。 # 正则表达式并不是Python独有的,几乎所有主流语言都支持正则表达式。 # Python主要应用在爬虫以及数据处理与分析上。爬虫的核心在于抓取html,利用正则表达式分析html,最终提炼出需要的数据和信息。 # 建议: # 常用的正则表达式,如电话号码的判断,邮箱的判断,这样常见的校验规则是可以使用别人写好的。 # 搜索常见正则表达式 # 如果用别人写好的正则表达式,可以花一点时间分析一下别人的正则表达式是怎么写的。 # 正则表达式功能强大,但是长时间不用...
StarcoderdataPython
12843384
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Attachment) on 2019-01-22. # 2019, SMART Health IT. from . import element class Attachment(element.Element): """ C o n t e n t i n a f ...
StarcoderdataPython
3402776
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(N): squrt_of_n = int(N ** 0.5) + 1 min_perm = 0 current_perm = 0 for i in range(1, squrt_of_n): if N % i == 0: current_perm = (i + N // i) * 2 if current_perm < min_pe...
StarcoderdataPython
11344064
from floodsystem.stationdata import build_station_list from floodsystem.geo import stations_by_distance def show_c(): #Variables stations = build_station_list() show_list_0 = stations_by_distance(stations, (52.2053, 0.1218)) #Calls function that calculates distance show_list_closest_0 = [] ...
StarcoderdataPython
6597978
<filename>datamart/unit_tests/test_general_materializer.py<gh_stars>1-10 from datamart.materializers.general_materializer import GeneralMaterializer import unittest from datamart.utilities.utils import Utils class TestGeneralMaterializer(unittest.TestCase): def setUp(self): self.general_materializer = Gen...
StarcoderdataPython
3578596
<filename>tests/test_pdf_reader.py import unittest import pytest from extractor.pdf_reader import PDFReader @pytest.mark.usefixtures("path_to_anthology") class TestPDFReader(unittest.TestCase): def test_read_page(self): reader = PDFReader(self._path) text_stack = [] for texts in reader.i...
StarcoderdataPython
197991
<reponame>ezequieljsosa/sndg-bio #!/usr/bin/python import sys import os import getopt import time #import mysql.connector from random import randint from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from commands import getoutput def help(): print "Prediccion de rRNAs y tRNAs en ...
StarcoderdataPython
1989757
<reponame>kenserr/cs165<gh_stars>0 from django.contrib import admin from .models import passport_stat admin.site.register(passport_stat) # Register your models here.
StarcoderdataPython
3565529
""" pycmark.cli ~~~~~~~~~~~ command line tools for pycmark. :copyright: Copyright 2017-2019 by <NAME> :license: Apache License 2.0, see LICENSE for details. """ from docutils.core import publish_cmdline from pycmark import CommonMarkParser def md2html() -> None: publish_cmdline(parser=Comm...
StarcoderdataPython
5094008
from sketcher import * import random canvas = Canvas(600, 600) noise_seeds = [random.randint(0,999) for i in range(0,3)] color = [random.randint(150,250) for i in range(3)] warp = Ink('simplex_gradient',color=color, c_var=70, noise_seeds=noise_seeds, noise_scale=0.001) canvas.fill(warp) img = shuffle_image(canvas...
StarcoderdataPython
185838
# Copyright 2021 Nokia # Licensed under the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause from typing import Optional from common.files import create_temp_dir from common.logger import Logger class Policy(object): def __init__(self, namespace: Optional[str], policy: str): self.namespace = ...
StarcoderdataPython
11247472
import ast from niveristand import _errormessages from niveristand.clientapi import realtimesequencedefinition from niveristand.errors import TranslateError def custom_stop_task(node, resources): _validate_restrictions(node) realtimesequencedefinition.add_stop_task(resources.get_current_block(), node.args[0]....
StarcoderdataPython
3404479
from persistence.repositories.course_rating_repository_postgres import CourseRatingRepositoryPostgres from exceptions.http_error import NotFoundError crrp = CourseRatingRepositoryPostgres() def delete_course_rating(db, course_id, rating_id): rating = crrp.get_course_rating(db, course_id, rating_id) if not r...
StarcoderdataPython
6426821
<reponame>avroshk/7100_Spring_16<gh_stars>1-10 from __future__ import division import os, random, wave import scipy.io.wavfile as wavfile import numpy as np from random import randint numSpeakers = 4 ## In each file numRepetitions = 2 numOutput = 200 ## to be generated set = "F" outputFileName = "set"+set+"_"+"S"+st...
StarcoderdataPython
122630
<reponame>hasithadkr7/udp_150 #!/usr/bin/python3 import datetime, re def getUTCOffset(utcOffset, default=False): """ Get timedelta instance of given UTC offset string. E.g. Given UTC offset string '+05:30' will return datetime.timedelta(hours=5, minutes=30)) :param string utcOffset: UTC offset in...
StarcoderdataPython
186935
# Front matter ############## import os from os import fdopen, remove from tempfile import mkstemp from shutil import move import glob import re import time import pandas as pd import numpy as np from scipy import constants from scipy.optimize import curve_fit, fsolve from scipy.interpolate import interp1d import matpl...
StarcoderdataPython
3580656
<gh_stars>1-10 from typing import Optional, Tuple import torch import torch.nn.functional as F import torch_geometric.utils from torch import Tensor, nn from torch_geometric.nn.meta import MetaLayer from torch_scatter import scatter_add, scatter_mean from src.models.node_edge_blocks import * class GraphNetworkBlock...
StarcoderdataPython
11328546
import os from flask import Flask, url_for, request, flash ,render_template , session , redirect , send_file from flask_admin import Admin from DatabaseHelper import DatabaseHelper import model from model import db as database import myAdmin from flask_uploads import UploadSet , IMAGES , configure_uploads ...
StarcoderdataPython
9760205
""" Defines custom middleware for users and user management. """ import re from django.conf import settings from django.shortcuts import render from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from rest_framework.views import APIView from .views import PublicView class ...
StarcoderdataPython
3480857
<reponame>ThomasYeoLab/Standalone_He2022_MM<filename>stable_projects/predict_phenotypes/He2022_MM/cbig/He2022/CBIG_ukbb_dnn_haufe.py<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Written by <NAME> and CBIG under MIT license: https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md """ import os impo...
StarcoderdataPython
265272
<gh_stars>0 from abc import ABC, abstractmethod from overrides import overrides import networkx as nx from task_answer import TaskAnswer from test_parser import Parser class Graph(ABC): _graph_impl = None _n = 0 _X = None _Y = None _edges = None def __init__(self, **kwargs): pass ...
StarcoderdataPython
6633326
<filename>tools/demo.py<gh_stars>100-1000 import _init_paths import argparse import time import os import sys import os.path as osp from glob import glob import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import caffe from mpi4py import MPI from fast_rcnn.test_probe import demo_exfeat from f...
StarcoderdataPython
3291018
#!/usr/bin/env python mqtt_host = 'mqtt.home' import sys import paho.mqtt.client as paho import os import datetime import threading import serial import serial.threaded import serial.tools.list_ports import re import signal import time serial_dev = '/dev/ttyACM' #sys.stderr = open('proxy_error.log', 'a') mqtt = pa...
StarcoderdataPython
3217430
# Copyright 2020 The Microsoft DeepSpeed Team """ DeepSpeed runner is the main front-end to launching multi-worker training jobs with DeepSpeed. By default this uses pdsh to parallel ssh into multiple worker nodes and launch all the necessary processes per rank for training. """ import os import sys import json import...
StarcoderdataPython
4819657
# Copyright (C) 2022 FireEye, Inc. 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: [package root]/LICENSE.txt # Unless required by applicable law or agreed to in writing,...
StarcoderdataPython
137082
<filename>SC101Assignment/SC101_Assignment0/coin_flip_runs.py """ File: coin_flip_runs.py Name: 洪禎蔚 ----------------------- This program should simulate coin flip(s) with the number of runs input by users. A 'run' is defined as consecutive results on either 'H' or 'T'. For example, 'HHHHHTHTT' is regarded as a 2-run re...
StarcoderdataPython
1897184
import sys from types import SimpleNamespace from . import jupyter, non_tty, tty, void # work around a bug on Windows' command prompt, where ANSI escape codes are disabled by default. if sys.platform == 'win32': import os os.system('') def _create(mod, interactive): terminal = SimpleNamespace( ...
StarcoderdataPython
5111703
# -*- coding: utf-8 -*- ''' saltpylint.version ~~~~~~~~~~~~~~~~~~~ :codeauthor: :email:`<NAME> (<EMAIL>)` :copyright: © 2013-2018 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. ''' # Import Python libs from __future__ import absolute_import...
StarcoderdataPython
1994676
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode: def trim(node): if not node: return None elif ...
StarcoderdataPython
11340347
<reponame>Brett777/Predict-Churn import os from boto.s3.connection import S3Connection from boto.s3.key import Key import h2o import numpy as np import pandas as pd from tabulate import tabulate # initialize the model scoring server h2o.init(nthreads=1,max_mem_size=1, start_h2o=True, strict_version_check = False) def ...
StarcoderdataPython
3533694
<filename>util/cmd_loader.py # -*- coding: UTF-8 -*- import importlib import os from command import Cmd from util import CmdLoader def py_file_to_class_name(py_file): """ 将py文件名按照首字母大写驼峰式转换成类名。忽略文件名中的"_"并截断"." :param py_file: py文件名,非路径 :return: 首字母大写驼峰式类名 """ class_name = [] idx = 0 ...
StarcoderdataPython
8055840
import spacy import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.cluster.vq import kmeans from collections import Counter def form_unique_text_lemmas(file_name, nlp): min_len = 2 with open(file_name, 'r', encoding='utf-16') as file: text = file.read() ...
StarcoderdataPython
8131831
from lxml import etree def xml_to_string(xml_object): return etree.tostring(xml_object).decode()
StarcoderdataPython
8049437
<gh_stars>10-100 #iris_save_load_predict_gridmodel.py import joblib from pandas import read_csv from sklearn.metrics import accuracy_score, classification_report from sklearn.model_selection import train_test_split, GridSearchCV,RandomizedSearchCV from sklearn.datasets import load_iris from sklearn.svm import SVC da...
StarcoderdataPython
4931039
<gh_stars>10-100 import unittest from mock import patch, Mock, call from textmagic.rest.models import Users, MessagingStats, SpendingStats, Utils, Invoices class TestUser(unittest.TestCase): def setUp(self): self.resource = Users("uri", ("username", "token")) def test_get(self): with patch.o...
StarcoderdataPython
6584918
<gh_stars>0 try: from fields import field_classes as fc from selection import concrete_expression as ce except ImportError: from . import field_classes as fc from ..selection import concrete_expression as ce def test_add_fields(): field_a = fc.field('a', int) field_b = fc.field('b', float) ...
StarcoderdataPython
1805002
"""timvt.endpoints.factory: router factories.""" from dataclasses import dataclass, field from typing import Any, Callable, Dict, Optional, Type from buildpg.asyncpg import BuildPgPool from morecantile import TileMatrixSet from timvt.db.tiles import VectorTileReader from timvt.dependencies import ( TableParams, ...
StarcoderdataPython
1665917
<gh_stars>0 from collections import deque def read_file(test = True): if test: filename = '../tests/day1.txt' else: filename = '../input/day1.txt' with open(filename) as file: temp = [int(line.strip()) for line in file] return temp def puzzle1(test = True): depth...
StarcoderdataPython
9702764
def uninstall_base(context): gs = context.getSite().portal_setup if u'collective.talkflow:install-base' in gs._profile_upgrade_versions: # make safe for reinstall... del(gs._profile_upgrade_versions[u'collective.talkflow:install-base'])
StarcoderdataPython
333233
class Scene: def __init__(self): """ A scene has multiple SceneObject """ self.objects = [] class SceneObject: def __init__(self, pos, color): """ Object that belongs to a scene Args: pos(ndarray): Position in 3D space color(ndarr...
StarcoderdataPython
5009508
<filename>learn-py/regex/regex3.py # Meta caracteres: ^ $ ( ) # * 0 ou n # + 1 ou n {1,} # ? 0 ou 1 # {n} # {min, max} # {10,} 10 ou mais # {,10} De zero a 10 # {10} Especificamente 10 # {5,10} De 5 a 10 # ()+ [a-zA-Z0-9]+ import re texto = ''' João trouxe flores para sua amada namorada em 10 de janeiro de 1970, M...
StarcoderdataPython
3580864
<filename>supriya/ugens/InRange.py import collections from supriya import CalculationRate from supriya.synthdefs import UGen class InRange(UGen): """ Tests if a signal is within a given range. :: >>> source = supriya.ugens.SinOsc.ar() >>> in_range = supriya.ugens.InRange.ar( ......
StarcoderdataPython
9668621
import sys import os ps = """ cp `$PROFILE` '' """ END_SYNC_SIGNAL = "# Do not Sync Below #" REPLACE_SYNC_SIGNAL = "# Used to Sync:" def syncWindowsProfile(save_path = '../windows/profile.ps1'): cmd = "powershell echo $PROFILE" profile_path = os.popen(cmd).read()[:-1] print(f"Powershell Profile location...
StarcoderdataPython
3536568
<reponame>chasebk/code_ISLO_ELM<gh_stars>1-10 #!/usr/bin/env python # ------------------------------------------------------------------------------------------------------% # Created by "Thieu" at 10:23, 03/08/2021 % # ...
StarcoderdataPython
1996421
import idc import idautils def enum_segments(): for segstart in idautils.Segments(): segend = idc.SegEnd(segstart) segname = idc.SegName(segstart) yield segstart, segend, segname def find_pointers(start, end): for va in range(start, end-0x4): ptr = idc.Dword(va) if id...
StarcoderdataPython
159069
import scrapy import json import requests import time from spiderUtil import FbrefFixtureResponseWrapper, FbrefMatchResponseWrapper from hashlib import md5 from dateSearch import DateSearch from itertools import permutations from scrapy.http import HtmlResponse class FixturesSpider(scrapy.Spider): name = "Fixtu...
StarcoderdataPython
11347331
import bs4 import requests import threading from colorama import Fore def get_html(episode_number: int, text_html: list) -> str: print(Fore.YELLOW + f'Getting HTML for episode {episode_number}', flush=True) url = f'https://talkpython.fm/{episode_number}' resp = requests.get(url) resp.raise_for_status...
StarcoderdataPython
8181192
<filename>MainFile_OptPRFF_RFF_Nyst_ORF.py<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Fri Apr 14 15:40:47 2017 @author: damodara """ # -*- coding: utf-8 -*- """ Created on Fri Oct 21 15:48:47 2016 @author: damodara """ # -*- coding: utf-8 -*- """ Created on Fri Oct 14 14:50:12 2016 @author...
StarcoderdataPython
1612119
## This file is made so that specific statements may be copied inside existing files. This is useful to copy ## import statements in __init__.py, or to complete model lists in the AUTO files. ## ## It is to be used as such: ## Put '# To replace in: "FILE_PATH"' in order to indicate the contents will be copied in the fi...
StarcoderdataPython
3356699
<reponame>sepideh-srj/flashNoflash import torch from .base_model import BaseModel from . import networks import matplotlib.pyplot as plt import numpy as np import numpy import itertools from util.image_pool import ImagePool from torchvision import transforms import cv2 import kornia class SharedDecModel(BaseModel): ...
StarcoderdataPython
322794
""" See if slowly raising discount factor can stablize DDPG. """ import random from railrl.envs.mujoco.twod_point import TwoDPoint from railrl.exploration_strategies.ou_strategy import OUStrategy from railrl.launchers.launcher_util import ( run_experiment, set_seed, ) def experiment(variant): from railrl...
StarcoderdataPython
12837522
#!/usr/bin/env python2.7 # # This file is part of peakAnalysis, http://github.com/alexjgriffith/peaks/, # and is Copyright (C) University of Ottawa, 2014. It is Licensed under # the three-clause BSD License; see doc/LICENSE.txt. # Contact: <EMAIL> # # Created : AU1862014 # File : peak_functions # Author : <NAME> ...
StarcoderdataPython
4850898
<reponame>barbagroup/cloud-repro """Plot the time-to-solution versus the number of nodes.""" import pathlib from matplotlib import pyplot, gridspec import numpy def get_filepaths(casedir, prefix='stdout_run', suffix='.txt', niter=5): """Get the file paths with data to read. Parameters ---------- cas...
StarcoderdataPython
6574122
from tecton import sql_transformation, TemporalFeaturePackage, DataSourceConfig, MaterializationConfig from feature_repo.shared import entities as e, data_sources from datetime import datetime # @sql_transformation(inputs=data_sources.user_info, has_context=True) # def user_age_years_sql_transform(context, table_name...
StarcoderdataPython
151348
<filename>skworkorders/ConfigCenter.py<gh_stars>0 #! /usr/bin/env python # -*- coding: utf-8 -*- from .models import ConfigCenter from django.contrib.auth.decorators import login_required from skaccounts.permission import permission_verify from .forms import ConfigCenter_form from django.shortcuts import render...
StarcoderdataPython
1711710
<reponame>ibestvina/dagpy from . import utils from . import blockio from . import dag from pkg_resources import resource_string import os import re import nbformat from nbformat.v4 import new_markdown_cell, new_code_cell, new_notebook class FlowManager: """Manages the creation, parsing and saving of flow notebo...
StarcoderdataPython
9741193
<gh_stars>0 from typing import List from helpers import console from .checks import guild_only, registered_guild_only, registered_guild_and_admin_or_mod_only, registered_guild_with_muted_role_and_admin_or_mod_only, _is_admin_or_mod from .command_registration import register_command as _register_command from .command_r...
StarcoderdataPython
8116275
"""tokenize readable handle to tokens""" def tokenize(handle): """read handle and turn it into tokens""" run = True pos = -1 mem = "" while run: pos += 1 char = handle.read(1) if not char: run = False break if char in ['[', ']', '{', '}', ",",...
StarcoderdataPython
1971209
<gh_stars>10-100 from polyphony import testbench def f(): return 0 def call02(): return f() @testbench def test(): assert 0 == call02() test()
StarcoderdataPython
8083675
from os import listdir import glob import json def load_track(filename:str): with open(filename) as f: operations = json.load(f) track = Tracker(filename) track.operations = operations return track class Tracker: def __init__(self, name:str, sounds_dir:str = "sounds/*.wav", mo...
StarcoderdataPython
3558324
# File name : SakitoScrap.py # Author : <NAME> # Outline : Sakitoの自動化を行うクラス # license : MIT # Copyright (c) 2017, <NAME> import requests from bs4 import BeautifulSoup class SakitoScrap: def __init__(self, email:str, password:str): self.email = email self.passwor...
StarcoderdataPython
6427461
""" New Zealand Business Number Retrieve Entity Test Module author: <EMAIL> © Procuret Operating Pty Ltd """ from nzbn.tests.test import Test from nzbn.tests.test_result import Success, TestResult, Failure from nzbn.entity import Entity class RetrieveEntity(Test): NAME = 'Retrieve an Entity' def execute(sel...
StarcoderdataPython
1917874
<filename>acky/ec2.py<gh_stars>0 from acky.api import ( AwsCollection, AwsApiClient, make_filters, ) from itertools import chain class EC2ApiClient(AwsApiClient): service_name = "ec2" class EC2(EC2ApiClient): def regions(self, continent='us', include_gov=False): # returns (string, ...) ...
StarcoderdataPython
275006
<filename>permabots/utils.py from telegram import emoji from six import iteritems, PY2 def create_emoji_context(): context = {} for key, value in iteritems(emoji.Emoji.__dict__): if '__' not in key: if PY2: value = value.decode('utf-8') context[key.lower().repla...
StarcoderdataPython
5095696
<filename>Mapping.py import pickle #Python wraper for MetaMap from pymetamap import MetaMap# MetaMap for identifying biomedical concepts # each element is a list of indications for prescribing a plant phenotypes = pickle.load(open('/home/balus/Metamap/1000 random phenotypes', 'rb')) #creating a metamap instace from...
StarcoderdataPython
6402352
#!/usr/bin/env python # -*- coding: utf-8 -*- # These two lines are necessary to find source files!!! import sys sys.path.append('../src') from neuralNet import NeuralNet, DataSet from files import files if __name__ == '__main__': f = files["haberman"] ds = DataSet(f) n = NeuralNet([3, 1, 2], ds.dataMatr...
StarcoderdataPython
3593647
<filename>src/demographics.py def birth_generation(birth_year): """ Takes in a birth_year and returns the corresponding generation. The earliest corresponding generation is returned. Parameters ---------- birth_year: int The birth year in question. Returns ------- generation:...
StarcoderdataPython
11252339
<filename>tests/decorators/test_render_html.py from fbv.decorators import render_html from tests.utils import assert_response def test_render_html(request): @render_html("test/template.html") def _(*args): return {"test": 123} response = _(request) assert_response(response, content="asdf 123...
StarcoderdataPython
5030947
from primes import get_primes, is_prime
StarcoderdataPython
1874680
import os import subprocess import logging from subprocess import Popen logger = logging.getLogger(__name__) class SFTPUsers: """ System sftp users name (which are usual unix account users) have format: <prefix><company_name>_<web_username> Examples: Company opel with two web users:...
StarcoderdataPython
3218082
from queue_with_stacks import Queue def test_queue_with_stacks_tests(): # Setup q = Queue() q.enqueue(1) q.enqueue(2) q.enqueue(3) # Test size assert(q.size() == 3) # Test dequeue assert(q.dequeue() == 1) # Test enqueue q.enqueue(4) assert (q.dequeue() == 2) asse...
StarcoderdataPython
1940021
<gh_stars>1-10 #class PopupPanel: # # # PopupImpl.onShow # def onShowImpl(self, popup): # frame = doc().createElement('iframe') # frame.scrolling = 'no' # frame.frameBorder = 0 # frame.style.position = 'absolute' # # popup.__frame = frame # frame.__popup = pop...
StarcoderdataPython
397722
<reponame>doctorblinch/leetcode<filename>1. Two Sum/two_sum.py class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: diffs = {} for i in range(len(nums)): if nums[i] in diffs: return [diffs[nums[i]], i] diffs.update...
StarcoderdataPython
3388058
# -*- coding: utf-8 -*- """Checker of PEP-8 Class Constant Naming Conventions.""" import ast __version__ = '0.1.2' class ConstantNameChecker(ast.NodeVisitor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.issues = [] def _ccn_101(self, t_id: str, lineno: int, ...
StarcoderdataPython
6431328
<gh_stars>0 import albumentations as a import cv2,os,random path='E:\\pos_neg\\Positive' write='E:\\augmented\\positive' j=0 for file in os.listdir(path): img=cv2.imread(os.path.join(path,file)) angle=random.randint(15,30) img=a.rotate(img,angle) cv2.imwrite(os.path.join(write,str(j)+file),img)...
StarcoderdataPython
3385335
<filename>addons/test_mail/tests/test_mail_template.py<gh_stars>0 # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 from datetime import datetime, timedelta from unittest.mock import patch from odoo.addons.test_mail.tests.common import BaseFunctionalTest,...
StarcoderdataPython
5136598
<reponame>yun-mh/uniwalk # Generated by Django 2.2.5 on 2020-01-14 01:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0015_template'), ] operations = [ migrations.AlterField( model_name='template', ...
StarcoderdataPython
5035004
from unittest import TestCase from neuropower import BUM import numpy as np class TestBUM(TestCase): def test_fpLL(self): np.random.seed(seed=100) testpeaks = np.vstack((np.random.uniform(0,1,10),np.random.uniform(0,0.2,10))).flatten() x = np.sum(BUM.fpLL([0.5,0.5],testpeaks)) self....
StarcoderdataPython
4894957
import pickle import numpy as np from collections import deque from format_data import format_data def bfs(adj_dict, group_list, source_group, depth_limit): observed_group = {source_group} depth = 0 queue = deque([(source_group,depth)]) while queue and queue[0][1] < depth_limit: group_parent, d...
StarcoderdataPython
3314473
class Node: def __init__(self, value): self.prev = None self.value = value self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def append(self, value): new_node = Node(value) if self.head == None: self...
StarcoderdataPython
4809185
<filename>test/testp4svn_actions.py #!/usr/bin/env python # -*- coding: utf-8 -*- '''Test cases of perforce to svn replication ''' import os import unittest import tempfile from testcommon import get_p4d_from_docker from testcommon_p4svn import replicate_P4SvnReplicate, verify_replication from lib.buildlogger impor...
StarcoderdataPython
11365024
import time import unittest from hydrus.core import HydrusConstants as HC from hydrus.core import HydrusData from hydrus.core import HydrusExceptions from hydrus.core import HydrusGlobals as HG from hydrus.core.networking import HydrusNetwork from hydrus.core.networking import HydrusNetworking from hydrus.server impo...
StarcoderdataPython
9664204
import dash_bootstrap_components as dbc from dash import Input, Output, State, html tooltip = html.Div( [ dbc.Button( "Toggle", id="toggle", color="success", className="me-4", n_clicks=0, ), dbc.Button("Target", id="target", color=...
StarcoderdataPython
3470225
import smtplib server = smtplib.SMTP('localhost') addr_from = '<EMAIL>' addr_to = '<EMAIL>' server.sendmail(addr_from, addr_to, """To: {1} From: {0} ... Beware the Ides of March. 日本語も送れるかな? """.format(addr_from, addr_to)) server.quit()
StarcoderdataPython
11212768
<filename>dashboard/migrations/0002_author_auth_status.py # Generated by Django 3.1.5 on 2021-04-24 18:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0001_initial'), ] operations = [ migrations.AddField( mod...
StarcoderdataPython
1796659
import os import sys from faker import Factory sys.path.append(os.getcwd()) import api import user fake = Factory.create() MOCK_NEW_USER = { 'name': '<NAME>', 'user_id': '3141592654', 'email': '<EMAIL>' } MOCK_SCAN = { "env": { "LANG": "en_US.UTF-8", "AWS_DEFAULT_REGION"...
StarcoderdataPython
4943122
import sys sensivity = sys.argv; temp = sensivity[1].split('=')[1] print({"temp": float(temp) * 0.460646})
StarcoderdataPython
391902
<gh_stars>100-1000 import itertools import matplotlib import numpy as np from scipy.optimize import curve_fit from scipy import interpolate from astropy import units from astropy.io import fits from astropy.convolution import convolve, Gaussian1DKernel from matplotlib import pyplot as plt # Imports for fast_runnin...
StarcoderdataPython