id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1670547 | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import time
import webbrowser
caffe_root = './'
import sys
sys.path.insert(0, caffe_root + 'python')
# 0 - debug
# 1 - info (still a LOT of outputs)
# 2 - warnings
# 3 - errors
import os
os.environ['GLOG_minloglevel'] = '0'
import caffe
net = ... | StarcoderdataPython |
3354346 | <gh_stars>0
# -*- coding: utf-8 -*-
"""Top-level package for cards."""
__version__ = '0.2.4'
from .api import * # noqa
| StarcoderdataPython |
1710090 | import unittest
from bubblesort import bubblesort
class TwoQueens(unittest.TestCase):
def test_bubblesort(self):
testcase = [1,3,8,2,9,2,5,6]
expected = [1,2,2,3,5,6,8,9]
self.assertEqual(bubblesort(testcase), expected)
if __name__ == '__main__':
unittest.main() | StarcoderdataPython |
55824 | from .video import VideoEntity
ENTITY_CLASSES = [VideoEntity]
ENTITY_TYPE_CHOICES = [
(VideoEntity.name, 'Video'),
]
ENTITY_TYPE_NAME_TO_CLASS = {
k.name: k for k in ENTITY_CLASSES
}
| StarcoderdataPython |
3331689 | import torch
import torch.nn as nn
from einops import rearrange, repeat
from ...common.base_model import BaseClassificationModel
from ...decoder.mlp import MLPDecoder
from ...encoder.embedding import LinearVideoEmbedding, PosEmbedding, TubeletEmbedding
from ...encoder.vanilla import VanillaEncoder
from ...encoder.vivi... | StarcoderdataPython |
3344762 | <reponame>Jakobis/OrderedSequences
from datastructures import AutoLoad
k = [i for i in range(10 ** 8)]
l = AutoLoad.AutoLoad(k)
print(l.size()) | StarcoderdataPython |
1681772 | <filename>.venv/lib/python3.8/site-packages/findatapy/market/indices/indicesfx.py<gh_stars>0
__author__ = 'saeedamen' # <NAME>
#
# Copyright 2016 Cuemacro
#
# 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 o... | StarcoderdataPython |
3340846 | <gh_stars>0
#!/usr/bin/env python3
"""@@@
Main Module: SettingsPacket.py
Classes: InputSettings
Author: <NAME>
creation date: 190829
last update: 200603 (various updates, minor bug fixes)
version: 0.0
Purpose:
Works as a packet of default settings for class FreeEnergy and
BranchEntropy.
... | StarcoderdataPython |
22658 | from random import randint
s = t = ma = 0
m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0, 3):
for c in range(0, 3):
m[l][c] = randint(0, 100)
print('-='*15)
for l in range(0, 3):
t += m[l][2]
for c in range(0, 3):
print(f'[{m[l][c]:^5}]', end='')
if m[l][c] % 2 == 0:
... | StarcoderdataPython |
71158 | <reponame>sriiora/tcf<filename>examples/test_dump_kws_one_target.py
#! /usr/bin/python3
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
#
# pylint: disable = missing-docstring
"""Testcase using one target
-------------------------
Note the data offered for the target is a superse of th... | StarcoderdataPython |
1603242 | import pygame
from pygame.locals import *
import time
import random
import numpy as np
import player
import food
class Agaria:
def __init__(self, rendering = True):
self.agents: [player.Player] = []
self.foods: [food.Food] = []
self.player_lastID = 0
self.rendering = rendering
... | StarcoderdataPython |
1759871 | <filename>mp4box/parsing/urn.py
from mp4box.box import DataEntryUrnBox
def parse_urn(reader, my_size):
box = DataEntryUrnBox(my_size)
return box
| StarcoderdataPython |
161108 | # -*- coding: utf-8 -*-
"""
ABSTRACT LOGGER
"""
# %% LIBRARY IMPORT
import abc
# %% FILE IMPORT
# %% CLASSES
class AbstractLogger(metaclass = abc.ABCMeta):
""" Abstract class for Loggers """
@abc.abstractmethod
def __init__(self):
pass
@abc.abstractmethod
def debug(self):
... | StarcoderdataPython |
58045 | #!/usr/bin/env python3
import argparse
import csv
from logging import error, warning
import requests
import urllib3
import act
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def parseargs():
""" Parse arguments """
parser = argparse.ArgumentParser(
description='Get Threat Acto... | StarcoderdataPython |
3338156 | # ---------------------------------------------------------------------
# Vendor: Enterasys
# OS: EOS
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
#... | StarcoderdataPython |
1604698 | <reponame>DhananjayMukhedkar/feature-store-api
#
# Copyright 2022 Logical Clocks AB
#
# 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.... | StarcoderdataPython |
3245564 | """
O(n)
"""
from ds.linkedList.linkedlist import LinkedList
def find_middle_node_linkedlist(l):
node = l.get_first()
single = double = node
while single.next_node is not None and double.next_node is not None:
single = single.next_node
double = double.next_node.next_node
if doubl... | StarcoderdataPython |
143694 | from dateutil.relativedelta import *
from eventtools.models import Rule
from eventtools_testapp.models import *
from eventtools.utils.dateranges import *
from datetime import datetime, date, timedelta
def fixture(obj):
obj.gallery = ExampleVenue.objects.create(name="Gallery A", slug="gallery-A")
obj.auditorium... | StarcoderdataPython |
3359747 | """
firmware
========
Provides a device firmware revision, which can be change by incoming "upgradeFirmware" events,
and rolled-back to factory firmware by incoming "factoryReset" events.
Configurable parameters::
{
}
Device properties created::
{
"firmware" : The current firmware of the device
... | StarcoderdataPython |
65142 | import torch
import unittest
import numpy as np
from torch.autograd import Variable
from losses.svm import SmoothTop1SVM, SmoothTopkSVM, MaxTop1SVM, MaxTopkSVM
from losses.functional import Topk_Smooth_SVM
from tests.utils import assert_all_close, V
from tests.py_ref import svm_topk_smooth_py_1, svm_topk_smooth_py_2,\... | StarcoderdataPython |
3377825 | <filename>python/researchDev/Parse.py<gh_stars>100-1000
class Parse:
def Parse():
with open('C:\users\dryft\desktop\URLlist.txt','r') as infile:
data = infile.read()
testdata = "www.bit.ly"
my_list = data.splitlines()
for word in my_list:
... | StarcoderdataPython |
119168 | <reponame>py2ai/putBText
import pathlib
from setuptools import setup
# from distutils.core import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setup(
name="pyshine",
... | StarcoderdataPython |
3340341 | '''
Created on Apr 10, 2011
@author: <NAME> <<EMAIL>>
'''
import png
import sys
import csv
def png2rgb(file):
r=png.Reader(file);
img = r.asRGB()
print(file, img)
return img
pass
def rgb2png(img, file, depth=8):
f = open(file, 'wb')
pngWriter = png.Writer(img[0], img[1], bitdepth=depth, grey... | StarcoderdataPython |
3339225 | <reponame>nypzxy/detection_transformer<filename>dataset/FaceDataset.py
from pathlib import Path
import torch
from torch.utils.data import Dataset, DataLoader
import torchvision
from pycocotools import mask as coco_mask
import datasets.transforms as T
class FaceDataset(Dataset):
def __init__(self, img_folder, an... | StarcoderdataPython |
4805967 | import cv2
import base64
from fastapi import WebSocket, APIRouter
from fastapi.responses import HTMLResponse
from fastapi.websockets import WebSocketDisconnect
from starlette.websockets import WebSocketState
from logger import get_logger
from services.factories import video_reader
router = APIRouter()
logger = get_log... | StarcoderdataPython |
1659751 | import os
import numpy as np
import pandas as pd
import torch
from data_management import IPDataset
from operators import (
Fourier,
RadialMaskFunc,
TVAnalysisPeriodic,
noise_gaussian,
to_complex,
unprep_fft_channel,
)
from reconstruction_methods import admm_l1_rec_diag, grid_search
# ----- ... | StarcoderdataPython |
1676861 | <reponame>ethanlu/pazudora-solver
from pazudorasolver.piece import Fire, Wood, Water, Dark, Light, Heart, Poison, Jammer, Unknown
from pazudorasolver.board import Board
from pazudorasolver.heuristics.pruned_bfs import PrunedBfs
import pytest
@pytest.fixture(scope='module')
def weights():
return {Fire.symbol: 1.0... | StarcoderdataPython |
3329811 | """Main."""
import logging
import os
import sys
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from .interfaces.db import db_models
from .interfaces.db.database import engine
from .external_interfaces import user_router, record_router
db_models.Base.metadata.create_all(bind=engine)
a... | StarcoderdataPython |
3273879 | <reponame>avcopan/autofile<gh_stars>0
""" A script to wipe out all cscan directories
"""
import itertools
from autofile import fs
RUN_PFX = '/lcrc/project/PACC/AutoMech/data/run/'
SAVE_PFX = '/lcrc/project/PACC/AutoMech/data/save/'
for sca_fs in itertools.chain(
fs.iterate_managers(RUN_PFX, ['SPECIES', 'THEOR... | StarcoderdataPython |
3283982 | <filename>Python/Zelle/Chapter5_SequencesStringsListsFiles/ProgrammingExercises/3_ExamScoring/examScoring.py<gh_stars>0
# examScoring.py
# A program that accepts a quiz score as an input and prints out the
# corresponding grade.
# 90-100:A, 80-89:B, 70-79:C, 60-69:D, <60:F
def main():
print("Quiz scoring is a pro... | StarcoderdataPython |
1719258 | # Python modules
# Constants specific to pulse_funcs
class ApodizationFilterType(object):
NONE = 0
COSINE = 1
HAMMING = 2
class AnalyticType(object):
NONE = 0
GAUSSIAN = 1
SINC_GAUSSIAN = 2
HYPERBOLIC_SECANT = 3
class ProfileType(object):
NONE = 0
M_XY = 1
M_X_MINUS_Y =... | StarcoderdataPython |
1697332 | <filename>DataAugScripts/cosine_similarity.py
import datetime
from absl import logging
import numpy as np
import pandas as pd
def get_cosine_similarity(sents, embed):
# Reduce logging output.
logging.set_verbosity(logging.ERROR)
# with tf.Session() as session:
# session.run([tf.global_variables... | StarcoderdataPython |
1713272 | <gh_stars>0
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Step generator
import numpy as np
from numpy.linalg import norm
from scipy.io import savemat
import matplotlib.pyplot as plot
import struct
import UR5Class
import socket
import time
import sys
import csv
#import json
import Transformations as tf
import os
import t... | StarcoderdataPython |
1612014 | # Copyright 2018-2019 The glTF-Blender-IO 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 applicable law or ... | StarcoderdataPython |
3266936 | <gh_stars>0
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-07-24 07:21
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('smelltest', '0006_auto_20180118_0838'),
]
operations = [
migrations.Alt... | StarcoderdataPython |
47123 | from os import system
from requests import get
from pyfiglet import figlet_format
from colored import fore, back, style, attr
attr(0)
print(back.BLACK)
print(fore.BLUE_VIOLET + style.BOLD)
system("clear")
print(figlet_format("DIRETORY BRUTE\nBY MOLEEY", width=58, justify="center", font="smslant"))
site = input("Link ... | StarcoderdataPython |
3383812 | <gh_stars>1-10
# Copyright YukonTR 2015
from operator import itemgetter
class DeliveryManager(object):
''' Delivery Manager manages vehicle resources and their routes
'''
def __init__(self, env):
# simulation environment
self.env = env
self._vehicle_list = None
self.vindexe... | StarcoderdataPython |
1763399 | <filename>lib/ram/wiz/disk_choice/utils.py
import lsblk
def TryDevice(dev_path, size, subs):
dev_errs = []
dev_warn = []
dev = lsblk.GetBlockDevice(dev_path)
if dev.btype != 'disk':
dev_errs.append("Cannot operate on disks of type: %s." % dev.btype)
if dev.ro:
dev_errs.append("T... | StarcoderdataPython |
1615322 | <gh_stars>0
#Quiz 2
#Nombre: <NAME>
#Cedula: 8-840-2233
for i in range(4):
print("monto de la compra: ")
monto = int(input())
if monto >= 500:
descuento = monto * 0.30
total = monto - descuento
print ("el total es " + str(total))
if monto <500 and monto >=200:
descuento = monto * 0.20
total = mo... | StarcoderdataPython |
187558 | <filename>lib/googlecloudsdk/command_lib/compute/os_config/declarative.py
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. 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 Lice... | StarcoderdataPython |
3271716 | import io
import os
import re
import sys
import csv
import urllib
import itertools
from collections import defaultdict
from indra.databases import hgnc_client
hgnc_fam_url = ('ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/csv/'
'genefamily_db_tables/')
gene_fam_file = 'gene_has_family.csv'
family_fil... | StarcoderdataPython |
3271015 | <reponame>YuxinZou/mmclassification
# Copyright (c) OpenMMLab. All rights reserved.
import math
import torch
import torch.nn.functional as F
def timm_resize_pos_embed(posemb, posemb_new, num_tokens=1, gs_new=()):
"""Timm version pos embed resize function.
copied from https://github.com/rwightman/pytorch-ima... | StarcoderdataPython |
3245026 | <filename>gym_goal/envs/goal_env.py
"""
Robot Soccer Goal domain by <NAME> et al. [2016], Reinforcement Learning with Parameterized Actions
Based on code from https://github.com/WarwickMasson/aaai-goal
Author: <NAME>
June 2018
"""
import numpy as np
import math
import gym
import pygame
from gym import spaces, error
fr... | StarcoderdataPython |
3343019 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | StarcoderdataPython |
1641781 | class Game:
""" Represents main Game class"""
def __init__(self):
self.state = 'Ready'
self.score = 0
self.objects_found = []
self.keys = {}
self.messages = []
self.player = None
def play(self):
self.new_attribute = 1
| StarcoderdataPython |
1618408 | import time, os, requests, re, csv, time
from lxml import etree
from selenium import webdriver
img_folder = 'D:\\dataset_object_detect\\open_image_dataset\\train_00\\train_00'
img_files = list()
for root, dirs, files in os.walk(img_folder):
for name in files:
file_path = os.path.join(img_folder, name)
... | StarcoderdataPython |
104513 | # -*- coding: UTF-8 -*-
"""
Based on ``behave tutorial``
Feature: A Step uses a User-Defined Type as Step Parameter (tutorial10)
Scenario Outline: Calculator
Given I have a calculator
When I add "<x>" and "<y>"
Then the calculator returns "<sum>"
Examples: Add Numbers
| x | y | sum |
... | StarcoderdataPython |
3301482 | marks = []
sum = 0
for i in range(0, 3):
mark = eval(input("Enter marks in subject {}: ".format(i+1)))
marks.append(mark)
sum += mark
avg = sum/3
print(int(avg))
if avg >= 80:
print("Level 4, above agency-noramlized standards")
elif avg >=70:
print("Level 3, at agency-noramlized standards")
elif av... | StarcoderdataPython |
3264503 | from pylab import *
import skrf as rf
import pdb
c = 3e8
def create_sdrkits_ideal(skrf_f):
# create ideal cal kit
media = rf.media.Freespace(skrf_f)
sdrkit_open = media.line(42.35, 'ps', z0 = 50) ** media.open() # 42.35
sdrkit_short = media.line(26.91, 'ps', z0 = 50) ** media.short()
# TODO: add ... | StarcoderdataPython |
104543 | <reponame>wx-b/cockpit<gh_stars>100-1000
"""Base class for executing and hooking into a training loop to execute checks."""
from backpack import extend
from cockpit import Cockpit
from tests.utils.rand import restore_rng_state
class SimpleTestHarness:
"""Class for running a simple test loop with the Cockpit.
... | StarcoderdataPython |
1679591 | <reponame>srikanthallu/proteuslib
###############################################################################
# WaterTAP Copyright (c) 2021, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory, Oak Ridge National
# Laboratory, National Renewable Energy Laboratory, and Nation... | StarcoderdataPython |
4840242 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) with Amazon Simple Email Service
(Amazon SES) to manage email templates that contain replaceable tags.
"""
import logging
from pprint import pprint
im... | StarcoderdataPython |
1705836 | # (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
def get_rate(check, metric_name, modifiers, global_options):
"""
Send with the `AgentCheck.rate` method.
"""
rate_method = check.rate
def rate(metric, sample_data, runtime_data):
... | StarcoderdataPython |
1789273 | <filename>problems/days_between_two_dates.py
from datetime import date
first_date = date(2019, 10, 14)
second_date = date(2019, 9, 14)
diff = first_date - second_date
print(diff.days)
| StarcoderdataPython |
197134 | <reponame>NatsubiSogan/comp_library<filename>Python/data_structure/wavelet_matrix.py
from bit_vector import BitVector
# Wavelet Matrix
class WaveletMatrix:
def __init__(self, array: list, log: int = 32) -> None:
self.n = len(array)
self.mat = []
self.zs = []
self.log = log
for d in range(self.log)[::-1]:
... | StarcoderdataPython |
3298358 | <reponame>Puppet-Finland/puppet-trac
# -*- coding: utf-8 -*-
"""
License: BSD
(c) 2005-2008 ::: <NAME> (<EMAIL>)
(c) 2009 ::: www.CodeResort.com - BV Network AS (<EMAIL>)
"""
import os
from datetime import datetime
from trac.attachment import Attachment
from trac.core import *
from trac.mimeview import Context
... | StarcoderdataPython |
3369686 | import sqlite3
# Total number of characters
conn = sqlite3.connect('rpg_db.sqlite3')
cur = conn.cursor()
cur.execute('SELECT name FROM charactercreator_character')
all_rows = cur.fetchall()
print(f'The number of characters is {len(all_rows)}.')
# Number by class
classlist = ['cleric', 'fighter', 'mage', 'necromancer', ... | StarcoderdataPython |
1628969 | <reponame>TalHadad/yolov5_pytorch
#############################################################################################
# page 4: Feedforward neural network
#############################################################################################
######################################
# 1. Neural Networks
... | StarcoderdataPython |
1757556 | <gh_stars>1-10
#! /usr/bin/env python
from __future__ import generators
"""
Module difflib -- helpers for computing deltas between objects.
Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
Use SequenceMatcher to return list of the best "good enough" matches.
Function ndiff(a, b):
Return a d... | StarcoderdataPython |
1757726 | import os
from flask import Flask
from .extensions import login_manager, mongo
from .config import TestingConfig
def create_app(config=TestingConfig):
""" Flask application factory """
# Setup Flask and load app.config
app = Flask(__name__)
app.config.from_object(config)
try:
os.makedi... | StarcoderdataPython |
3263506 | import tempfile
import warnings
from pathlib import Path
import pandas as pd
import pytest
from gobbli.dataset.cmu_movie_summary import MovieSummaryDataset
from gobbli.dataset.newsgroups import NewsgroupsDataset
from gobbli.experiment.classification import (
ClassificationExperiment,
ClassificationExperimentR... | StarcoderdataPython |
4823025 | from __future__ import division
import numpy as np
from tf.transformations import quaternion_from_euler, euler_from_quaternion, random_quaternion
from msg_helpers import numpy_quat_pair_to_pose
from geometry_msgs.msg import Quaternion
'''
A file to assist with some math that is commonly used in robotics
Some ... | StarcoderdataPython |
24352 | <filename>tests/test_article.py
import unittest
from app.models import Article
class ArticleTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Article class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_article = A... | StarcoderdataPython |
63334 | #!/usr/bin/env python3
import sys
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class ImageGrabber:
def __init__(self):
self.bridge = CvBridge()
self.image_sub = rospy.Subscriber("main_camera/image_raw", Image, self.callback)
def ca... | StarcoderdataPython |
1784281 | from openpyxl import Workbook, load_workbook
from halo import Halo
import time
from datetime import date, timedelta, datetime
from copy import copy
class XCel:
def __init__(self, config):
p1 = time.time()
self.config = config
spin = Halo(text="Opening template file: {0}".format(self.config['... | StarcoderdataPython |
140553 | from django import forms
from apps.Testings.models import Phase
from .models import Argument, Source, Command
from django.utils.safestring import mark_safe
class ArgumentForm(forms.ModelForm):
class Meta:
model = Argument
fields = '__all__'
widgets = {
'command' : forms.HiddenI... | StarcoderdataPython |
59572 | # -*- coding: utf-8 -*-
""" make Classes and functions available via a simple import
Copyright 2017, <<EMAIL>>
See COPYRIGHT for details
"""
# first party
from simplecasper.api import (
CasperAPI,
get_casper_credentials
)
from simplecasper.util import (
SimpleHTTPJSON,
SWVersions,
to_file
)
__all_... | StarcoderdataPython |
1717490 | # 🚨 Don't change the code below 👇
year = int(input("Which year do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
#Test if the year is evenly divisible by 100
if year % 100 == 0:
#Tests if the year is evenly divisible by 400
if year % 400 == 0:
#The year is bot... | StarcoderdataPython |
18061 | # -*- coding: utf-8 -*-
import botocore.exceptions
import logging
import dockerfilegenerator.lib.constants as constants
import dockerfilegenerator.lib.exceptions as exceptions
import dockerfilegenerator.lib.versions as versions
import dockerfilegenerator.lib.jsonstore as jsonstore
import dockerfilegenerator.lib.s3sto... | StarcoderdataPython |
179698 | # 020 - O mesmo professor do desafio anterior quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia
#o nome dos quatro alunos e mostre a ordem sorteada:
import random
from random import shuffle
lista = []
for c in range(1,5):
nome = str(input(f'Digite o nome do aluno {c}: '))
lis... | StarcoderdataPython |
1616572 | # Linear Search Approach
def first_and_last(arr, target):
for i in range(len(arr)):
if arr[i] == target:
start = i
while i+ 1 < len(arr) and arr[i+1]== target:
i += 1
return [start, i]
return [-1, -1]
arr = [1,2,3,4,5,5,5,6,7]
target = 5
# T(n) = O(... | StarcoderdataPython |
3202648 | import numpy as np
from fitter import *
from scipy.constants import hbar
cons_w = 2*3.14*6.002e9
cons_ke = 2*3.14*0.017e6
cons_k = 2*3.14*1.4e6
cons_delta = 0
def Plin(p):
return 10.**(p/10.-3.)
def photons(power):
return Plin(power)/(hbar*cons_w)*(cons_ke/((cons_k/2)**2+cons_delta**2))
path = ... | StarcoderdataPython |
3219300 | <gh_stars>0
# © 2021 <NAME> (initOS GmbH)
# License Apache-2.0 (http://www.apache.org/licenses/).
import configparser
import os
import re
import sys
from contextlib import closing, contextmanager
import yaml
from . import base, utils
SubstituteRegex = re.compile(r"\$\{(?P<var>(\w|:)+)\}")
def load_config_argument... | StarcoderdataPython |
3259635 | <reponame>sunlightlabs/regulations-scraper
def all_aliases():
import itertools
from regs_common.util import get_db
db = get_db()
return itertools.chain.from_iterable(
itertools.imap(
lambda entity: [(alias, entity['_id']) for alias in entity.get('filtered_aliases', [])],
... | StarcoderdataPython |
4813178 | <reponame>bogdandm/attrs-api-client<filename>json_to_models/utils.py
import json
from functools import wraps
from typing import Callable, Optional, Set
class Index:
def __init__(self):
self.ch = 'A'
self.i = 1
def __call__(self, *args, **kwargs):
value = f'{self.i}{self.ch}'
c... | StarcoderdataPython |
3382476 | import torch
import torch.nn as nn
import torch.nn.functional as F
import pandas as pd
import numpy as np
import os
class Loss_Synonymy(nn.Module):
"""
This class contains a loss function that uses the sum of ReLu loss to make predictions for the encoded embeddings
in the synonym subspace. A lower and hi... | StarcoderdataPython |
1600319 | <filename>oTree/reffort/ajax.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^validate_transcription/$" ,
views.validate_transcription, name="validate_transcription")]
| StarcoderdataPython |
13935 | <reponame>tlh45342/polygon-pull
import datetime
import os
import pandas
from polygon.rest.client import RESTClient
def ts_to_datetime(ts) -> str:
return datetime.datetime.fromtimestamp(ts / 1000.0).strftime('%Y-%m-%d %H:%M')
def pull_day(Symbol, from_):
POLYGON_API_KEY = os.environ.get('POLYGON_A... | StarcoderdataPython |
1620129 | #!/usr/bin/env python
from scipy.stats import poisson
import pickle
from trip_rules import *
from trip_definitions import *
rule_funcs = [rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8]
def rule_likelihood(test_data, rule_funcs, core_params):
(values, rains) = test_data
res = 0
num_regions = len(... | StarcoderdataPython |
1699415 | <gh_stars>1-10
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QLineEdit, QFrame, QPushButton, QTableWidget, QHeaderView, QMenu, \
QInputDialog, QTableWidgetItem, QSizePolicy, QMessageBox, QSpacerItem
from PyQt5.QtCore import Qt
from .filter import Filter
from lxml import etree as ET
import re, os
from depend... | StarcoderdataPython |
163284 | import requests
from lxml import html
class GithubRepo:
name = ''
author = ''
summary = ''
tag_list = []
license = ''
lastUpdateTime = ''
language = ''
star_num = 0
def tostring(self):
print(self.__dict__)
keyWorld = 'swift'
language = 'Swift'
URL = ('https://github.com... | StarcoderdataPython |
90455 | <filename>stegbench/executor/embeddor_cmds.py
from collections import defaultdict
from os.path import abspath, join
import stegbench.executor.runner as runner
import stegbench.utils.filesystem as fs
import stegbench.utils.lookup as lookup
def replace(cmd: str, replacements):
for replacement_key in replacements:
... | StarcoderdataPython |
3306795 | <filename>src/predict.py
import cv2
import numpy as np
import pandas as pd
from skimage import io
def prediction(test, model, model_seg):
"""
Pipeline to connect the classification and segmentation model.
All the preprocessing and detection takes place in this function.
The classification model first ... | StarcoderdataPython |
3396503 | # 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.
# libcloud.org licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not... | StarcoderdataPython |
3255174 | import versioneer
from setuptools import find_packages, setup
setup(
name="fastscore",
description="FastScore SDK",
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
packages=find_packages(),
use_2to3=True,
author="Open Data Group",
author_email="<EMAIL>",
instal... | StarcoderdataPython |
3226060 | <filename>RestPy/SampleScripts/evpnNgpf2.py
"""
Evpn_NGPF.py:
Tested with two back-2-back Ixia ports and put variables for the VTEP scale (L2/L3 VNI, number of VTEPs, ETC)
- Connect to the API server
- Assign ports:
- If variable forceTakePortOwnership is True, take over the ports if they're owned by... | StarcoderdataPython |
3287231 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""
Created on : Tue Apr 17 22:44:31 2018
@author : Sourabh
"""
# %%
class HttpException(Exception):
def __init__(self, message, code):
super().__init__(message)
self.errorCode = code
| StarcoderdataPython |
1637269 | # Make a program that reads any angle and shows on the screen the value of the sine, cosine and tangent of that angle
from math import radians, sin, cos, tan
a = float(input('Enter a angle: '))
s = sin(radians(a))
c = cos(radians(a))
t = tan(radians(a))
print('The SINE of this angle is {:.2f} \nThe COSINE of this ang... | StarcoderdataPython |
1748993 | #!/usr/bin/env python
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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
... | StarcoderdataPython |
4198 | <gh_stars>1000+
"""Implementation of Rule L024."""
from sqlfluff.core.rules.doc_decorators import document_fix_compatible
from sqlfluff.rules.L023 import Rule_L023
@document_fix_compatible
class Rule_L024(Rule_L023):
"""Single whitespace expected after USING in JOIN clause.
| **Anti-pattern**
.. code-... | StarcoderdataPython |
152777 | import os
from nmapy.classification import *
if __name__ == "__main__":
in_image = "/mnt/GATES/UserDirs/4ja/data/johannesburg_cw_wv2_000024000_000078000_00114.tif"
out = None
block = "30 meters"
model_dir = "/mnt/GATES/UserDirs/4ja/models"
classifier_file = os.path.join(model_dir,... | StarcoderdataPython |
3314220 | <reponame>isaacmorneau/3-CPO<filename>c3po/output.py
from __future__ import print_function
verbose = True
#so you can globally disable all prints
def vprint(*args, **kwargs):
if verbose:
print(*args, **kwargs)
| StarcoderdataPython |
1664575 | entity_uri = '/ngsi-ld/v1/entities/'
header={'content-type': 'application/ld+json', 'Accept-Charset': 'UTF-8'}
subscribe_uri='/ngsi10/subscribeContext'
context_url="https://forge.etsi.org/gitlab/NGSI-LD/NGSI-LD/raw/master/coreContext/ngsi-ld-core-context.jsonld"
brand_url="http://example.org/"
id_value="urn:ngsi-ld:"
u... | StarcoderdataPython |
1797173 | '''
Module containing the online game class called mayhem
Written by <NAME>
'''
import pygame as pg
import numpy as np
import pickle
import time
import itertools
from multiprocessing import Pipe, Process
from importlib import reload
import user_settings as cng
from states import state_config as state_c... | StarcoderdataPython |
3294514 | import filecmp
import os
import tempfile
import unittest
import sbol3
import tyto
from sbol_utilities.component import contained_components, contains, add_feature, add_interaction, constitutive, \
regulate, order, in_role, all_in_role, ensure_singleton_feature
from sbol_utilities.component import dna_component_wi... | StarcoderdataPython |
3301864 | <reponame>gyeongmoon/CNN-DM<filename>model/memoryModel.py
import time
import torch
import torch.nn as nn
from model import utils
from model import LwFLoss
from torchvision import models
from torch.autograd import Variable
############################################################
# Defining the CNN with Development... | StarcoderdataPython |
1764086 | # vim:fileencoding=utf-8:noet
""" python function """
# Copyright (c) 2010 - 2019, © Badassops LLC / <NAME>
# 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... | StarcoderdataPython |
3244387 | <reponame>bobo-care/bobo-care<gh_stars>0
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Baby(models.Model):
name = models.CharField(max_length=255)
born = models.DateField()
class Meta:
verbose_name_plural = "babies"
def __str__(se... | StarcoderdataPython |
3310124 | <filename>firmwares/models.py
# Copyright 2016 <NAME>. 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 requir... | StarcoderdataPython |
96554 | from Button import Button
import pygame
class SmallButton(Button):
def __init__(self, position, value, label):
Button.__init__(self, position, value, label)
self.unPressedImage = pygame.transform.smoothscale(self.unPressedImage, (104, 32))
self.pressedImage = pygame.transform.smoothscale(s... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.