id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3393812 | <filename>safecast_deploy/same_env.py
import datetime
import pprint
import sys
from safecast_deploy import git_logger, verbose_sleep
class SameEnv:
def __init__(self, state):
self.state = state
self._c = state.eb_client
def run(self):
self.start_time = datetime.datetime.now(datetime.... | StarcoderdataPython |
4846339 | #!/usr/bin/env python3
from .curve import *
from .geodesics import *
from .manifold import *
| StarcoderdataPython |
9785570 | #!/usr/bin/env python
"""Simple parsers for the output of WMI queries."""
import binascii
import calendar
import struct
import time
from grr.lib import parser
from grr.lib import rdfvalue
from grr.lib.rdfvalues import anomaly as rdf_anomaly
from grr.lib.rdfvalues import client as rdf_client
from grr.lib.rdfvalues imp... | StarcoderdataPython |
38065 | <reponame>bhrutledge/jahhills.com<filename>docs/_ext/django_models.py
# Auto-document Django models
# Copied and adapted from https://djangosnippets.org/snippets/2533/
import inspect
from django.utils.html import strip_tags
from django.utils.encoding import force_text
from django.db import models
def process_docstri... | StarcoderdataPython |
3248296 | <reponame>polrev-github/polrev-django
from django import forms
from django.contrib.admin import site, widgets
from areas.models import LocalCouncilDistrict
from .area_forms import AreaForm
class LocalCouncilDistrictForm(AreaForm):
class Meta:
model = LocalCouncilDistrict
fields = AreaForm.Meta.fi... | StarcoderdataPython |
1934983 | <reponame>mari-hernandez/03-tarea-mari-hernandez
import numpy as np
from matplotlib import pyplot as plt
G = 1
M = 1
m = 1
class Planeta(object):
"""
La clase planeta, crea un planeta dadas su condiciones iniciales de
posicion y velocidad ademas de un alpha opcional.Posee metodos para la
ecuacion de ... | StarcoderdataPython |
123780 | <filename>cla_backend/apps/knowledgebase/management/commands/grant_cla_superusers_article_categories_permissions.py
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Permission, Group, ContentType
class Command(BaseCommand):
def handle(self, *args, **options):
cont... | StarcoderdataPython |
1928151 | <filename>firestore/datatypes/integer.py
from firestore.datatypes.number import Number
class Integer(Number):
"""
64bit signed non decimal integer
"""
def __init__(self, *args, **kwargs):
self.py_type = int
super(Integer, self).__init__(*args, **kwargs)
| StarcoderdataPython |
1798233 | <reponame>MOvations/speedRuns
#%%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.neural_network import M... | StarcoderdataPython |
8062754 | <filename>elit/layers/embeddings/word2vec.py
# ========================================================================
# Copyright 2020 Emory University
#
# 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 ... | StarcoderdataPython |
1719897 | <reponame>jbyu/HorizonNet
#!/usr/bin/env python
from .naive import grid_sample as naive
from .faster import grid_sample as faster
__all__ = [
"faster",
"naive",
]
| StarcoderdataPython |
5140040 | <reponame>zehengl/ezapi_tmdb
from .base import process_response, ENDPOINT, any_required_kwargs
class ListMixin:
@process_response
def get_list(self, list_id, **kwargs):
"""
GET /list/{list_id}
"""
url = f"{ENDPOINT}/4/list/{list_id}"
return self.make_request("GET", url... | StarcoderdataPython |
1850313 | import csv
with open('Emp_details.csv','a') as csvfile:
ID="114185"
Name="RAMU"
Location="MUMBAI"
BU="FS"
newemp=ID+","+Name+","+Location+","+BU
csvfile.write(newemp+"\n")
| StarcoderdataPython |
9695101 | <reponame>hennr/buildnotify<gh_stars>10-100
import unittest
from buildnotifylib.core.continous_integration_server import ContinuousIntegrationServer
from buildnotifylib.core.projects import OverallIntegrationStatus
from buildnotifylib.project_status_notification import ProjectStatus, ProjectStatusNotification
from tes... | StarcoderdataPython |
3425288 | #! python3
# renameDates.py - Renames a bunch of files with US-style dates in the name to
# have UK-style dates
import shutil
import os
import re
date_pattern = re.compile(
r"""^(.*?) # all text before the date
((0|1)?\d)- # an optional 0 or 1 followed by a digit (month) then hyphen
([0-3]?\d)- # ... | StarcoderdataPython |
8046496 | """Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_BRIGHTNESS_PCT,
ATTR_COLOR_NAME,
ATTR_COLOR_TEMP,
ATTR_EFFECT,
ATTR_FLA... | StarcoderdataPython |
3382608 | import InputReader
"""
Decrypt word by counting how many times each character appears in each position in a word for a list of words
Uses a dictionary for each character position with the character as key and count as value.
"""
class wordDecrypter:
def __init__(self,wordLength):
self.dictionaries = [{} f... | StarcoderdataPython |
8012990 | <reponame>jacquerie/leetcode
# -*- coding: utf-8 -*-
class Solution:
def countGoodSubstrings(self, s: str) -> int:
return sum(ss[0] != ss[1] and ss[1] != ss[2] and ss[0] != ss[2] for ss in zip(*(s[i:] for i in range(3))))
if __name__ == '__main__':
solution = Solution()
assert 1 == solution.coun... | StarcoderdataPython |
165553 | <reponame>arjunkhunti-crest/security_content
"""
Disable a list of AWS IAM user accounts. After checking the list of accounts against an allowlist and confirming with an analyst, each account is disabled. The change can be reversed with the "enable user" action.
"""
import phantom.rules as phantom
import js... | StarcoderdataPython |
12863664 | #!/usr/bin/env python
__author__ = "bt3"
import random
''' The simplest way...'''
def quickSelect(seq, k):
# this part is the same as quick sort
len_seq = len(seq)
if len_seq < 2: return seq
# we could use a random choice here doing
#pivot = random.choice(seq)
ipivot = len_seq // 2
pivo... | StarcoderdataPython |
8089763 | # ======================================================================
# Knights of the Dinner Table
# Advent of Code 2015 Day 13 -- <NAME> -- https://adventofcode.com
#
# Python implementation by Dr. <NAME> III
# ======================================================================
# ============================... | StarcoderdataPython |
11357639 | # Generated by Django 3.0.4 on 2020-04-22 08:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hp', '0017_auto_20200422_0815'),
]
operations = [
migrations.AddField(
model_name='complaint',
name='reply',
... | StarcoderdataPython |
11305277 | from .full import Spotify
| StarcoderdataPython |
6705657 | import discord
def pretty_keys(ctx, keys):
"""
Returns an embed for keys for a prettier discord format
"""
embed = discord.Embed(
title='Office Keys',
color=0x03f8fc,
timestamp=ctx.message.created_at)
for key in keys:
id_value = f'{key[0]}' + '\u2800' * 45
em... | StarcoderdataPython |
4931196 | <filename>hapy/hapy/render.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import jinja2
from loguru import logger
import shutil
'''
Jinja2 Render Util
'''
class Render(object):
def __init__(self):
pass
def render_j2_template_file(self, templateFile, searchPath, **kwargs):
""" T... | StarcoderdataPython |
167325 | # Demonstrate how to use dictionary comprehensions
def main():
# define a list of temperature values
ctemps = [0, 12, 34, 100]
# Use a comprehension to build a dictionary
tempDict = {t: (t * 9/5) + 32 for t in ctemps if t < 100}
print(tempDict)
print(tempDict[12])
# Merge two dictionarie... | StarcoderdataPython |
6646186 | import numpy as np
import json
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
import torch.utils.data as data
from sklearn.metrics import confusion_matrix
from sklearn.datasets import load_svmlight_file
from sklearn.model_select... | StarcoderdataPython |
55368 | # Copyright 2019 The Regents of the University of California.
#
# 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 applic... | StarcoderdataPython |
276002 | ## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(sel... | StarcoderdataPython |
137172 | # Copyright 2018-2019 SourceOptics Project Contributors
#
# 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... | StarcoderdataPython |
11307473 | from typing import Any, Tuple, TextIO
import swan.io.ioutil
import swan.util
import os
import platform
import datetime
class File:
""" Describes a file and allows for the aplication of usefull functions.
This class describes a file with usefull information like permissions size and other features
like th... | StarcoderdataPython |
8022497 | from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='MaForecasting a time series using regression, ARIMA and RNN methods among others',
author='Fernando_Montes',
license='MIT',
)
| StarcoderdataPython |
4833062 | # -*- coding: utf-8 -*-
# Copyright 2014, 2015 OpenMarket 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 applica... | StarcoderdataPython |
1844810 | class Param:
def __init__(self, name, param_line, param_col, param_type,
default_val, value_range, steps=None):
self.name = name
self.param_line=param_line
self.param_col=param_col
self.param_type=param_type
self.param_default=default_val
self.value_r... | StarcoderdataPython |
382571 | from decimal import Decimal
from httmock import HTTMock, all_requests
import pytest
from htmltab.cli import main
from htmltab.utils import numberise
@all_requests
def basic_response(url, request):
with open("tests/fixtures/basic.html") as fh:
file_contents = fh.read()
return {"status_code": 200, "te... | StarcoderdataPython |
11272126 | # -*- coding: utf-8 -*-
"""
识别图像的类,为了快速进行多次识别可以调用此类下面的方法:
R = Recognizer(image_height, image_width, max_captcha)
for i in range(10):
r_img = Image.open(str(i) + ".jpg")
t = R.rec_image(r_img)
简单的图片每张基本上可以达到毫秒级的识别速度
"""
import tensorflow as tf
import numpy as np
from PIL import Image
from sample import sample_co... | StarcoderdataPython |
50630 | #!/usr/bin/python
import serial
import sys
import time
def main():
while True:
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=5000)
last_time = time.time()
while True:
tag = ser.readline().strip()
new_time = time.time()
print('%s %s'%(tag, new_time - ... | StarcoderdataPython |
3207847 | <gh_stars>1-10
"""
Assembles Model
"""
import iomb
import logging as log
from useeiopy.common import modulepath
#Turn on logging to see process in terminal
iomb.log_all(level=log.INFO)
"""
Class to extend iomb.model to give it a name and modelpath
"""
class Model(object):
def __init__(self, iomb_model=iomb.mode... | StarcoderdataPython |
6414544 | #!/usr/bin/env python
# encoding: utf-8
'''
@author: <NAME>
@license: (C) Copyright @ <NAME>
@contact: <EMAIL>
@file: jianzhi_offer_59.py
@time: 2019/5/9 13:23
@desc:
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
d... | StarcoderdataPython |
4927174 | <reponame>shopkeep/deis
"""
RESTful URL patterns and routing for the Deis API app.
Clusters
========
.. http:get:: /api/clusters/(string:id)/
Retrieve a :class:`~api.models.Cluster` by its `id`.
.. http:delete:: /api/clusters/(string:id)/
Destroy a :class:`~api.models.Cluster` by its `id`.
.. http:get:: /api... | StarcoderdataPython |
3581474 | import math
import os
from utils.utils import get_logger, is_logging_process
def train_model(cfg, model, train_loader, writer):
logger = get_logger(cfg, os.path.basename(__file__))
model.net.train()
for input_, target in train_loader:
model.feed_data(input=input_, GT=target)
model.optimiz... | StarcoderdataPython |
4945248 | from os import chdir as os_chdir
from pathlib import Path
os_chdir(Path(__file__).resolve().parent)
from sys import path as sys_path
sys_path.append('lib')
import logging
import pyd3ckbase as __
import pyd3ckservice.redis as srv_redis
try:
_cfg = __.init(__.get_arg_parser())
log = logging.getLogger(__name__)
e... | StarcoderdataPython |
1739511 | import sys
__all__ = ['register_after_fork']
if sys.platform == 'win32' or sys.version_info < (3, 7):
import multiprocessing.util as _util
def _register(func):
def wrapper(arg):
func()
_util.register_after_fork(_register, wrapper)
else:
import os
def _register(func):
... | StarcoderdataPython |
11391528 | from PySide2 import QtCore, QtWidgets, QtGui
from element.LineEdit import LineEdit
from element.PushButton import DefaultPushButton
class FileEdit(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.label = LineEdit("")
self.button = DefaultPushButton("Browse... | StarcoderdataPython |
3395159 | <reponame>SpotlightKid/jackclient-python
#!/usr/bin/env python3
"""Display information about time, transport state et cetera.
This is somewhat modeled after the "showtime.c" example of JACK.
https://github.com/jackaudio/example-clients/blob/master/showtime.c
https://github.com/jackaudio/jack2/blob/master/example-clie... | StarcoderdataPython |
1753729 | import json
import os
from pathlib import Path
import shutil
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from attr import dataclass
@dataclass
class PropertyInfo:
Name: str
Type: Optional[str]
Pattern: Optional[str]
UnderlyingDataType: Optional[s... | StarcoderdataPython |
12842835 | <filename>repos/build_pipeline/lambdas/extract_metrics/extract_metrics.py
"""
This Lambda parses the output of ModelQualityStep to extract the value of a specific metric
"""
import json
import boto3
sm_client = boto3.client("sagemaker")
s3 = boto3.resource('s3')
def lambda_handler(event, context):
# model quali... | StarcoderdataPython |
5099361 | #!/usr/bin/env python3
# encoding: utf-8
# @Time : 2019/5/9 14:18
# @Author : <NAME>
import glob
import os
import numpy as np
import nibabel as nib
import torch
from torch.utils.data import Dataset, DataLoader
import random
class Brats2018(Dataset):
def __init__(self, patients_dir, crop_size, modes, train=Tru... | StarcoderdataPython |
3510225 | <gh_stars>1-10
import configparser
import datetime
import logging
import os
import pyspark
from pyspark import SparkConf
from pyspark.sql import SparkSession
from pyspark.sql.functions import col
from pyspark.sql.functions import explode
from pyspark.sql.functions import lower
from pyspark.sql.functions import regexp_... | StarcoderdataPython |
3344131 | from .mini_zinc import *
| StarcoderdataPython |
3595290 | <reponame>Jac-Lazza/termiko
#author: n01
"""
Useful Keyboard keys
"""
# UP = "\x1b[A"
# DOWN = "\x1b[B"
# RIGHT = "\x1b[C"
# LEFT = "\x1b[D"
UP = "W"
LEFT = "A"
DOWN = "S"
RIGHT = "D"
ENTER = "\r"
# ARROW_PREP = ('\x1b', '[') #Not needed anymore
# ESC = "\x1b" #Now this keys can be finnaly hit EDIT: no, it has problems... | StarcoderdataPython |
328278 | <filename>qulab/sugar.py
import asyncio
from urllib.parse import urlparse
from qulab._config import config, config_dir
from qulab.dht.network import Server as DHT
from qulab.dht.network import cfg as DHT_config
from qulab.dht.utils import digest
from qulab.exceptions import QuLabRPCError, QuLabRPCTimeout
from qulab.rp... | StarcoderdataPython |
283258 | #
# This file is part of LiteDRAM.
#
# Copyright (c) 2019 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
import os
import filecmp
import unittest
from litex.build.tools import write_to_file
from litedram.init import get_sdram_phy_c_header, get_sdram_phy_py_header
def compare_with_reference(content, filen... | StarcoderdataPython |
11305417 | <reponame>ARMmbed/mbed-client-pal-public
# -----------------------------------------------------------------------
# Copyright (c) 2016 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# Licensed under the Apache License, Version 2.0 (the License); you may
# not use this file except in compliance... | StarcoderdataPython |
4824600 | <filename>userbot/plugins/dumpster_IQ.py
#@TeleOniOn
from telethon import events
import asyncio
from userbot.utils import admin_cmd
from telethon.errors.rpcerrorlist import MessageIdInvalidError
@borg.on(admin_cmd(pattern="dump ?(.*)"))
async def _(message):
try:
obj = message.pattern_match.group(1)
... | StarcoderdataPython |
9689259 | # ---------------------------------------------------------------------------------------------------------------------
# <NAME> - V0.1 - 15/11/2021 Creation of the python DEMIX library
# <NAME> - V0.2 - 17/11/2021 Added several useful lists to be used
# -----------------------------------------------------------------... | StarcoderdataPython |
3539515 | import pandas as pd
import numpy as np
import pickle
import os
import tensorflow as tf
import yamnet.features as features_lib
import yamnet.params as params
from librosa.core import load
from librosa.feature import melspectrogram
from librosa import power_to_db
from sklearn.preprocessing import LabelEncoder, OneHotEn... | StarcoderdataPython |
12865037 | <gh_stars>0
# Copyright 2015-2018,2020 <NAME>
# License MIT (https://opensource.org/licenses/MIT).
{
"name": "POS debranding",
"version": "13.0.1.0.0",
"author": "IT-Projects LLC, <NAME>",
"license": "Other OSI approved licence", # MIT
"category": "Debranding",
"support": "<EMAIL>",
"websit... | StarcoderdataPython |
1678757 | ''' Some public credential information and checks used in Python scripts.
By: WhiteBombo
'''
CLIENT_ID = 'qm7yhtp9i5h2785tjrkyh7a1lvsls3'
def check_id():
''' Checks whether a Client-ID exists and throws a tantrum if it doesn't. '''
try:
if CLIENT_ID == '':
print('Missing Client-ID. A tant... | StarcoderdataPython |
11359492 | <reponame>craigh92/ros2cli
# Copyright 2019 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | StarcoderdataPython |
1977743 | # Getting started with APIC-EM APIs
# Follows APIC-EM Basics Learning Lab
# Create a Policy Use Case
# Basic Steps
# 1. Get Hosts
# 2. Get the count of the policies
# 3. Create a new policy
# 4. Check on the progress of the create task
# 5. Get the count of the policies after the task was added
# 6. Get Policies ... | StarcoderdataPython |
8127247 | from .models import *
from rest_framework import serializers
# CRUD API
class ReviewSerializer(serializers.ModelSerializer):
class Meta:
model = Review
fields = ('visited_day', 'region', 'cafe_name', 'theme_name', 'participant_num', 'escape_flag', 'r_time', 'star_num')
class ReviewDetailSeria... | StarcoderdataPython |
4869745 | # Copyright (c) 2013, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
if not filters: filters = {}
columns = get_columns()
start_up_summary = get_start_up_summary(filters)
first_off_su... | StarcoderdataPython |
3509050 | APP_NAME = "cartoview_arcgis_portal"
BASE_TPL = APP_NAME + "/base.html"
MAP_LIST_TPL = APP_NAME + "/map_list.html"
MAP_LIST_ACTIONS_TPL = APP_NAME + "/map_list_actions.html"
MAP_EDIT_TPL = APP_NAME + "/map_edit.html"
ITEM_DATA_JSON_TPL = APP_NAME + "/portal_json_config/item_data.json"
OPERATIONAL_LAYERS_JSON_TPL = AP... | StarcoderdataPython |
369053 | # !/usr/bin/python
"""
Created on Thu Apr 4 08:37 2013
@author: marcel
"""
import pygame as pg
from pygame.locals import *
from data.tilemap import Tilemap
def main():
pg.init()
screen = pg.display.set_mode((800, 600))
pg.display.set_caption('Bow & Arrows')
pg.mouse.set_visible(1)
clock = pg.t... | StarcoderdataPython |
8003009 | import asyncio
async def echo(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
print("New connection")
try:
while data := await reader.readline():
writer.write(data.upper())
await writer.drain()
print("Leaving connection!")
except asyncio.CancelledError:... | StarcoderdataPython |
11366423 | from django.db import models
from django.db.models import F
class Agency(models.Model):
id = models.AutoField(primary_key=True)
create_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
toptier_agency = models.ForeignKey("references.ToptierAgency", models.... | StarcoderdataPython |
293136 | #!/usr/bin/env python3
#Advent of Code Day 14 "Extended Polymerization"
import sys
sys.path.append("..")
import submarine
sub = submarine.Submarine()
filename = "input.txt"
#Part 1
man = sub.manual
file = open(filename,"r")
man.parse_rules(file.readlines())
print(man.polymer_template)
man.do_steps(number_of_steps=1... | StarcoderdataPython |
43434 | <gh_stars>0
from invoke import task
from .common import docker, constants, config, ROOT_DIR
valid_backend_names = constants.D_BACKENDS
@task(help={'name': '|'.join(constants.D_ALL)})
def build(c, name, local=False, build_frontend=True):
assert name in constants.D_ALL
docker.auto_build(c, 'frontend', local=lo... | StarcoderdataPython |
3594944 | <filename>flarestack/analyses/angular_error_floor/test_dynamic_pull_correction.py
from __future__ import division
from builtins import str
from builtins import range
import os
import numpy as np
import matplotlib.pyplot as plt
from flarestack.data.icecube.ps_tracks.ps_v002_p01 import IC86_1_dict
from flarestack.data.ic... | StarcoderdataPython |
9764709 | <gh_stars>0
print("bob.py was just imported")
def ben():
print("ben")
class Jim:
def jane(self, hey):
print("jane")
| StarcoderdataPython |
9702130 | import cv2
import numpy as np
filename = 'D:\master\opencv-python\image\sad.jpg'
image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
# print(image)
cv2.imshow('origin', image)
h, w = image.shape[:2] # 把图片2像素的行数,列数以及通道数返回给rows,cols,channels
sum = np.zeros((h + 1, w + 1), dtype=np.float32) # 创建指定大小的数组,数组元素以 0 来填充:
ima... | StarcoderdataPython |
1747646 | <reponame>Picarro-kskog/mcculw
from __future__ import absolute_import, division, print_function
from builtins import * # @UnusedWildImport
from mcculw import ul
from mcculw.ul import ULError
from examples.console import util
from examples.props.ai import AnalogInputProps
use_device_detection = True
def run_examp... | StarcoderdataPython |
3524522 | # Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - <NAME>, <<EMAIL>>, ... | StarcoderdataPython |
137591 | #Author(s): <NAME> (15051) and <NAME> (15118)
#Code under the project of the course PHY312 Numerical Methods and Programming
import numpy as np
from math import *
import matplotlib.pylab as plt
import pyfits as pf
from mpl_toolkits import mplot3d
from gaussfit import *
from Analysis import *
def plot_all_star(A):
... | StarcoderdataPython |
9753514 | import unittest
from typing import List
from octopus import DumboOctopi
class TestDumboOctopi(unittest.TestCase):
def setUp(self) -> None:
pass
def test_dumbo_octopus_sample(self) -> None:
lines = file_read_helper('day-11/sample_input.txt')
dumbo_octopi = DumboOctopi(lines)
fla... | StarcoderdataPython |
12853550 | from functools import wraps
from flask import request, make_response
from .exceptions import ApiError
from .schemas import create_schema, ma_version_lt_300b7
def request_schema(schema_or_dict, extends=None, many=None, cache_schema=True, pass_data=False):
schema_ = create_schema(schema_or_dict, extends)
def... | StarcoderdataPython |
8180928 | import re
result = 0
double = re.compile( r"([a-z]{2}).*\1" )
repeat = re.compile( r"([a-z]).\1")
with open("input.txt", "r") as input:
for line in input:
line = line.strip()
prop1 = double.search(line) is not None
prop2 = repeat.search(line) is not None
if prop1 and p... | StarcoderdataPython |
3551155 | <gh_stars>1-10
import numpy as np
from PIL import Image, ImageDraw
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
from team_code.base_agent import BaseAgent
from team_code.planner import RoutePlanner
class MapAgent(BaseAgent):
def sensors(self):
result = super().sensors()
... | StarcoderdataPython |
1763645 | import backup
backup.Bdd_Updates() | StarcoderdataPython |
8023427 | # Copyright Notice:
# Copyright 2016-2019 DMTF. All rights reserved.
# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Interface-Emulator/blob/master/LICENSE.md
# get_chassis_template()
#from api_emulator.utils import timestamp
_CHASSIS_TEMPLATE = \
{
"@odata.contex... | StarcoderdataPython |
4890892 | # Copyright 2012, <NAME>, NTT MCL, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | StarcoderdataPython |
11359858 | # Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | StarcoderdataPython |
1707926 | <reponame>huong-rose/student-practices
n=input()
a=[]
b=[]
for i in range(len(n)):
a.append(n.count(n[i]))
for i in range(len(n)):
b.append([n[i],a[i]])
c=[]
for i in range(len(b)):
if (b[i] in c)==False:
c.append(b[i])
for i in range(len(c)):
print(str(c[i][0])+'('+str(c[i][1])+... | StarcoderdataPython |
158450 | <gh_stars>1-10
#!/usr/bin/env python3
import argparse
from random import choice
from multiprocessing import freeze_support
from textwrap import dedent
from common import VALID_FILENAME, ANSWER_FILENAME, DEFAULT_ROUNDS, Mode, get_words
from play import play
from benchmark import benchmark
DEFAULT_MODE = Mode.SOLVE
d... | StarcoderdataPython |
4890068 | """
Find the k-cores of a graph.
The k-core is found by recursively pruning nodes with degrees less than k.
See the following references for details:
An O(m) Algorithm for Cores Decomposition of Networks
<NAME> and <NAME>, 2003.
https://arxiv.org/abs/cs.DS/0310049
Generalized Cores
<NAME> and <NAME>, 2002.
https://... | StarcoderdataPython |
3434381 | <filename>tanuky/__init__.py
from .tanuky import *
__version__ = '1.3.1'
| StarcoderdataPython |
1904400 | <filename>Bot/bot.py
'''
This project was made by https://github.com/himanshu2406 , incase of cloning / modifying or release of any bot based on this source code,
You are obligated to give credits to the original author.
Original repo: https://github.com/himanshu2406/Corona-Tracker-Bot
Original Bot Support Serv... | StarcoderdataPython |
9638334 | <filename>pybacktest/verification.py
import pandas
import sys
from pybacktest.backtest import Backtest
def iter_verify(strategy_fn, data, window_size):
"""
Verify vectorized pandas backtest iteratively by running it
in sliding window, bar-by-bar.
NOTE: depreciated, use `verify` now.
"""
sp = ... | StarcoderdataPython |
5139205 | """simd float32x4"""
def main():
float32x4 a = numpy.array( [1.1, 1.2, 1.3, 0.4], dtype=numpy.float32 )
float32x4 b = numpy.array( [1.9, 1.8, 1.7, 0.6], dtype=numpy.float32 )
c = a + b
print(c)
if PYTHON == 'PYTHONJS':
TestError( c.x==3.0 )
TestError( c.y==3.0 )
TestError( c.z==3.0 )
TestError( c.w==1.0... | StarcoderdataPython |
6549351 | <filename>aws_boto3_demo.py
"""
This is a python demo of boto3 library.
Written By: <NAME>
"""
import boto3
s3_resource = boto3.resource('s3')
#Create a Bucket
s3_resource.create_bucket(Bucket="first-aws-bucket-1")
#List all buckets in S3
for bucket in s3_resource.buckets.all():
print(bucket.name)
#Uploading an... | StarcoderdataPython |
9624410 | """
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous
subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no
such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2, 3, 1, 2, 4,... | StarcoderdataPython |
11255863 | """
Copyright (C) 2011 <NAME>
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy... | StarcoderdataPython |
3531360 | # hitme_game/routing.py
from django.conf.urls import url
from django.urls import path
from . import consumers
websocket_urlpatterns = [
url(r'^ws/lobby/$', consumers.LobbyConsumer),
path('ws/game/<game_url>/', consumers.GameRoomConsumer),
]
| StarcoderdataPython |
1948215 | <gh_stars>0
from discord.ext import commands
import discord
from discord.utils import get
class FeedbackCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def botfeedback(self, ctx):
channel = self.bot.get_channel(826078825649668136)
if not ctx.me... | StarcoderdataPython |
5010246 | <filename>stephen/week3.py
from collections import Counter
from distutils.archive_util import make_zipfile
from typing import List, Tuple
def get_rainfall(data: List[Tuple[str, int]]) -> dict:
totals = {}
for pair in data:
city, rain = pair[0], pair[1]
if city in totals:
totals[ci... | StarcoderdataPython |
3234110 | <reponame>drlim2u/Shuttle-Bus-Educational-Tool
from common.Scope import Scope
from common.TokenType import TokenType
class Function(Scope):
"""
Class to define the Function object to be used during compilation of the whole program.
"""
def __init__(self, line_number, instructions):
"""
... | StarcoderdataPython |
8091887 | <filename>heavytailed/lognormal.py
from .base_distribution import distribution
import numpy as np
from scipy.stats import norm
from scipy.optimize import minimize
class lognormal(distribution):
'''
Discrete log-normal distributions, given by
ln(x) ~ Normal(mu, sigma^2)
More specificly:
P(k)=(Phi(... | StarcoderdataPython |
4332 | # Create your views here.
from .models import Mfund
import plotly.graph_objects as go
from plotly.offline import plot
from plotly.tools import make_subplots
from django.db.models import Q
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_require... | StarcoderdataPython |
9612299 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
simple boto instance example
'''
# import argparse
from collections import defaultdict
import boto3
EC2 = boto3.resource('ec2')
SESSION = boto3.Session()
REGIONS = SESSION.get_available_regions('ec2')
# print REGIONS
EC2CLIENT = SESSION.client('ec2', 'us-west-1')
EC... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.