id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1764866
<reponame>luk036/ellpy #! /usr/bin/env python3 """ Unittests for the CSD module """ import unittest import pycsd.csd as csd good_values_dict = { 16.5: '+0000.+', -16.5: '-0000.-', -2.5: '-0.-', 0.5: '0.+', -0.5: '0.-' } class tests__decimals(unittest.TestCase): def tmp(self): pass ...
StarcoderdataPython
3230293
from django.apps import AppConfig class UploadingConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'uploading'
StarcoderdataPython
100536
<reponame>worldwonderer/algorithm<gh_stars>1-10 # @Title: 删除排序链表中的重复元素 II (Remove Duplicates from Sorted List II) # @Author: 18015528893 # @Date: 2021-02-12 21:18:52 # @Runtime: 56 ms # @Memory: 14.9 MB # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.v...
StarcoderdataPython
3299815
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import unittest from unittest.mock import MagicMock from xml.etree.ElementTree import Element, tostring import numpy as np from openvino.tools.mo.back.ie_ir_ver_2.emitter import soft_get, xml_shape, serialize_runtime_info from openvino...
StarcoderdataPython
196314
<reponame>zhusonghe/Paddle # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
StarcoderdataPython
145568
""" faça um programa que peça os 3 lados de um triângulo. O programa deverá informar se os valores podem ser um triangulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isóceles ou escaleno.""" # três lados formam um triângulo quando a soma de quaisquer dois lados for maior que o terceiro # Eq...
StarcoderdataPython
41585
import argparse import datetime import sys import threading import time import matplotlib.pyplot as plt import numpy import yaml from .__about__ import __copyright__, __version__ from .main import ( cooldown, measure_temp, measure_core_frequency, measure_ambient_temperature, test, ) def _get_ver...
StarcoderdataPython
3238978
<reponame>renmcc/bk-PaaS # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not u...
StarcoderdataPython
1604434
<gh_stars>0 """ communicability_jsd.py -------------------------- Distance measure based on the Jensen-Shannon Divergence between the communicability sequence of two graphs as defined in: <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2018). Complex network comparison based on communicability sequence entropy. Ph...
StarcoderdataPython
2692
<reponame>plojyon/resolwe<gh_stars>10-100 """.. Ignore pydocstyle D400. ======= Resolwe ======= Open source enterprise dataflow engine in Django. """ from resolwe.__about__ import ( # noqa: F401 __author__, __copyright__, __email__, __license__, __summary__, __title__, __url__, __ver...
StarcoderdataPython
115507
from .playbooks import ListPlaybooks, PlaybookState, StartPlaybook from .api import API from .hosts import Hosts, HostMgmt, HostUpdate from .jobs import ListEvents, GetEvent
StarcoderdataPython
169255
# https://leetcode.com/problems/sliding-window-maximum/ # # algorithms # Hard (37.06%) # Total Accepted: 137,871 # Total Submissions: 372,038 # beats 79.21% of python submissions from collections import deque class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int...
StarcoderdataPython
4835392
import RPi.GPIO as GPIO import time LED = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(LED, GPIO.OUT) pwm = GPIO.PWM(LED, 100) pwm.start(0) for value in range(0, 1024): pwm.ChangeDutyCycle(value / 10.23) time.sleep(0.005) pwm.stop() GPIO.cleanup()
StarcoderdataPython
3388418
# -*- coding: utf-8 -*- """ @ author: <NAME> @ detail: Configuration file for Customer Agent (The Great-DR project) """ # UNIT DETAILS MRIDLIST = ['\x0a\xaf\x72\x05\x44\x04\xff\xa0\xed\x54\xc1\xab\x00\x00\x87\xb4', '\x29\x25\x00\x2e\x58\x6c\xf4\x62\x11\xba\x3d\xbb\x00\x00\x87\xb4', \ '\xcf\x36\x3b\x08\x5a\x91\xb7...
StarcoderdataPython
3210573
#! /usr/bin/env python # import os # temporarily redirect config directory to prevent matplotlib importing # testing that for writeable directory which results in sandbox error in # certain easy_install versions os.environ["MPLCONFIGDIR"] = "." DESCRIPTION = "Somecode Twitter Science and Research Platform" LONG_DESCRI...
StarcoderdataPython
148498
<gh_stars>10-100 from django import forms from .models import ImapServer, SmtpServer class ImapServerForm(forms.ModelForm): class Meta: model = ImapServer exclude = ['user'] widgets = { 'passwd': forms.PasswordInput(), } class SmtpServerForm(forms.ModelForm): class ...
StarcoderdataPython
11067
from btypes.big_endian import * cstring_sjis = CString('shift-jis') class Header(Struct): string_count = uint16 __padding__ = Padding(2) class Entry(Struct): string_hash = uint16 string_offset = uint16 def unsigned_to_signed_byte(b): return b - 0x100 if b & 0x80 else b def calculate_hash(s...
StarcoderdataPython
4815789
<reponame>tfn10/beecrowd def matriz_quadrada(): while True: n = int(input()) if n == 0: break elif n == 1: print(f'{n}'.rjust(3)) else: matriz = list() linha = list() for i in range(n): for j in range(n): ...
StarcoderdataPython
4818812
MASTER_KEY = "/master" MASTER_STATE = "OFF" WORKFLOW_KEY = "/workflow/batch:batch_imaging:0.1.1" WORKFLOW_VALUE = '{ "image": "workflow-batch-imaging:0.1.1" }'
StarcoderdataPython
3231881
from django.db import models from mptt.models import MPTTModel from mptt.managers import TreeManager class CustomTreeManager(TreeManager): pass class Category(MPTTModel): name = models.CharField(max_length=50) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') def _...
StarcoderdataPython
3347227
from ast import * from type_check_Pvar import check_type_equal from type_check_Pif import TypeCheckPif from utils import * class TypeCheckPwhile(TypeCheckPif): def type_check_stmts(self, ss, env): if len(ss) == 0: return match ss[0]: case While(test, body, []): test_t = self.type_check_e...
StarcoderdataPython
3327761
from __future__ import absolute_import, unicode_literals # following PEP 386 __version__ = "1.7.1a" from . import patches # NOQA
StarcoderdataPython
3396368
# encoding: utf-8 from django.db import models from django.utils.translation import ugettext_lazy as _ from core.models import EventMetaBase from core.utils import alias_property, is_within_period class EnrollmentEventMeta(EventMetaBase): """ An event has an instance of this class to indicate use of the e...
StarcoderdataPython
3226646
import collections class Aircraft(collections.namedtuple('Aircraft', ['jsbsim_id', 'flightgear_id', 'name', 'cruise_speed_kts'])): KTS_TO_M_PER_S = 0.51444 KTS_TO_FT_PER_S = 1.6878 def get_max_distance_m(self, episode_time_s: float) -> float: """...
StarcoderdataPython
4808715
<filename>infrastructure/dynamodb/table.py import pulumi import pulumi_aws as aws BOOKS_DYNAMODB_TABLE_NAME = "books" books_dynamodb_table = aws.dynamodb.Table( BOOKS_DYNAMODB_TABLE_NAME, attributes=[ aws.dynamodb.TableAttributeArgs( name="author", type="S", ), ...
StarcoderdataPython
137364
from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand import os from application.models import * from application.routes import app from application import db app.config.from_object(os.environ.get('SETTINGS')) print(app.config) migrate = Migrate(app, db) manager = Manager(app) ...
StarcoderdataPython
1632127
import matplotlib.pyplot as plot import matplotlib.dates as md from matplotlib.dates import date2num import datetime # from pylab import * from numpy import polyfit import numpy as np f = open("deviations.csv") values = [] timestamps = [] for (i, line) in enumerate(f): if i >= 1: lineArray = line.split(",...
StarcoderdataPython
53015
import numpy as np from io import BytesIO import wave import struct from dcase_models.util.gui import encode_audio #from .utils import save_model_weights,save_model_json, get_data_train, get_data_test #from .utils import init_model, evaluate_model, load_scaler, save, load #from .model import debugg_model, pr...
StarcoderdataPython
4820230
<gh_stars>0 """ integration test for arduino NOTE: requires the arduino to be plugged in """ import unittest from comp.comm import ADCSArduino class TestComm(unittest.TestCase): def setUp(self): self.ard = ADCSArduino(pr="/dev/ttyACM0") def tearDown(self): self.ard.close_arduino_port...
StarcoderdataPython
3225589
<gh_stars>100-1000 from django import forms from django.forms.widgets import RadioSelect, Textarea class QuestionForm(forms.Form): def __init__(self, question, *args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) choice_list = [x for x in question.get_answers_list()] self....
StarcoderdataPython
3346729
import sys input = sys.stdin.readline n = int(input()) point = [[0, 0, 0], [1, 0, 0]] for i in range(2, n+1): point.append([i, 0, 3]) for _ in range(n-1): u, v, w = map(int, input().split()) point[v][0] = u point[v][1] = w for i in range(1, n + 1): if (point[i][0] != i): if (point[i][1] ...
StarcoderdataPython
1676035
<reponame>petabyteboy/nix-update<gh_stars>0 import re import urllib.request import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element from typing import Optional from urllib.parse import ParseResult, urlparse from ..errors import VersionError from ..utils import extract_version, info def version_f...
StarcoderdataPython
3246209
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Library containing functions to access a remote test device.""" import logging import os import shutil import stat import time ...
StarcoderdataPython
1615736
<gh_stars>1-10 import builtins from dataclasses import dataclass from typing import List from datetime import datetime #TODO: Docs @dataclass class Lecture: start: datetime end: datetime subject: str group: str = None building: str = None room: str = None lecture_type: str = None lectu...
StarcoderdataPython
1659249
<reponame>mcara/stsci.tools<gh_stars>1-10 """ Learn basic capabilities here (e.g. can we display graphics?). This is meant to be fast and light, having no complicated dependencies, so that any module can fearlessly import this without adverse affects or performance concerns. $Id$ """ import os import sys descrip = "b...
StarcoderdataPython
3267764
# -*- coding: utf-8 -*- import urllib.error from . import gw2data from . import gw2cache def get_skins(api_key, recipes_only=False): gw = gw2data.Gw2Data() gw.api_key = api_key data = {} account_skins = None try: account_skins = gw.makeRequest('account/skins') if recipes_only: ...
StarcoderdataPython
96980
"""The controller for https://[PATH]/answer/""" from flask import Blueprint from flask import request from flask import jsonify from util.util import InvalidUsage from util.util import handle_invalid_usage from util.util import decode_user_token from config.config import config from models.model_operations.answer_oper...
StarcoderdataPython
3216614
<filename>homeassistant/components/sensor/alarmdecoder.py """ Support for AlarmDecoder Sensors (Shows Panel Display). For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.alarmdecoder/ """ import asyncio import logging from homeassistant.core import ca...
StarcoderdataPython
128877
<filename>random_customer/PersonFactorySeeds/Email.py<gh_stars>0 import string import random def random_string(length): return ''.join(random.choice(string.ascii_letters) for m in range(length)) email={} def getEmailAddress(firstName, lastName, isPrimary=True, emailType='Personal'): email['isPrimary'] = isPri...
StarcoderdataPython
1632755
class BaseMeta(type): def __new__(cls, name, bases, body): if name != 'Base': if not 'bar' in body: raise TypeError("Bad user class") return super().__new__(cls, name, bases, body) class Base(metaclass=BaseMeta): def foo(self): return self.bar() ...
StarcoderdataPython
3288201
#!/usr/bin/python import os ''' # Extract the features pos_path = "../data/dataset/pos" neg_path = "../data/dataset/neg" os.system("python ../object-detector/extract-features.py -p {} -n {}".format(pos_path, neg_path)) # Perform training pos_feat_path = "../data/features/pos" neg_feat_path = "../data/features/neg" o...
StarcoderdataPython
111561
import os from utils.data_utils import EMB_PATH, EMB_DICT, RAW_DICT, SRC_TGT class Configurations: def __init__(self, parser): # set common arguments self.use_gpu, self.gpu_idx, self.random_seed = parser.use_gpu, parser.gpu_idx, parser.random_seed self.train, self.restore_model, self.iobes...
StarcoderdataPython
1705053
import torch.nn as nn # type: ignore import torch # type: ignore import torch.nn.init # type: ignore import math # type: ignore from collections import OrderedDict #import models use_relu = False use_bn = True def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" global use_bn ...
StarcoderdataPython
1634259
# Generated by Django 2.2.11 on 2020-03-22 20:02 from django.db import migrations, models import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ('contentPages', '0007_delete_resourceitempreview'), ] operations = [ migrations.AlterField( model_nam...
StarcoderdataPython
1685078
import wataru.workflow.utils as wfutils from wataru.utils import get_hash class Model: def __init__(self, data, material_location, name, manager_param): self.data = data self.material_location = material_location self.name = name self.manager_param = manager_param def get_hash...
StarcoderdataPython
180169
# Heh, found this on a Usenet sig. reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))
StarcoderdataPython
1724182
from . import base from . import fields from .base import VKObject from .photo import Photo class Action(VKObject): type: base.String = fields.Field() member_id: base.Integer = fields.Field() text: base.String = fields.Field() email: base.String = fields.Field() photo: Photo = fields.Field(base=Ph...
StarcoderdataPython
3227358
# Copyright 2017 Cloudbase Solutions # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
StarcoderdataPython
3264944
from torch.distributions import Distribution Distribution = Distribution
StarcoderdataPython
4807412
<reponame>Roberto-Sartore/Python '''import math n = float(input('digite um valor')) print('O valor digitado foi {} e sua porção inteira é {}'.format(n, math.trunc(n)))''' n = float(input('digite um valor')) print('O valor digitado foi {} e sua porção inteira é {}'.format(n, int(n)))
StarcoderdataPython
165387
<gh_stars>0 import csv import logging import os import re from psycopg2 import connect class CsvLoader(object): """ Automatically create tables and load data from CSV files to your database. This loader creates tables based on CSV headers. Then data is loaded using COPY command. It works only with Po...
StarcoderdataPython
11751
#!/usr/bin/python3 """ Given a binary tree, we install cameras on the nodes of the tree. Each camera at a node can monitor its parent, itself, and its immediate children. Calculate the minimum number of cameras needed to monitor all nodes of the tree. Example 1: Input: [0,0,null,0,0] Output: 1 Explanation: One c...
StarcoderdataPython
16354
# The MIT License (MIT) # # Copyright (c) 2015 by Teradata # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modif...
StarcoderdataPython
154838
class TestSessOverallResults: def __init__(self): self._recall = -1. self._precision = -1. self._f_measure = -1. def __str__(self): rez = '\nRecall : ' + str(self.recall) rez += '\nPrecision : ' + str(self.precision) rez += '\nF-measure : ' + str...
StarcoderdataPython
80547
# Number of images used for training (rest goes for validation) train_size = 55000 # Image width and height of mnist width = 28 height = 28 # The total number of labels num_labels = 10 # The number of batches to prefetch when training on GPU num_prefetch = 5 # Number of neurons the weight matrices as specified in t...
StarcoderdataPython
3349865
import rasterio from rasterio.plot import show import geopandas as gpd import pandas as pd import json import shapely import pyproj from rasterio import mask from rasterio.warp import calculate_default_transform, reproject, Resampling, transform_geom import sys import os import time import re import zipfil...
StarcoderdataPython
3308905
from tkinter import * import random class Canvascontrol(): def __init__(self): self.width = 5 self.height = 5 self.minenum = 1 self.boxval = [10,0,0,0,0,10,0,0,0,0,10,0,0,0,0,10,0,0,0,0,0,0,0,0,0] self.minelist = [] self.clicklist = [] listA = [[1, 2, 3],[1,...
StarcoderdataPython
1702756
<gh_stars>100-1000 import theano import theano.tensor as T from lasagne.utils import unroll_scan from lasagne.layers import MergeLayer, helper, get_output from lasagne.random import get_rng from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams class StochsticRecurrentLayer(MergeLayer): def __init_...
StarcoderdataPython
183760
#!/usr/bin/env python3 """ Read GVF lines from stdin and write bed9+ lines to stdout """ import os,sys,re import argparse bed9Fields = ["chrom", "chromStart", "chromEnd", "name", "score", "strand", "thickStart", "thickEnd", "itemRgb"] # the following list of fields may not exist for every record in the input fi...
StarcoderdataPython
1657305
<reponame>needlehaystack/needlestack from typing import List, Tuple, Dict, Union import numpy as np from needlestack.apis import indices_pb2 from needlestack.apis import serializers from needlestack.exceptions import DeserializationError class BaseIndex(object): """Base class for index implementations. Defines ...
StarcoderdataPython
1639111
<gh_stars>0 #Pythons and Shells and Stars, Oh My! def mathsCheck(starCount, shellCount): count = 0 if starCount > shellCount: count = starCount - shellCount return count elif starCount < shellCount: count = starCount - shellCount return count elif starCount == shellCount: r...
StarcoderdataPython
158946
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import copy import glob import json import os import luigi import yaml import shutil import zipfile from servicecatalog_puppet import config, constants from servicecatalog_puppet.workflow import tasks fr...
StarcoderdataPython
1744571
<filename>CollimationToolKit/elements.py from pysixtrack.elements import Element from operator import sub, mul from CollimationToolKit.ScatterFunctions import default_scatter, test_strip_ions import numpy as np import types #------------------------------------------------------------------------------- #------- Pol...
StarcoderdataPython
1780400
import math, copy, random, time from cmu_112_graphics import * from pieces import * #Splash Screen Mode and Player vs Player standard mode class SplashScreenMode(Mode): def appStarted(self): #background image taken from online url self.backgroundURL = 'https://wallpaperaccess.com/full/1307...
StarcoderdataPython
1663049
<reponame>Wolemercy/leetcode # https://leetcode.com/problems/flip-equivalent-binary-trees/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def flipEquiv(se...
StarcoderdataPython
1718451
# Generated by Django 3.1.7 on 2021-02-27 19:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('envdatasystem', '0010_auto_20210227_1855'), ] operations = [ migrations.RemoveField( model_name...
StarcoderdataPython
3388295
<filename>src/gui/threads/CalculationThread.py import math from PyQt5.QtCore import QThread, pyqtSignal, QThreadPool, QMutex, QEventLoop, QTimer from src.core.apen_opt import ApproximateEntropy from src.core.cordim import CorDim from src.core.fracdim import FracDim from src.core.permen import PermutationEntropy from ...
StarcoderdataPython
147175
<gh_stars>0 import logging import random import unittest import mock from qgis.core import ( QgsCoordinateReferenceSystem, QgsFeature, QgsField, QgsGeometry, QgsVectorFileWriter, QgsVectorLayer, ) from qgis.PyQt.QtCore import QVariant from catatom2osm import config from catatom2osm.app import ...
StarcoderdataPython
1789445
import turtle import random ເຕົ່າ = turtle.Turtle() ເຕົ່າ.shape('turtle') color = ['red','blue','green','purple','orange','pink'] ເຕົ່າ.speed(2) for i in range(36): i = random.choice(color) ເຕົ່າ.color(i) ເຕົ່າ.forward(100) ເຕົ່າ.backward(100) ເຕົ່າ.left(10) for UncleMedia in range(1,30): ...
StarcoderdataPython
3320394
from wiki_440_version_helper.wiki_440_version_helper import Version_Helper from unittest import TestCase class Version_Helper_Test_Case(TestCase): file_path_one = '/Users/dustingulley/PycharmProjects/wiki_440_version_helper/tests/test_files/test_file_v1.md' file_path_two = '/Users/dustingulley/PycharmProjects...
StarcoderdataPython
3344709
<reponame>yaoyao-liu/POD-AANets<gh_stars>1-10 import numpy as np import torch from torch import nn from torch.nn import functional as F def binarize_and_smooth_labels(T, nb_classes, smoothing_const=0.1): import sklearn.preprocessing T = T.cpu().numpy() T = sklearn.preprocessing.label_binarize(T, classes=r...
StarcoderdataPython
196085
# -*- coding: utf-8 -*- # Copyright (C) 2014-2016 <NAME> <<EMAIL>> # Copyright (C) 2014-2016 <NAME> <<EMAIL>> # Copyright (C) 2014-2016 <NAME> <<EMAIL>> # Copyright (C) 2014-2016 <NAME> <<EMAIL>> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public...
StarcoderdataPython
22953
# Copyright 2014-2015 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. class mockData: """dictionary of mocking data for the mocking tests""" # dictionary to hold the mock data _data={} # function to add mock data to the _mock_data dictionary def _add(se...
StarcoderdataPython
130989
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 17 09:52:39 2018 @author: saintlyvi """ import pandas as pd import os from .support import results_dir def joinResults(searchterm): mod = pd.DataFrame() p = os.path.join(results_dir,'classification_results') for file in os.listdir(p):...
StarcoderdataPython
3391465
<filename>src/rgt/viz/projection_test.py # Python Libraries from __future__ import print_function from __future__ import division import matplotlib.pyplot as plt import matplotlib.ticker as mtick import numpy # Local Libraries # Distal Libraries from ..Util import Html from ..CoverageSet import * from ..ExperimentalMa...
StarcoderdataPython
1791581
from collections import deque from itertools import chain from operator import attrgetter # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[L...
StarcoderdataPython
11277
from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_all_tables(): db.create_all() def initialize_db(app: Flask): db.init_app(app) db.app = app from investing_algorithm_framework.core.models.order_status import OrderStatus from investing_algorithm_framework.core...
StarcoderdataPython
1651816
<filename>templates/separation_forces.py import numpy as np from scipy import constants import matplotlib.pyplot as plt import matplotlib as mpl import meep import meep_ext import pinboard job = pinboard.pinboard() ### transformation optics nb = 1.33 scale = nb nm = 1e-9*scale um = 1e-6*scale ### geometry radius = 7...
StarcoderdataPython
3396719
<filename>supports/pyload/src/pyload/plugins/downloaders/XHamsterCom.py # -*- coding: utf-8 -*- import json import re from ..base.downloader import BaseDownloader def quality_fallback(desired, available): result = available.get(desired, None) if result is None: if desired == "720p": retur...
StarcoderdataPython
188275
import os import django from django.test import TestCase from django.test.utils import setup_test_environment, teardown_test_environment from pytest_django.compat import setup_databases, teardown_databases os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() # Run with -D RESETDB=1 t...
StarcoderdataPython
3326154
<gh_stars>1-10 """ 07.12.2020 - <NAME> """ # !Tipo str que é string print('Isso é uma "String" (str).') # Metodo "\" caracter de escape, não fica bonito. print('Isso é uma \'string\' (str).') # Metodo "\n" quebra de linha print('Ola linha 1 \nOla Linha 2') # Metodo para o IDE não ler o codigo dentro do Print (...
StarcoderdataPython
3201040
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import dataclasses import glob import json import logging import os import shutil import site import subprocess import sys from dataclasses...
StarcoderdataPython
4817587
import sys import pygame from pygame.locals import * import pymunk from numpy import * def add_ball(space): mass = 1 radius = 14 moment = pymunk.moment_for_circle(mass, 0, radius) body = pymunk.Body(mass, moment) x = random.randint(15, 585) body.position = x, 550 shape = pymunk.Circle(body,...
StarcoderdataPython
3232576
<reponame>JJorgeDSIC/ShellMatrixExampleSLEPc4py import sys, slepc4py slepc4py.init(sys.argv) from petsc4py import PETSc from slepc4py import SLEPc import numpy as np Print = PETSc.Sys.Print class ShellMatrix(object): def __init__(self, m, n, KL11, KL21, KL22, L21, L22, M11, M12): self.m, self.n = m, n ...
StarcoderdataPython
111782
import json import pytest from plenum.common.request import Request from plenum.common.constants import AML from plenum.common.exceptions import InvalidClientRequest def test_taa_acceptance_static_validation(write_manager, taa_aml_request): taa_aml_request = json.loads(taa_aml_request) taa_aml_request['oper...
StarcoderdataPython
612
<gh_stars>0 from rest_framework import serializers from posts.models import Post class PostCreateUpdateSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ #'id', 'title', #'slug', 'content', 'publish', ] ...
StarcoderdataPython
1681805
# terrascript/newrelic/__init__.py import terrascript class newrelic(terrascript.Provider): pass
StarcoderdataPython
9920
import os import json import gzip from copy import deepcopy, copy import numpy as np import csv import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader, RandomSampler from transformers.tokenization_utils import trim_batch class LabelSmoothingLoss(nn.Module)...
StarcoderdataPython
1794355
<filename>server.py import time from flask import Flask, request app = Flask(__name__) messages = [ {'username': 'jack', 'text': 'Hello', 'time': time.time()}, {'username': 'mary', 'text': 'Hi, jack', 'time': time.time()}, ] users = { # username: password 'jack': '<PASSWORD>', 'mary': '<PASSWORD>...
StarcoderdataPython
156029
<gh_stars>100-1000 #!/usr/bin/env python3 import pytest import time import os from pymetasploit3.msfrpc import * @pytest.fixture() def client(): client = MsfRpcClient('123', port=55552) yield client client.call(MsfRpcMethod.AuthLogout) @pytest.fixture() def meterpreter_sid(client): s = client.sessio...
StarcoderdataPython
1673737
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 <NAME> <<EMAIL>> # # Distributed under terms of the MIT license. from setuptools import setup, find_packages setup( name='lw12', version='0.9.2', description='Library to control the Lagute LW-12 WiFi LED controller.', ...
StarcoderdataPython
1616328
<gh_stars>0 class Health: def __init__(self, max_count: int = 500): self.max_count: int = max_count self.percentage: float = 1.00 self.average_reset: bool = False self.positive_count: int = 0 self.negative_count: int = 0 def __repr__(self): return self.__str__() ...
StarcoderdataPython
3255958
from django import forms class MailchimpSignUpForm(forms.Form): email = forms.EmailField(label='Email', max_length=256, required=True, widget=forms.EmailInput(attrs={'placeholder': '<EMAIL>'}))
StarcoderdataPython
1651480
# Copyright 2016 Netherlands eScience Center # # 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 t...
StarcoderdataPython
135471
def assert_raises(excClass, callableObj, *args, **kwargs): """ Like unittest.TestCase.assertRaises, but returns the exception. """ try: callableObj(*args, **kwargs) except excClass as e: return e else: if hasattr(excClass,'__name__'): excName = excClass.__name__ e...
StarcoderdataPython
1732259
<reponame>florimondmanca/deduce<gh_stars>1-10 import re from typing import ( Callable, Dict, Generic, Match, Optional, Pattern, Tuple, Type, Union, ) from .typevars import T, U, V, W # pylint: disable=unused-import __all__ = ( "Converter", "Filter", "Transform", "E...
StarcoderdataPython
3284995
<reponame>jonhue/propose<gh_stars>1-10 from .binary import Binary class Implication(Binary): def __str__(self): return '(' + str(self.left) + ' → ' + str(self.right) + ')' def to_string(self, formulas, offset = 0): left = self.left.to_string(formulas, offset + 1) formulas.update({(offs...
StarcoderdataPython
113874
<reponame>AugustinMascarelli/survol #!/usr/bin/env python """ Windows local groups """ from __future__ import generators import lib_util import lib_uris import lib_common from lib_properties import pc import win32net import win32security from sources_types import Win32_Group as survol_Win32_Group from sources_types ...
StarcoderdataPython
3324287
<filename>analysis/event_study_analysis.py import numpy as np import pandas as pd from datetime import date as Date from datetime import timedelta from collections.abc import Iterable from scipy.stats import ttest_ind, ttest_1samp, wilcoxon from statsmodels.stats.proportion import proportions_ztest from statsmodels.s...
StarcoderdataPython
3295867
<gh_stars>0 import numpy as np import matplotlib.pyplot as plt import time from scipy.special import erf """ --------------- Statistics --------------- """ def moments(x,y): mean = np.sum(x*y)/np.sum(y) variance = np.sum( (x-mean)**2*y )/y.sum() sigma = np.sqrt(variance) skew = np.sum( (x-mean)**3*y ) ...
StarcoderdataPython