id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
3542819
import StructPy.cross_sections as xs import StructPy.structural_classes as sc import StructPy.materials as ma xs1 = xs.generalSection(A=30, Ix=700) s1 = sc.Structure(xs1, ma.Steel(E=29000)) s1.addNode(0, 0) s1.addNode(0, 144) s1.addNode(144, 144) s1.addMember(0, 1) s1.addMember(1, 2) m1 = s1.members[0] stiff1 = m1...
StarcoderdataPython
3238395
<filename>nipy/io/nibcompat.py<gh_stars>0 """ Compatibility functions for older versions of nibabel Nibabel <= 1.3.0 do not have these attributes: * header * affine * dataobj The equivalents for these older versions of nibabel are: * obj.get_header() * obj.get_affine() * obj._data With old nibabel, getting unscale...
StarcoderdataPython
9623710
<filename>python/raydp/spark/tf/dataset.py # # 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, Ve...
StarcoderdataPython
6624878
# coding=utf-8 # Copyright 2019 The TensorFlow Datasets 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 the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
StarcoderdataPython
3524902
<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2018-02-05 18:56 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('info', '0021_info_logo_header'), ] operations = [ migrations.RemoveFiel...
StarcoderdataPython
8097631
import sys from django.core.exceptions import ValidationError, NON_FIELD_ERRORS try: from django.db import models except Exception: print("There was an error loading django modules. Do you have django?") sys.exit() class FeedSource(models.Model): name = models.TextField(null=False) status = mode...
StarcoderdataPython
8048237
<filename>test/test_storage.py<gh_stars>0 from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from conftest import Mock import responses class TestStorage(object): @responses.activate def test_get_storage(self, m...
StarcoderdataPython
1907793
<reponame>mrjmad/gnu_linux_mag_drf<filename>hall_of_cards/cardsgame/views.py<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import (print_function, division, absolute_import, unicode_literals) from django.core.exceptions import ObjectDoesNotExist from rest_framework import viewsets from rest_framework import sta...
StarcoderdataPython
4980126
<gh_stars>0 import requests from printing import printin def testCase1(serverIP,username,password): ''' This will demostrate a user that creates an account and then leaves the app :return: Nothing ''' print("\nTest case #1 Create Acc and leave the App \n") r = requests.post("http://" + serv...
StarcoderdataPython
1775253
#!/usr/bin/env python # -*- coding: UTF-8 -*- import platform from selenium import webdriver from bs4 import BeautifulSoup # Check Python version # print(platform.python_version()) # Using the right PhantomJS for the corresponding OS if platform.system() == "Windows": PHANTOMJS_EXE = "./PhantomJS/phantomjs.exe"...
StarcoderdataPython
11368859
from height_over_bottom import HeightOverBottom from network_loss import NetworkLoss from thruster_out import ThrusterOut from bus_voltage import BusVoltage from odom_kill import OdomKill from kill import Kill from hw_kill import HwKill
StarcoderdataPython
6702241
<filename>tests/test_regrid_periodicity.py import requests import cdms2 import os import sys import basetest import numpy as np import basetest import ssl modFile = "model_ANN_climo.nc" obsFile = "GPCP_ANN_climo.nc" class TestRegrid(basetest.CDMSBaseTest): def setUp(self): super(TestRegrid, self).setUp()...
StarcoderdataPython
11294288
# -*- coding: utf-8 -*- """ Created on Tue Dec 17 12:59:29 2019 @author: ap18525 """ import pandas as pd import numpy as np from netCDF4 import Dataset def read_csv_data(folder_path,file_name,column_name = None): data = pd.read_csv(folder_path+"/"+file_name) ### Dates ### # the next day at 00:00 we need ...
StarcoderdataPython
209931
# Using cryptographic-appropriate methods to generate random data # that may be sensitive. secrets module introduced in Python 3.6 import os import secrets # the urandom() function in the OS module produces random numbers that # are cryptographically safe to use for sensitive purposes result = os.urandom(8) print([he...
StarcoderdataPython
6520488
import unittest from app.models import NewsSource class NewsSourceTest(unittest.TestCase): """Test class to test newsSource class""" def setUp(self) -> None: """Instructions to be run before each test case""" self.new_source = NewsSource("County-news", "County news", "Kenya", "Source for the...
StarcoderdataPython
143423
# import csv # import PyPDF2 # import nltk # from tika import parser # from spacy.en import English # # #nltk.download('punkt') # #nltk.download('averaged_perceptron_tagger') # #from nltk.corpus import brown # #nltk.download('brown') # # raw = parser.from_file('C://Users//bvjan//Documents//data.pdf') # my =...
StarcoderdataPython
3206771
#!/home/wiseman/anaconda3/bin/python # -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2019 University of Southampton # All Rights Reserved. # 12/05/2018 ############################################################################## __author__ = "<...
StarcoderdataPython
1772353
# CS+ startup python script ThrowExceptSave = common.ThrowExcept common.ThrowExcept = True try: if ScriptStarted == True: pass except: ScriptStarted = False common.ThrowExcept = ThrowExceptSave del ThrowExceptSave if ScriptStarted == False: ScriptStarted = True common.Hook(__file__) def After...
StarcoderdataPython
3376928
<filename>clipmon.py #!/usr/local/bin/python3 import time, sys, os, subprocess, re, traceback from datetime import datetime import pyperclip import conf def clip_str_to_path_line(clip_str, path_exists=os.path.exists): if clip_str.count('\n') > 1: return for f in test_replacements, test_partial_path: re...
StarcoderdataPython
3265298
<gh_stars>0 from typing import Iterable from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.module_loading import import_string def get_all_dynamic_perm_names() -> Iterable[str]: """ Get a list of all dynamic permissions """ return settings.DYNAMI...
StarcoderdataPython
1801030
import sys import os # \todo need to figure out where to put the lib/tnn.so binary so that it adheres to # usual import semantics sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'bin')) import tnnlib # just for testing from .conv_einsumfunc import *
StarcoderdataPython
1827097
questions = { "q1" : { "question": "Has your hero ever had a nationality other than the U.S.? ", "yes" : 500, "no" : 0 }, "q2" : { "question" : "Are your hero a student? ", "yes" : 200, "no" : 0 }, "q3" : { "question" : "Are your hero a super...
StarcoderdataPython
1850931
<gh_stars>0 """Main implementation.""" import argparse import os from livereload import Server from . import __version__ from .sphinx import SPHINX_BUILD_OPTIONS, SphinxBuilder from .watcher import LivereloadWatchdogWatcher from .utils import find_free_port DEFAULT_IGNORE_REGEX = [ r"__pycache__/.*\.py", r"...
StarcoderdataPython
6438441
<reponame>mariajosearias/talleres-for-estructuras-control- archivo = open('paises.txt', 'r') #Imprima todos los paises y capitales, cuyo inicio sea con la letra U lista=[] ciudad=[] for i in archivo: a=i.index(":") for r in range(a+2,len(i)): lista.append(i[r]) a="".join(lista) ciudad.append(a) lista=[] ...
StarcoderdataPython
1765246
import requests from collections import namedtuple import datetime _YNABTransactionBase = namedtuple( "YNABTransactionBase", ("date", "amount", "payee_name", "import_id", "is_foreign", "is_cleared"), ) class YNABTransaction(_YNABTransactionBase): @classmethod def from_up_transaction_data(cls, transac...
StarcoderdataPython
8161487
<gh_stars>1-10 """A game state for a level loaded from a file.""" # Copyright © 2014 <NAME> <<EMAIL>> # License: MIT, see the LICENSE file. import sfml as sf from pymazing import world, level_loader, color, light, camera, coordinate_grid, renderer, matrix class GameStateLoadedLevel: def __init__(self,...
StarcoderdataPython
4965339
<filename>classification/demos.py import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import ListedColormap import dataset_gen from .regression import (linear_regression, multivariate_regression, polynomial_regression) from .classi...
StarcoderdataPython
9627396
''' Created on Nov 6, 2011 @author: cryan Rough script for testing the python simulator ''' import numpy as np import matplotlib.pyplot as plt from PySim.SystemParams import SystemParams from PySim.QuantumSystems import Hamiltonian, Dissipator from PySim.PulseSequence import PulseSequence from PySim.Simulation impo...
StarcoderdataPython
246125
import unittest from katas.kyu_8.even_or_odd import even_or_odd class EvenOrOddTestCases(unittest.TestCase): def test_equals(self): self.assertEqual(even_or_odd(0), "Even") def test_equals_2(self): self.assertEqual(even_or_odd(1), "Odd") def test_equals_3(self): self.assertEqua...
StarcoderdataPython
5184301
#!/usr/bin/env python # coding:utf-8 from __future__ import unicode_literals import os import sys # 模块自己的PYTHON_PATH, 让代码找到正确的tools_lib. =>要在所有import前做!!! sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))) from tools_lib.common_util.log import init_log # 配置全局logging. => 配完PYTHON_...
StarcoderdataPython
367888
import pytest from scripts import Database from scripts import Accessor def test_connection_success(): try: conn = Database.Database.connect() except MyError: pytest.fail("Unhandled exception") def test_api(): page = "1" url = 'https://www.rentfaster.ca/api/search.json?keywords=&...
StarcoderdataPython
376831
from abc import ABC, abstractmethod class Entity(ABC): # pragma: no cover """ An interface representing a Telegram message entity. """ @abstractmethod def offset(self) -> int: """ :return: entity offset (int) """ pass @abstractmethod def length(self) -> in...
StarcoderdataPython
8196705
#import dependencies import pandas as pd from bs4 import BeautifulSoup as bs from splinter import Browser import requests def init_browser(): ex_path = {'executable_path': '../Mission_to_Mars/chromedriver.exe'} #changed pc path to git forlder browser = Browser('chrome', **ex_path, headless=True) #return ...
StarcoderdataPython
11946
# -*- coding: utf-8 -*- """ manage ~~~~~~ Flask-Script Manager """ import os from flask.ext.script import Manager from flask.ext.migrate import MigrateCommand from fbone import create_app from fbone.extensions import db from fbone.utils import PROJECT_PATH, MALE from fbone.modules.user import User, ADMI...
StarcoderdataPython
11256366
<reponame>MacarielAerial/eos<gh_stars>1-10 """ Ordinally encodes categorical features of a dataframe as a preprocessing step for AutoEncoder later to embed categorical features """ import logging from typing import Dict, List from numpy import ndarray from pandas import DataFrame from sklearn.preprocessing import Ord...
StarcoderdataPython
4962788
<reponame>nuuuwan/news_lk2<gh_stars>1-10 import os import shutil from utils import hashx from news_lk2._utils import log REPO_NAME = 'news_lk2' GIT_REPO_URL = f'https://github.com/nuuuwan/{REPO_NAME}.git' DIR_ROOT = '/tmp' DIR_REPO = os.path.join(DIR_ROOT, REPO_NAME) DIR_ARTICLES = os.path.join( DIR_REPO, 'a...
StarcoderdataPython
5003810
<filename>algorithm/BOJ/I:O/11721.py word=input() length = len(word) for i in range(0,length,10): th = i + 10 print(word[i:th])
StarcoderdataPython
40331
<reponame>vicrsp/rto from setuptools import setup, find_packages setup( name='rtotools', version='0.1.0', description='Real-Time Optimization Tools', url='https://github.com/vicrsp/rto', author='<NAME>', author_email='<EMAIL>', license='MIT', package_dir={"": "src"}, packages=fi...
StarcoderdataPython
6659291
<gh_stars>1-10 # proxy module from __future__ import absolute_import from apptools.appscripting.scriptable import *
StarcoderdataPython
5002971
<reponame>pots007/fbpic<filename>fbpic/lpa_utils/laser/longitudinal_laser_profiles.py # Copyright 2016, FBPIC contributors # Authors: <NAME>, <NAME> # License: 3-Clause-BSD-LBNL """ This file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC) It defines a set of common longitudinal laser profiles. """ import ...
StarcoderdataPython
3558024
from setuptools import setup, find_packages import pushoverflow setup( name="pushoverflow", version=pushoverflow.__version__, author=pushoverflow.__author__, author_email="<EMAIL>", description="Pushover Notifications for StackExchange Sites", long_description=open("README.rst").read(), url...
StarcoderdataPython
6588592
import re import ipaddress import logging from collections import Counter logger = logging.getLogger(__name__) class LogParser: """Class to parse a log file and search for a specific ip/subnet address""" def __init__(self, ip, log_file, top): """ __init_ Args: ip (str): ip to sea...
StarcoderdataPython
9776091
import numpy as np import torch if __name__ == "__main__": labels = [] model = resnet() model.eval() aggre = np.load('../utils/cluster_v3.npy') images = h5py.File('path/to/video_h5', 'r')['video'] with torch.no_grad(): for im in images: im = (im/255.0-np.array([0.485, 0.456,...
StarcoderdataPython
3237213
<reponame>rickdg/vivi<gh_stars>1-10 # -*- coding: utf-8 -*- import lxml.objectify import pytest import zeit.cms.content.interfaces import zeit.cms.content.sources import zeit.content.video.interfaces import zeit.content.video.testing import zeit.content.video.video import zope.component class TestVideo(zeit.content.v...
StarcoderdataPython
11225750
""" This is the new gateway program to all of the cgns_utils. Run cgns_utils -help to get a list of all available options. The basic idea is as follows:: | write new file read cngs file -> Do some operations on it -> | .or. ...
StarcoderdataPython
4979988
<gh_stars>0 # Projeto similar ao descrito no Notebook, porém com mais volumes de dados e # rodado em Spark, instalado localmente. Executado com pyspark. # Tempo estimado: 29 segundos com 200.000 matches / 400.000 hitóricos from pyspark.sql import SparkSession from pyspark.sql import Row from pyspark.sql imp...
StarcoderdataPython
11317269
import unittest import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'jgtextrank')) sys.path.append(os.path.join(os.path.dirname(__file__))) import types import warnings from collections import Counter import networkx as nx import matplotlib as mpl if os.environ.get('DISPLAY','') == ''...
StarcoderdataPython
8119456
name = input("Write your name: ") print("Hello", name, "!") hours = int(input("Enter Hours: ")) rate = float(input("Enter Rate: ")) salary = hours * rate print("Pay: {0:.2f}".format(salary)) width = 17 height = 12.0 print(width/2) print(type(width/2)) print(width/2.0) print(type(width/2.0)) print(height/3) print(typ...
StarcoderdataPython
240408
import numpy as np import pandas as pd anime = pd.read_csv('./data/AnimeData.csv') def PreProcessing(anime): #Cleaning data #Deleting null ratings anime['Weighted_Score'] = anime['Weighted_Score'].apply(lambda x: np.nan if x==0 else x) anime['Genre'] = anime['Genre'].apply(lambda x: np.nan if x==0 or ...
StarcoderdataPython
5043830
# -*- coding:utf-8 -*- - import rospy import math import time import numpy as np np.random.seed(1) from nav_msgs.msg import Odometry from tf_rl.envs import gazebo_env from geometry_msgs.msg import Twist, Pose, Quaternion, Vector3, Point from std_srvs.srv import Empty from gazebo_msgs.srv import SetModelState, GetMode...
StarcoderdataPython
41159
#!/usr/bin/env python3 """ Models that maps to Cloudformation functions. """ def replace_fn(node): """Iteratively replace all Fn/Ref in the node""" if isinstance(node, list): return [replace_fn(item) for item in node] if isinstance(node, dict): return {name: replace_fn(value) for name, val...
StarcoderdataPython
6415889
from collections import deque dx = [0, 0, 1, -1] dy = [1, -1, 0, 0] n, m = map(int, input().split()) a = [list(map(int, list(input()))) for _ in range(n)] q = deque() check = [[False]*m for _ in range(n)] dist = [[0]*m for _ in range(n)] q.append((0,0)) check[0][0] = True dist[0][0] = 1 while q: x, y = q.p...
StarcoderdataPython
5099483
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os.path import re import subprocess from textwrap import dedent import pytest from pex.common import safe_open from pex.pex import PEX from pex.pex_bootstrapper import ensure_venv...
StarcoderdataPython
11305409
from __future__ import unicode_literals from django.core.exceptions import PermissionDenied from django.db.models import Count from rest_framework import response, viewsets, permissions, status, decorators, mixins from nodeconductor.core import serializers as core_serializers, filters as core_filters from nodeconduct...
StarcoderdataPython
1951586
import git # Git SHA repo = git.Repo(search_parent_directories=True) GIT_SHA = repo.head.object.hexsha
StarcoderdataPython
1823694
<gh_stars>1-10 #!/usr/bin/env python # coding: utf-8 __author__ = 'whoami' """ @version: 1.0 @author: whoami @license: Apache Licence 2.0 @contact: <EMAIL> @site: http://www.itweet.cn @software: PyCharm Community Edition @file: DataProcess.py @time: 2015-12-29 下午4:25 """ import ActionProcess import Tools import pickl...
StarcoderdataPython
11280332
<gh_stars>0 import time import client class Actuator(): """Class to represent greenhouse's actuators. Open two channels of communication, one with Manager server to read instructions to be turned on and off, the other with Environment server to act on it. Parameters ---------- `ID: str` ...
StarcoderdataPython
19108
""" Enum Assembler-Directives """ from enum import Enum, auto class AssemblerDirectives(Enum): START = auto() END = auto() ORG = auto() DEFINE = auto() @classmethod def to_string(cls): return "{START},{END},{ORG},{DEFINE}".format( START=cls.START.name, END=cls...
StarcoderdataPython
11399218
# !/usr/bin/env python # title :experiment_helper.py # description : Experiment helper class along with subclasses for each experiment, with their respective # characteristics and methods. # author :<NAME> # date :30092018 # version :1.0 # usage : - ...
StarcoderdataPython
6572362
<filename>examples/example_1.py<gh_stars>10-100 from causaleffect import createGraph, plotGraph, graph '''Code in Figure 3.5 (a)''' edges = ['X<->Z', 'X<->W', 'X->Z', 'Z->W', 'W->Y', 'X->Y'] G = createGraph(edges) print(graph.to_R_notation(edges)) plotGraph(G)
StarcoderdataPython
6546422
<reponame>kirichoi/tellurium #!/usr/bin/env python """ Functions to work with event triggers and event handling. Example demonstrates ho to attach such function. """ # TODO: test me, write example, update me import roadrunner # -------------------------------------------------- # Event handling functions # ---------...
StarcoderdataPython
4876754
<reponame>SergeHall/Tony-Gaddis-Python-4th class Pet: def __init__(self, name, animal_type, age): self.__name = name self.__animal_type = animal_type self.__age = age def get_name(self): return self.__name def get_animal_type(self): return self.__animal_type d...
StarcoderdataPython
3308000
<gh_stars>10-100 from django.urls import include from django.urls import path from django.urls import register_converter from common import views from common.path_converters import NumericSIDConverter register_converter(NumericSIDConverter, "sid") urlpatterns = [ path("", views.index, name="index"), path("he...
StarcoderdataPython
4971240
<filename>images/producer/src/producer.py # Copyright (c) 2021, Oracle and/or its affiliates. # All rights reserved. The Universal Permissive License (UPL), Version 1.0 as shown at http://oss.oracle.com/licenses/upl import json import socket import ssl import sys from datetime import datetime from math import cos from...
StarcoderdataPython
4924385
from Climate import Climate, getDetermination from math import sin, cos, radians, exp class Location(): N = 0 Latitude = 0 Longitude = 0 Height = 0 ClimateType = Climate.NONE_TYPE Time = 0 G_on = 0 G_0 = 0 G_cd = 0 G_cb = 0 CosOfZenithAngle = 0 Permeance = 0 def _...
StarcoderdataPython
4819421
from setuptools import setup,find_packages setup( name='DDos', version='1.0.3', description='DDos any site', long_description=open('README.md').read(), long_description_content_type="text/markdown", url='https://github.com/donno2048/DDos', packages=find_packages(), include_package_data=T...
StarcoderdataPython
240984
from rest_framework import serializers from .models import Ranking, Track class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ("name", "duration", "track_number", "order") class RankingSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=...
StarcoderdataPython
3263237
from django.apps import AppConfig class Sql3Config(AppConfig): name = 'SQL3'
StarcoderdataPython
1620843
from ..utility import * def handle(data, theme): theme.ping( message = data['zen'], zen = not configValue('allowArbitraryMessages') )
StarcoderdataPython
6403315
<gh_stars>1-10 # -*- coding: utf-8 -*- """ Created on Thu Nov 8 11:18:14 2018 SIFT特征点检测demo2 准备两张人脸图片,分别检测特征点并尝试匹配 若匹配成功,则可一定概率认为提供的两张人脸图片是同一个人 @author: zyb_as """ import cv2 import numpy as np from PIL import Image # 1) 以灰度图的形式读入图片 # 人脸模板 psd_img_1 = cv2.imread('jgz2.jpg', cv2.IMREAD_GRAYSCALE) # 待匹配图片 psd_img_...
StarcoderdataPython
4801445
#!/usr/bin/env python3 from numpy.random import randint import pygame, sys, time from detection import OpenCV from objects import * from layout import Button, Menu, printText from handleScore import getScore, saveScore pygame.init() class Game: w,h = 900,720 screen = pygame.display.set_mode((w,h)) detector = ...
StarcoderdataPython
11335271
<reponame>vipshop/Tuplenet<gh_stars>0 from pyDatalog import pyDatalog import physical_flow import middle_table as mid import lsp_ingress import lsp_egress import lrp_ingress import lrp_egress import pkt_trace import action import match from reg import * from logicalview import * from flow_common import * pyDatalog.cre...
StarcoderdataPython
6401450
<gh_stars>1-10 # coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from openapi_server.models.base_model_ import Model from openapi_server.models.text_contact_annotation import TextContactAnnotation from openapi_server.m...
StarcoderdataPython
1964474
<gh_stars>0 from ..utils.jl import jlprepare from ._helper import init, params def prepare(name): kwds = init(**params[name]) jlrun = jlprepare("Comparatist.Simulators.rnn.vec", name, m=kwds["m"]) def run(): jlkwds = jlrun() jlkwds["m"] = jlkwds["m"].T return jlkwds return run...
StarcoderdataPython
3423599
# -*- coding: utf-8 -*- # # Copyright (c) 2014 Netheos (http://www.netheos.net) # # 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 req...
StarcoderdataPython
8071228
<filename>tests/test_SimTimestampDiv.py # # ------------------------------------------------------------ # Copyright (c) All rights reserved # SiLab, Institute of Physics, University of Bonn # ------------------------------------------------------------ # import unittest import os import time from basil.dut import Du...
StarcoderdataPython
2468
<filename>tests/core/test_headerupdater.py # -*- coding: utf-8 -*- ''' HeaderUpdater class test ======================== ''' import unittest from tests.testutils import print_testtitle, validate_with_fail from builder.commands.scode import SCode, SCmd from builder.containers.chapter import Chapter from builder.contain...
StarcoderdataPython
1899514
import sys import os import time from torchvision import transforms import torch, torchaudio import yarp import numpy as np from speechbrain.pretrained import EncoderClassifier from project.voiceRecognition.speaker_embeddings import EmbeddingsHandler from project.faceRecognition.utils import format_face_coord, face_al...
StarcoderdataPython
5128002
<reponame>tlee911/aoc2021<gh_stars>0 with open('input.txt', 'r') as file: input = file.readlines() input = [ line.strip() for line in input ] def get_values_at_index(i, l): values = [] for line in l: values.append((line[i])) return values def get_counts_at_index(i, l): values = get_values...
StarcoderdataPython
3208466
<filename>src/testSylvSequence.py import numpy as np import matplotlib.pyplot as plt from matplotlib import animation import matplotlib.patches as patches from LucasKanadeBasis import * from LucasKanade import * from TemplateCorrection import * import time def copyRect(rect): rect_new = [] for ele in rect: ...
StarcoderdataPython
3594387
<reponame>a1b2c3d4e5x/spider_iyp<filename>const/sub_categories/base_category.py<gh_stars>0 from typing import List class BaseCategory(object): def list(self) -> List[str]: all = [] method_list = [method for method in dir(self) if method.startswith('_') is False] for item in method_list: ...
StarcoderdataPython
1750900
import discord # Make sure we're using the correct version of Discord.py if discord.__author__ != "Rapptz": print("Error: Please use the rewrite version of Discord.py.") print("Check the README for instructions.") exit() import requests, asyncio, platform from discord.ext.commands import Bot # End imports...
StarcoderdataPython
8059483
import sys, json TILE_SIZE = 32 def print_usage(): print("""USAGE: python tiled2json.py <input json tiled file> <output json file>""") def move_to_visible_area(out_map): """Moves the sprites in the map so that they begin at (0, 0)""" min_x = min(map(lambda node: node["x"], out_map["objects"])) min_y ...
StarcoderdataPython
110168
import json from django import template from django.utils.html import format_html from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def json_script_with_non_ascii(value, element_id): from django.core.serializers.json import DjangoJSONEncoder _json_sc...
StarcoderdataPython
12809448
#!/usr/bin/env python from datetime import datetime from collections import OrderedDict import argparse import csv import os import re import subprocess import sys import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # Saved Measurements: measurements = ['Min', 'Median', '90%ile', '95%ile', 'Max', '...
StarcoderdataPython
9664387
# Authors: <NAME> <<EMAIL>> # License: BSD 3-Clause import os from nose.plugins.attrib import attr from numpy import array, sqrt, zeros from numpy.random import randn from numpy.testing import assert_allclose from commpy.channelcoding.ldpc import get_ldpc_code_params, ldpc_bp_decode from commpy.utilities import hamm...
StarcoderdataPython
8060681
import dataclasses import enum from typing import Any, Dict, List, Optional class Form(enum.Enum): """ Represents the "forms" a JSON Typedef schema can take on. The JSON Typedef spec restricts valid schemas to only using certain combinations of keywords. This enum represents which of those valid combin...
StarcoderdataPython
8118491
<reponame>ericu-u/GirlHacks from cProfile import label from email.policy import default from django import forms diet_choices = ( ("Vegetarian", "Vegetarian"), ("Vegan", "Vegan"), ("Pescatarians", "Pescatarians"), ("Normal (Hybrid)", "Normal (Hybrid)"), ("Keto", "Keto"), ) sex_choices = ( ('Ma...
StarcoderdataPython
3405405
<reponame>ZhongXinWang/python #!/usr/bin/env python3 # -*- coding: utf-8 -*- #Author:Winston.Wang import logging def div(s): return 10/int(s); def foo(s): print(div(s)); if __name__ == '__main__': try: foo(0) except ZeroDivisionError as e: logging.error(e) finally: logging.debug('程序执行结束')
StarcoderdataPython
5189825
<reponame>jippo015/Sub-Zero.bundle<filename>Contents/Code/support/i18n.py # coding=utf-8 import inspect from support.config import config core = getattr(Data, "_core") # get original localization module in order to access its base classes later on def get_localization_module(): cls = getattr(core.localization...
StarcoderdataPython
6636618
import os import pytest from testing_utils import * try: import pandas from matmodlab2.fitting.mcgen import * except ImportError: pandas = None this_d = os.path.dirname(os.path.realpath(__file__)) @pytest.mark.mcgen @pytest.mark.skipif(pandas is None, reason='pandas not imported') def test_mcgen(): "...
StarcoderdataPython
4819496
from rest_framework.generics import CreateAPIView, ListAPIView from .serializers import BookmarkSerializer from authors.apps.articles.models import Article from authors.apps.articles.views import article_not_found from .models import BookmarkArticle from rest_framework.response import Response from rest_framework impor...
StarcoderdataPython
3579554
<reponame>Jiezhi/myleetcode #!/usr/bin/env python """ CREATED AT: 2021/8/11 Des: https://leetcode.com/problems/array-of-doubled-pairs/ https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/614/week-2-august-8th-august-14th/3877/ GITHUB: https://github.com/Jiezhi/myleetcode Reference: https://lee...
StarcoderdataPython
9745804
<gh_stars>1-10 #!/usr/bin/env python ############################################################################# ## # This file is part of Taurus ## # http://taurus-scada.org ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Taurus is free software: you can redistribute it and/or modify # it under...
StarcoderdataPython
6663466
import openseespy.opensees as ops from math import pi,cos,cosh,ceil from PyPonding.PondingLoadCell import PondingLoadCell2d import numpy as np import matplotlib.pyplot as plt class PondingLoadCell2d_OPS(PondingLoadCell2d): def __init__(self,id,nodeI,nodeJ,gamma,tw): self.id = id self.nodeI = nodeI ...
StarcoderdataPython
1910646
import json import argparse class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def print_err(msg): print("{}{}{}".format(bcolors.FAIL, m...
StarcoderdataPython
5137038
<reponame>rsmekala/junosautomation #!/usr/bin/env python # # Copyright 2017 Juniper Networks, Inc. All rights reserved. # Licensed under the Juniper Networks Script Software License (the "License"). # You may not use this script file except in compliance with the License, which is located at # http://www.juniper.net/su...
StarcoderdataPython
4898313
import numpy as np import av duration = 4 fps = 24 total_frames = duration * fps container = av.open("test.mp4", mode="w") stream = container.add_stream("mpeg4", rate=fps) stream.width = 480 stream.height = 320 stream.pix_fmt = "yuv420p" for frame_i in range(total_frames): img = np.empty((480, 320, 3)) i...
StarcoderdataPython
389864
# -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyrigh...
StarcoderdataPython
3394387
import scrapy, re from alleco.objects.official import Official class mccandless_t(scrapy.Spider): name = "mccandless_t" muniName = "MCCANDLESS" muniType = "TOWNSHIP" complete = True def start_requests(self): urls = ['https://www.townofmccandless.org/town-council'] for url in urls: yield scrapy...
StarcoderdataPython