id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1794327 | <filename>modules/m_etc.py<gh_stars>1-10
import psutil, base64, os, sys, hashlib, datetime, discord, random
from PIL import Image, ImageDraw, ImageFont
import configparser
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime, timedelta
if __name__=="__main__":
print("FATAL : Run this ... | StarcoderdataPython |
1779333 | # Generated by Django 2.1.15 on 2020-06-24 15:39
from django.db import migrations
def forwards(apps, schema_editor):
Category = apps.get_model("news", "Category")
Category.objects.create(name="Dummy Category", slug="dummy-category")
def backwards(apps, schema_editor):
Category = apps.get_model("news", ... | StarcoderdataPython |
128028 | <reponame>fengwanwan/st_analysis
#! /usr/bin/env python
"""
This script performs a supervised prediction in ST datasets
using a training set and a test set.
The training set will be one or more matrices of
with counts (genes as columns and spots as rows)
and the test set will be one matrix of counts.
One file or fi... | StarcoderdataPython |
3279696 | # Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Pngwriter(CMakePackage):
"""PNGwriter is a very easy to use open source graphics library t... | StarcoderdataPython |
3296902 | <reponame>monishshah18/python-cp-cheatsheet<gh_stars>100-1000
class Solution:
def maxProfit(self, prices: List[int]) -> int:
t0 = [0] * 3
t1 = [float(-inf)] * 3
for p in prices:
for i in range(2,0,-1):
t0[i] = max(t0[i], t1[i] + p)
t1[i] =... | StarcoderdataPython |
1646825 | <gh_stars>1-10
#!/usr/bin/python3
from pwn import *
# Telnet
sh = remote("ip", 30888)
# SSH:
# sh = ssh('user', 'ip', password='<PASSWORD>', port=22)
# Exec
# process('./exec')
# conn.sendlineafter(b"> ", b"1")
sh.sendline(b'ls')
flag = sh.recvline(timeout=5)
log.success(flag)
sh.interactive()
sh.close() | StarcoderdataPython |
1628292 | <gh_stars>0
#
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
#
import os
import docker
from sandesh.nodeinfo.cpuinfo.ttypes import ProcessCpuInfo
class DockerMemCpuUsageData(object):
def __init__(self, _id, last_cpu, last_time):
self.last_cpu = last_cpu
self.last_time = last_ti... | StarcoderdataPython |
39660 | import re
from data.scrape.link_extractors.create_extractor import create_extractor
from data.scrape.utils import clean_url
from .constants import ID
class Strategy:
def __init__(self, url_pattern, template=None, **extractor_args):
self.url_pattern = url_pattern.format(ID=ID)
self.url_regex = re.... | StarcoderdataPython |
153066 | <filename>app/questionnaire/routing_path.py
class RoutingPath:
"""Holds a list of block_ids and has section_id, list_item_id and list_name attributes"""
def __init__(self, block_ids, section_id, list_item_id=None, list_name=None):
self.block_ids = tuple(block_ids)
self.section_id = section_id
... | StarcoderdataPython |
4838390 | # coding:utf8
from setuptools import setup
long_desc = """
easyquotation
===============
* easy to use to get stock info in China Stock
Installation
--------------
pip install easyquotation
Upgrade
---------------
pip install easyquotation --upgrade
Quick Start
--------------
::
import easyquotation
... | StarcoderdataPython |
3238339 | <filename>CrySPY/gen_struc/random/with_spg/fw.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------
#
# This code partly includes find_wy (https://github.com/nim-hrkn/find_wy)
# which is distributed under the Apache License, Version 2.0.
#
# ------... | StarcoderdataPython |
45992 | <gh_stars>0
import os
import sys
import platform
import shutil
import flopy
import pymake
# make sure exe extension is used on windows
eext = ''
soext = '.so'
if sys.platform.lower() == 'win32':
eext = '.exe'
soext = '.dll'
binpth, temppth = os.path.join('..', 'bin'), os.path.join('temp')
# some flags to che... | StarcoderdataPython |
3340895 | <reponame>JohnGriffiths/dipy
# Init file for visualization package
from __future__ import division, print_function, absolute_import
# We make the visualization requirements optional imports:
try:
import matplotlib
has_mpl = True
except ImportError:
e_s = "You do not have Matplotlib installed. Some visuali... | StarcoderdataPython |
1793496 | import unittest
import torch
import alpa.torch.optim as torchoptim
import alpa
from alpa.torch.trainer import train_torch_module
class MyModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear1 = torch.nn.Linear(16, 16)
self.linear2 = torch.nn.Linear(16, 16)
def ... | StarcoderdataPython |
3313945 | from urllib import request
from url_helper import HeaderHelper
import json
import gzip
import time
import math
class Comment:
def __init__(self, cid: int, floor_num: int, content: str, uid: int) -> None:
# comment id
self.cid = cid
self.floor_num = floor_num
# user id
self... | StarcoderdataPython |
1637114 | <reponame>Nathanlauga/transparentai-ui
from transparentai import sustainable
from os.path import dirname, abspath
from ....utils.db import update_in_db, select_from_db
from ....utils.errors import get_errors
from ....utils import key_in_dict_not_empty, is_empty
from ....utils.components import clean_errors, format_str... | StarcoderdataPython |
4814058 | # -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function
from . import dc
from .. import __version__, __author__
class xlref(object):
def __init__(self,Workbook,Worksheet,Range):
""" xlref
Creates a XL reference handlers:
Params(3):
Workbook as ... | StarcoderdataPython |
115734 | <filename>model.py
# Copyright 2019 <NAME>
# Licensed under the Apache License, Version 2.0
import tensorflow as tf
import numpy as np
def gru(units):
return tf.keras.layers.GRU(units,
return_sequences=True,
return_state=True,
... | StarcoderdataPython |
1750330 | <filename>exoral/admin.py
from django.contrib import admin
from .models import (
Fach,
Dozent,
Testat,
Frage,
)
class FachAdmin(admin.ModelAdmin):
model = Fach
list_display = ('name', 'admin_list_dozent')
admin.site.register(Fach, FachAdmin)
class DozentAdmin(admin.ModelAdmin):
model = Do... | StarcoderdataPython |
109122 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
print('y1')
def main(filename):
raw_data = load_data(filename)
# TODO - Clean data
print(raw_data[0])
return raw_data
def load_data(filename):
with open(filename, 'r') as file:
raw = file.read()
raw_data = frames = raw.split... | StarcoderdataPython |
144510 | import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, 'textrank'))
from summa.preprocessing.textcleaner import get_sentences # Uses textrank's method for extracting sentences.
BASELINE_WORD_COUNT = 100
def baseline(text):
""" Creates a baseline summary to be ... | StarcoderdataPython |
3338850 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/14 15:08
# @Author : glacier
# @Site :
# @File : tianmao.py
# @Software: PyCharm Edu
import requests
import re
if __name__ == '__main__':
urls = []
for i in range(400):
urls.append("https://rate.tmall.com/li... | StarcoderdataPython |
4806157 | import pygame, sys, pymunk
def create_circle(space, pos):
body = pymunk.Body(1,100,body_type = pymunk.Body.DYNAMIC)
body.position = pos
shape = pymunk.Circle(body,80)
space.add(body,shape)
return shape
def draw_circles(circles):
for circle in circles:
pos_x = int(circle.body.position.... | StarcoderdataPython |
1742115 | # Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.opset1.ops import absolute
from openvino.opset1.ops import absolute as abs
from openvino.opset1.ops import acos
from openvino.opset4.ops import acosh
from openvino.opset1.ops import add
from openvino.opset1.ops import asin
... | StarcoderdataPython |
3277184 | import io
from abc import ABC
from typing import Generator, Any, TypeVar, Iterable, Iterator, Optional
from ijson import items as ijson_items
from requests import Response
class AbcRest(ABC):
__slots__ = ()
_T = TypeVar('_T')
def debug_iter(iterable: Iterable[_T], file_name: str) -> Generator[_T, None, None]... | StarcoderdataPython |
3395747 | # -*- coding: utf-8 -*-
import pili
# 替换成自己 Qiniu 账号的 AccessKey
access_key = "..."
# 替换成自己 Qiniu 账号的 SecretKey
secret_key = "..."
domain = '...'
hub_name = '...'
stream_title = '...'
expire = 3600
mac = pili.Mac(access_key, secret_key)
client = pili.Client(mac)
hub = client.hub(hub_name)
stream = hub.get("..... | StarcoderdataPython |
1798649 | from collections import OrderedDict
from itertools import product
from sympy import Basic
from sympy.core.singleton import Singleton
from sympy.core.compatibility import with_metaclass
from sympy.core.containers import Tuple
from sympy import AtomicExpr
from sympde.topology import ScalarTestFunction, VectorTestFuncti... | StarcoderdataPython |
11259 | # -*- coding: utf-8 -*-
"""API routes config for notifai_recruitment project.
REST framework adds support for automatic URL routing to Django, and provides simple, quick and consistent
way of wiring view logic to a set of URLs.
For more information on this file, see
https://www.django-rest-framework.org/api-guide/rou... | StarcoderdataPython |
28498 | <reponame>foropolo/task
from rest_framework import serializers
class HelloSerializer(serializers.Serializer):
"""Serializes a name field for testing out APIView"""
city_name = serializers.CharField(max_length=30)
| StarcoderdataPython |
3226457 | <gh_stars>0
# Ask the user to enter a word. Have the program keep asking them to
# enter one while the user writes "continue" as their word.
keyword = "continue"
current_word = ""
while current_word == keyword:
current_word = input("Enter a word: ").strip()
| StarcoderdataPython |
159306 | # File name: __init__.py
# Author: <NAME>
# Date created: 27-07-2018
# TODO: should I import the entire module, or just the relevant functions?
from . import chemical, recipe, make, help | StarcoderdataPython |
97468 | from typing import List
from logging import getLogger
import notify
logger = getLogger(__name__)
class _RegisteredNotifyTaskList():
def __init__(self):
self._task_list: List[notify.NotifyTask] = []
def append_task(self, task: notify.NotifyTask) -> None:
self._task_list.append(task)
... | StarcoderdataPython |
76572 | <reponame>naviocean/imgclsmob
import random
import threading
import numpy as np
from PIL import Image, ImageOps, ImageFilter
from tensorflow.keras.preprocessing.image import ImageDataGenerator, DirectoryIterator
class SegDataset(object):
"""
Segmentation base dataset.
Parameters:
----------
root ... | StarcoderdataPython |
4835522 | """This module is responsible for running the Flask restful API to
communicate the the values of basic_math to a localhost on port 5000 """
from flask import Flask, request
from flask_restful import Resource, Api
import basic_math
APP = Flask(__name__)
API = Api(APP)
def verify_list(list1, list2):
"""
Verifi... | StarcoderdataPython |
56343 | <reponame>Execut3/django-discount
# Generated by Django 2.2.5 on 2020-12-02 02:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | StarcoderdataPython |
4814592 | import os
import networkx as nx
import pandas as pd
def induced_subgraph(
G, filter_type, filter_attribute, filter_values, ignore_attrs=False
):
"""
Create custom induced subgraph.
Args:
filter_type: 'node' or 'edge'
filter_attribute: attribute to filter on
filter_values: att... | StarcoderdataPython |
1751374 | #Import modules
import os
import pandas as pd
import numpy as np
from pandas import DatetimeIndex
import dask
import scipy
from scipy.optimize import minimize, LinearConstraint
import time
from sklearn.preprocessing import MinMaxScaler, StandardScaler
import pickle
#Define Column Name
indexName = 'date'
... | StarcoderdataPython |
18760 | class ToolNameAPI:
thing = 'thing'
toolname_tool = 'example'
tln = ToolNameAPI()
the_repo = "reponame"
author = "authorname"
profile = "authorprofile" | StarcoderdataPython |
1697251 | <reponame>NeuralFlux/greenwheels
from django import forms
from Eprint_users.models import PrintDocs
from . models import RatePerPage
class UpdateForm(forms.ModelForm):
class Meta:
model = PrintDocs
fields = ['task_by', 'completed', 'paid', 'collected', 'id']
class ChangeRate(forms.Mod... | StarcoderdataPython |
81923 | #!/usr/bin/env python
import sys
def get_output_dir(target_arch, component):
# Build in "out_ffmpeg" for Chromium branding of ffmpeg.
if component == 'ffmpeg':
return 'out_ffmpeg'
# Build in "out_component" for component build.
output_dir = 'out'
if component == 'shared_library':
output_dir += '_c... | StarcoderdataPython |
5451 | <reponame>Ayansam1152/translate
#!/usr/bin/env python3
import importlib
import os
# automatically import any Python files in the models/ directory
for file in sorted(os.listdir(os.path.dirname(__file__))):
if file.endswith(".py") and not file.startswith("_"):
model_name = file[: file.find(".py")]
... | StarcoderdataPython |
3286186 | from abc import abstractmethod
import numpy as np
from rlgym.utils import math
from rlgym.utils.common_values import BLUE_TEAM, ORANGE_GOAL_CENTER, BLUE_GOAL_CENTER, ORANGE_TEAM
from rlgym.utils.gamestates import GameState, PlayerData
from rlgym.utils.reward_functions import RewardFunction
class EventReward(RewardF... | StarcoderdataPython |
3287069 | """
Test that using a non-existent architecture name does not crash LLDB.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
class NoSuchArchTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def test(self):
... | StarcoderdataPython |
3340432 | <filename>kay/tests/jinja2_test.py
#:coding=utf-8:
from kay.utils.test import Client
from kay.utils import url_for
from kay.app import get_application
from kay.conf import LazySettings
from kay.ext.testutils.gae_test_base import GAETestBase
class Jinja2TestCase(GAETestBase):
def setUp(self):
s = L... | StarcoderdataPython |
1642695 | <gh_stars>10-100
# Generated by Django 2.2.16 on 2020-11-04 19:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("api", "0101_scratch_org_nullable_email"),
]
operations = [
migrations.AddField(
model_name="product",
... | StarcoderdataPython |
1607043 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the file-like object implementation using pyvshadow."""
import os
import unittest
from dfvfs.file_io import vshadow_file_io
from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.path import factory as path_spec_factory
from dfvfs.resolver ... | StarcoderdataPython |
67142 | <filename>katacomb/katacomb/aips_parser.py
import logging
import InfoList
import ParserUtil
from katacomb import obit_err, handle_obit_err
from katacomb.obit_types import OBIT_TYPE_ENUM
log = logging.getLogger('katacomb')
def parse_aips_config(aips_cfg_file):
"""
Parses an AIPS config file into a
dicti... | StarcoderdataPython |
3270800 | import pathlib
import asyncio
import argparse
from typing import List
FPS = 60
SPEED_MULTIPLIER = float(input("Video speed multiplier: "))
FRAME_TIME = round(1 / SPEED_MULTIPLIER, 4)
FFMPEG_CMD = "ffmpeg -y -i {} -r 60 -filter:v \"setpts={}*PTS\" {}"
async def main():
file_list: List[pathlib.Path] = args.VIDEO... | StarcoderdataPython |
1721699 | <filename>sppas/documentation/scripting_solutions/ex16_annotations_dur_filter.py
#!/usr/bin python
"""
:author: <NAME>
:date: 2018-07-09
:contact: <EMAIL>
:license: GPL, v3
:copyright: Copyright (C) 2018 <NAME>, Laboratoire Parole et Langage
:summary: Open an annotated file and filter ... | StarcoderdataPython |
3278567 | <filename>analyzer/darwin/lib/common/config.py
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import ConfigParser
class Config:
def __init__(self, cfg):
"""@param cfg: configuration fil... | StarcoderdataPython |
1607818 | <reponame>arita37/ptl2r.github.io
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by <NAME> | 26/09/2018 | https://y-research.github.io
"""Description
"""
import torch
from org.archive.eval.metric import tor_nDCG_at_k, tor_nDCG_at_ks, EMD_at_k
from org.archive.l2r_global import L2R_GLOBAL
gpu, device = L2R... | StarcoderdataPython |
13893 | <filename>servermn/core/__init__.py
def init():
# Set locale environment
# Set config
# Set user and group
# init logger
pass | StarcoderdataPython |
3356356 | <reponame>ContinuumIO/enaml
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------------------... | StarcoderdataPython |
1697311 | <filename>agagd/agagd_core/tables/all_chapters_table.py
import agagd_core.models as agagd_models
import django_tables2 as tables
from django.utils.html import format_html
# Base Bootstrap Column Header Attributes
default_bootstrap_header_column_attrs = {
"class": "table",
"thead": {"class": "thead-dark"},
... | StarcoderdataPython |
3387436 | <reponame>krishotte/web_sperky<gh_stars>0
"""A DashboardController Module."""
from masonite.request import Request
from masonite.view import View
from masonite.controllers import Controller
from .PortfolioController import get_user
from .auth.LoginController import get_caller_path
from app.Product import Product
from ... | StarcoderdataPython |
1724007 | <reponame>forksnd/arbytmap
try:
from setuptools import setup, Extension, Command
except ImportError:
from distutils.core import setup, Extension, Command
import arbytmap
long_desc = ""
try:
long_desc = open("README.MD").read()
except Exception:
print("Couldn't read readme.")
setup(
name="arbytmap... | StarcoderdataPython |
3385397 | <filename>setup.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
version = '1.0.1'
setup(
name='fabplugins',
version=version,
description="Fabric plugins",
long_description="Fabric plugins",
keywords='fabplugins',
author='Time Home',
author_email='<EMAIL>',
... | StarcoderdataPython |
1702843 | <filename>ApiManager/utils/utils.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import json
import os
import requests
import xmind
import logging
import time
from .parser import xmind_to_testsuites
from ApiManager.models import XmindCase, UserInfo
# from django.utils import timezone
def get_absolute_path(path):
... | StarcoderdataPython |
1784441 | <reponame>a000b/zderzacz-BTC<gh_stars>0
## Program generuje dowolną ilość kluczy prywatnych oraz przekształca je w opcjonalnie w adresy Legacy bądź SegWit.
## Następnie odpytuje blockstream.info i oblicza saldo danego konta.
## To tylko zabawa, szansa na to że trafi się na tzw kolizję jest praktycznie zerowa, jak 1 do ... | StarcoderdataPython |
1747614 | <reponame>alexcfaber/katka-core<filename>katka/migrations/0005_scmservice.py
# Generated by Django 2.1.5 on 2019-02-14 08:04
import uuid
from django.db import migrations, models
import katka.fields
class Migration(migrations.Migration):
dependencies = [
("katka", "0004_credential_secret"),
]
... | StarcoderdataPython |
3347996 | from dj_rest_auth.registration.views import RegisterView
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.response import Response
from ... | StarcoderdataPython |
1784200 | import math
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras import backend as K
class PositionLayer(tf.keras.layers.Layer):
def __init__(self, embedding_size, **kwargs):
self.embedding_size = embedding_size
super(PositionLayer, self).__init__(*... | StarcoderdataPython |
1706448 | <filename>A/A 230 Dragons.py
# https://codeforces.com/problemset/problem/230/A
s, n = map(int, input().split())
dragons = sorted([[int(j) for j in input().split()] for i in range(n)], key=lambda x: x[0])
for d in dragons:
if s > d[0]:
s += d[1]
else:
print('NO')
break
else:
print('... | StarcoderdataPython |
1662282 | <filename>fulltext/services/extractor/extractor.py
"""Integration with Docker to perform plain text extraction."""
import os
import shutil
from datetime import datetime
from typing import Tuple, Optional, Any
import docker
from docker import DockerClient
from docker.errors import ContainerError, APIError
from request... | StarcoderdataPython |
175018 | import os
with open(os.path.join(os.path.dirname(__file__), "input.txt"), "r") as file:
ins = [l.strip() for l in file.readlines()]
card_count = 10007
stack = []
for j in range(card_count):
stack.append(j)
initial_stack = stack.copy()
count = 0
for i in ins:
if "stack" in i:
stack.reverse()
... | StarcoderdataPython |
58807 | # -*- coding: utf-8 -*-
import asyncio
from config import (CHECK_SERVER_INTERVAL, CHECK_SERVER_INTERVAL_MAX,
CRON_LOOP_INTERVAL)
from discord import Activity, ActivityType
from discord.errors import Forbidden, NotFound
from discord.ext import commands, tasks
from modules.db import Servers
from modu... | StarcoderdataPython |
1769239 | <filename>spikeextractors/extractors/mdaextractors/mdaextractors.py
from spikeextractors import RecordingExtractor
from spikeextractors import SortingExtractor
import json
import numpy as np
from pathlib import Path
from .mdaio import DiskReadMda, readmda, writemda32, writemda64
import os
class MdaRecordingExtractor... | StarcoderdataPython |
148360 | <filename>src/InstPyr/MyDevices/helpers.py
from dataclasses import dataclass,fields
@dataclass
class Sensor:
pass | StarcoderdataPython |
129787 | import random
import time
import pygame
import ppb.events as events
import ppb.flags as flags
default_resolution = 800, 600
class System(events.EventMixin):
def __init__(self, **_):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
from ppb.... | StarcoderdataPython |
1684568 | <filename>tests/unit/test_api.py
from eth_wallet.api import(
WalletAPI,
)
from tests.conftest import (
prepare_conf,
)
from web3 import (
Web3,
)
from eth_utils import (
decode_hex,
)
def test_account(tmp_path):
test_configuration = prepare_conf(tmp_path)
WalletAPI.new_wallet(test_configurati... | StarcoderdataPython |
3345793 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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... | StarcoderdataPython |
3221286 | <gh_stars>0
import copy
from .slct import some_keeping_order,some
from .index import uniform_index
def fcp(ol):
return(ol[:])
def max_length(ol):
lngths = list(map(lambda r:len(r),ol))
lngth = max(lngths)
return(lngth)
def entries(ol):
rslt = []
length = ol.__len__()
for i in range(0,l... | StarcoderdataPython |
1673374 | <gh_stars>0
import os
import sys
from typing import List, Tuple, TypeVar
try:
import importlib.resources as pkg_resources
except:
import importlib_resources as pkg_resources
T = TypeVar("T")
def var_to_grid(array_var: List[T], size: Tuple[int, int]) -> List[List[T]]:
"""convert ownership/policy to grid ... | StarcoderdataPython |
1612626 | from django.contrib.gis.db import models
from users.models import CustomUser as User
class Occurrence(models.Model):
CON = 'CONSTRUCTION'
SPE = 'SPECIAL_EVENT'
INC = 'INCIDENT'
WCD = 'WEATHER_CONDITION'
RCD = 'ROAD_CONDITION'
CATEGORY_CHOICES=[
(CON, 'Construction'),
(SPE, 'Spec... | StarcoderdataPython |
1602158 | if __name__ == "__main__":
import gizeh
import moviepy.editor as mpy
from vectortween.PointAnimation import PointAnimation
from vectortween.SequentialAnimation import SequentialAnimation
from vectortween.BezierCurveAnimation import BezierCurveAnimation
from vectortween.PolarAnimation import Pol... | StarcoderdataPython |
3375662 | <reponame>Livin21/LinuxDrop
import sys
from sender import send
from receiver import receive
def run():
try:
option = sys.argv[1]
if option == "-send":
f_name = sys.argv[2]
send.start_server(f_name)
elif option == "-receive":
receive.receive()
el... | StarcoderdataPython |
3302076 | #!/usr/bin/env python
# Goal of this script is to take a vulners url and give you the short description of the CVE
# Ideally, this will be run against the vulners nmap output, which will append the description
# to each of the findings.
# Probably a lot of unnecessary code, but got incredibly frustrated debugging due ... | StarcoderdataPython |
189130 | P = []
f = []
def primes():
P = []
mark = [0]*1000001
for i in xrange(2, 1000001):
if mark[i]:
continue
P.append(i)
for j in xrange(i + i, 1000001, i):
mark[j] = 1
return P
def calc():
for p in P:
for i in xrange(p + p, 1000001, p):
... | StarcoderdataPython |
118085 | <reponame>GodQ/notest
import pycurl
import os
import sys
import copy
from io import BytesIO
from .http_auth_type import HttpAuthType
from .http_response import HttpResponse
base_dir = os.path.abspath(os.path.dirname(__file__))
libcurl_crt_file = os.path.join(base_dir, "..", "..", "tools", "curl-ca-bundle.crt")
DEFA... | StarcoderdataPython |
3301969 | <filename>samples/tutorial-2-wg.py
from pyalgotrade import strategy
from pyalgotrade.barfeed import quandlfeed
from pyalgotrade.technical import ma
def safe_round(value, digits):
if value is not None:
value = round(value, digits)
return value
class MyStrategy(strategy.BacktestingStrategy):
def _... | StarcoderdataPython |
1697791 | <reponame>RealTimeWeb/wikisite
# -*- coding: utf-8 -*-
"""
MoinMoin - MoinMoin.caching Tests
@copyright: 2007 by MoinMoin:ThomasWaldmann
@license: GNU GPL, see COPYING for details.
"""
import py
import time
from MoinMoin import caching
from MoinMoin.PageEditor import PageEditor
class TestCaching(objec... | StarcoderdataPython |
1764967 | # 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | StarcoderdataPython |
1691673 | import tensorflow as tf
class ConfusionMatrix(tf.keras.metrics.Metric):
def __init__(self, num_classes, **kwargs):
super(ConfusionMatrix, self).__init__(name='confusion_matrix', **kwargs) # handles base args (e.g., dtype)
self.num_classes = num_classes
self.total_cm = self.add_we... | StarcoderdataPython |
3294577 | <reponame>kevinlib/IOHMM
'''
The Wrapper of statsmodels one parameter exponential family distributions used by GLM,
with the added functionality for log likelihood per sample. Loglikelihood per sample is
going to be used in IOHMM to estimate emission probability.
'''
from __future__ import division
from past.utils imp... | StarcoderdataPython |
1614392 | import random
import pytest
import redis
from RLTest import Env
from test_helper_classes import _get_ts_info
def test_ooo(self):
with Env().getClusterConnectionIfNeeded() as r:
quantity = 50001
type_list = ['', 'UNCOMPRESSED']
for chunk_type in type_list:
r.execute_command('ts... | StarcoderdataPython |
1741619 | <reponame>phigre/cobi
import torch
import numpy as np
import rasterio
import salem
from oggm import entity_task, cfg
from combine2d.core.sia2d_adapted import Upstream2D
import logging
# -------------------------------
# Further initialization / extended import tasks
# Module logger
log = logging.getLogger(__name__)
#... | StarcoderdataPython |
3384628 | <reponame>mann-brinson/LA_Apartments_Scraper
#!/usr/bin/env python
# coding: utf-8
import argparse
import sys
import sqlite3
import pandas as pd
import os
import shutil
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
import seaborn as sns
#GOAL: Run queries on la_apartments.db to return simple metri... | StarcoderdataPython |
137047 | from keeks.binary_strategies.base import BaseStrategy
__author__ = 'willmcginnis'
class NaiveStrategy(BaseStrategy):
def __init__(self, payoff, loss, transaction_cost):
"""
The Naive strategy returns full portion of bet if expected value is above transaction costs at all.
:param payoff:
... | StarcoderdataPython |
3247162 | import heapq
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.heap = []
self.k = k
for i in range(len(nums)):
self.add(nums[i])
def add(self, val):
"""
:type val: int
... | StarcoderdataPython |
1666323 | def old_test_single_annot_distinctiveness_params(ibs, aid):
r"""
CommandLine:
python -m ibeis.model.hots.distinctiveness_normalizer --test-old_test_single_annot_distinctiveness_params --show
python -m ibeis.model.hots.distinctiveness_normalizer --test-old_test_single_annot_distinctiveness_param... | StarcoderdataPython |
3336248 | class ExportError(Exception):
pass
| StarcoderdataPython |
4821698 | <reponame>uninassau-2020-2/proj-grupo5
from app.models.DAO import DAOFornecedorPJ
import pymysql
from app import app
from config import mysql
from flask import jsonify
from flask import flash, request
from app.models.classes_basicas.FornecedorPJ import FornecedorPJ
def add_fornecedorpj(f):
try:
return DAO... | StarcoderdataPython |
3222466 | <reponame>DogukanKundum/Classification-tweets<filename>test10.py<gh_stars>1-10
import sys
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
pd.options.mode.chained_assignment = None
import numpy as np
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning, module=... | StarcoderdataPython |
1603722 | #!/usr/bin/env python3
##########################################
## EKF source switch ##
##########################################
from mycelium.components import Base, Connector
class Switch(Base):
def __init__(self,
connection_string=None, # Port set in mavproxy/mavlink to send ... | StarcoderdataPython |
3360865 | import sys
sys.path = [
'']
import Phase1
from pirates.launcher.PiratesQuickLauncher import PiratesQuickLauncher
launcher = PiratesQuickLauncher()
launcher.notify.info('Reached end of StartPiratesLauncher.py.')
| StarcoderdataPython |
107230 | <filename>02.keras_MNIST_linear.py<gh_stars>1-10
from keras.models import Sequential
from keras.datasets import mnist
from keras.layers import Dense
from keras.utils import np_utils # For transformation of one-hot-encoding.
## Settings in training phase.
batch_size = 1024 # Change batch size based on the capability... | StarcoderdataPython |
1658050 | import requests
def ais() -> dict:
try:
url = 'https://i.sjtu.edu.cn/xtgl/login_slogin.html'
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.3 Safari/605.1.15',
'Content-Type': 'text/html;charset... | StarcoderdataPython |
1767439 | #!/usr/bin/env python
# encoding: utf-8
"""
Library of built-in probability functions.
These probability functions use `scipy.stats` at their core, but also
encapsulate *limits* so that they can return a ln prob of -infinity when
a sample is called outside those limits. This is useful for emcee sampling.
Note this is... | StarcoderdataPython |
3342742 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_django-activitylog
------------
Tests for `django-activitylog` models module.
"""
from django.test import TestCase
from django.utils import timezone
from activitylog.models import ActivityLog
class ActivityLogModelTests(TestCase):
def test_str(self):
... | StarcoderdataPython |
1627185 | <reponame>bpow/CNVpytor<gh_stars>0
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
exec(open('cnvpytor/version.py').read())
setup(
name='CNVpytor',
version=__version__,
author='<NAME>, <NAME>, <NAME>',
author_email='<EMAIL>',
packages=['cnvpytor'],... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.