id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1639987 | import pytest
from ciphers import vignere
def test_encrypt():
plaintext ="ATTACKATDAWN"
key = "LEMON"
assert vignere.encrypt(plaintext, key) == "LXFOPVEFRNHR"
def test_decrypt():
ciphertext ="LXFOPVEFRNHR"
key = "LEMON"
assert vignere.decrypt(ciphertext, key) == "ATTACKATDAWN"
def test_... | StarcoderdataPython |
1776891 | #!/usr/bin/env python
import os
import sys
import unittest
from random import randint
from concurrent.futures import ProcessPoolExecutor, as_completed
pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # noqa
sys.path.insert(0, pkg_root) # noqa
from getm.concurrent import SharedBufferArray
... | StarcoderdataPython |
1696304 | <gh_stars>0
import torch
import cv2
def time_synchronized():
torch.cuda.synchronize() if torch.cuda.is_available() else None
return time.time()
class VideoCamera(object):
def __init__(self):
global res;
self.video = cv2.VideoCapture(sys.argv[1])
res = f"{int(self.video.get(cv2.CAP_... | StarcoderdataPython |
3205166 | # -*- coding: UTF-8 -*-
import M2Crypto
from Crypto.PublicKey import RSA
import base64
import sys
#私钥加密
def pri_encrypt(msg, file_name):
rsa_pri = M2Crypto.RSA.load_key(file_name)
output = ''
while msg:
input = msg[:117]
msg = msg[117:]
out = rsa_pri.private_encrypt(input, M2Cry... | StarcoderdataPython |
3328037 | <gh_stars>0
import json
from data_visualysis import DataModeler
def main():
filename = 'covid_turkey.json'
with open(filename, 'r') as f_obj:
contents = json.load(f_obj)
daily_results = []
tests_list = []
cases_list = []
deaths_list = []
healed_list = []
result_lists = [tests_list, cases_list... | StarcoderdataPython |
3329677 | # -*- coding: utf-8 -*-
__version__ = "2.11.2" # version bump; deviates from divio/master which is at 1.11.0
| StarcoderdataPython |
179193 | #
# Explicit model for potential drop across a lithium metal electrode
#
from .base_ohm import BaseModel
class LithiumMetalExplicit(BaseModel):
"""Explicit model for potential drop across a lithium metal electrode.
Parameters
----------
param : parameter class
The parameters to use for this s... | StarcoderdataPython |
3359381 | <gh_stars>100-1000
""" Implementação do algoritmo passeio do cavalo """
def aceitavel(x, y):
"""
Aceitavel se estiver dentro do tabuleiro e a casa ainda nao tiver sido
visitada
Retorna True ou False
"""
if (
x >= 0
and x <= num - 1
and y >= 0
and y <= num - 1
... | StarcoderdataPython |
3234942 | from django.dispatch import receiver
from django.urls import resolve, reverse
from django.utils.translation import ugettext_lazy as _
from pretix.presale.signals import sass_postamble
from pretix.control.signals import nav_event_settings
@receiver(nav_event_settings, dispatch_uid="custom_css_settings")
def custom_css... | StarcoderdataPython |
3381873 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-09 20:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('showings', '0005_auto_20170809_1859'),
]
operations = [
migrations.AddField... | StarcoderdataPython |
4822179 | """Day 4 challenge"""
# Built-in
import re
# Personal
from _shared import read_input
# --------------------------------------------------------------------------------
# > Helpers
# --------------------------------------------------------------------------------
class PassportForm:
LINE_REGEX = r"([a-z]{3}):([^... | StarcoderdataPython |
1657015 | from logger import log_info
from Classes.Metadata import Metadata
from Classes.PortablePacket import PortablePacket
from timeit import default_timer as timer
from extension import write, write_debug
from colorama import Fore
from zip_utils import *
import os
import sys
home = os.path.expanduser('~')
def install_port... | StarcoderdataPython |
3386972 | <reponame>TroyWilliams3687/fuel_tracker
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# -----------
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 <NAME>
# uuid: 81ef08b8-0503-11ec-b7e5-a9913e95621d
# author: <NAME>
# email: <EMAIL>
# date: 2021-08-24
# -----------
"""
Perform bulk operations on the databa... | StarcoderdataPython |
1657875 | <filename>src/MidiConnector.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# JMMidiBassPedalController v3.0
# File: src/MidiConnector.py
# By: <NAME> <<EMAIL>> @ 28.10.2020
# This project is licensed under the MIT License. Please see the LICENSE.md file
# on the main folder of this code. An online version can be ... | StarcoderdataPython |
1683768 | import os
import sys
import re
import matplotlib as mpl
from jupyter_core.paths import jupyter_config_dir
# path to install (~/.jupyter/custom/)
jupyter_custom = os.path.join(jupyter_config_dir(), 'custom')
# path to local site-packages/jupyterthemes
package_dir = os.path.dirname(os.path.realpath(__file__))
# theme co... | StarcoderdataPython |
3338348 | <reponame>abal2051/Amwal
from amwal.cache import JsonCache, cached
from amwal.extract import RawExtractor
from amwal.log import logger
class Engine:
def __init__(self, downloader):
self.downloader = downloader
@cached([JsonCache()])
def daily_bulletin(self, date, ):
# should validate date... | StarcoderdataPython |
137273 | import os
import tempfile
import mock
import numpy as np
from yt.testing import assert_equal, fake_random_ds
from yt.units.unit_object import Unit
def setup():
from yt.config import ytcfg
ytcfg["yt", "__withintesting"] = "True"
def teardown_func(fns):
for fn in fns:
try:
os.remove... | StarcoderdataPython |
3354103 | <reponame>thevirtualbuddy/Python-freecodecamp
class Category:
#Constructor
def __init__(self, name):
self.name= name
self.ledger=list()
#Deposit method
def deposit(self, amount, description=""):
# We append an object to the ledger list
# in the form of
# {"amo... | StarcoderdataPython |
150619 |
########################################################################
# written by : <NAME>, <NAME>, CS, #
# Im<NAME> AlFaisal University #
#----------------------------------------------------------------------#
# #
# This interface is the user main menu where the users can ... | StarcoderdataPython |
58746 | # Copyright (c) 2017-2018 Wind River Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | StarcoderdataPython |
4834545 | <reponame>wedwardbeck/ibase
from django.urls import path
from itembase.core.views.staffing_views import ProjectManagerListView, TeamLeadListView, TeamListView, \
TeamMemberCreateView, TeamMemberClientCreateView, TeamMemberDetailView, TeamMemberUpdateView
app_name = "staff"
urlpatterns = [
# Client URL Patter... | StarcoderdataPython |
44904 | <reponame>boomsbloom/dtm-fmri
'''
==============================================
====== DYNAMIC TOPIC MODELING FOR FMRI =======
==============================================
Assumes subject timeseries have been
processed through:
1) binning
2) text creation (corr matrix as docs)
===========... | StarcoderdataPython |
3286357 | <filename>goose.py
# SPDX-FileCopyrightText: 2021 <NAME>
#
# SPDX-License-Identifier: MIT
# A simple example of how to set up a keymap and HID keyboard on Keybow 2040.
# You'll need to connect Keybow 2040 to a computer, as you would with a regular
# USB keyboard.
# Drop the keybow2040.py file into your `lib` folder ... | StarcoderdataPython |
3220357 | import os
if __name__ == '__main__':
amplxe_cl_path = '/opt/intel/vtune_amplifier/bin64/amplxe-cl'
# dataset and parameters
dataset_dir_path = '/home/yche/GitRepos/ScanOptimizing/dataset/'
dataset_path_lst = map(lambda file_name: dataset_dir_path + file_name,
['snap_orkut', '... | StarcoderdataPython |
3205030 | <filename>ae_service/main.py
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | StarcoderdataPython |
3312618 | import gym
import time
import os
import sys
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from gym import wrappers
from gym.wrappers.monitoring import stats_recorder, video_recorder
from datetime import datetime
import tensorflow as tf
import random
from sklearn.preprocessin... | StarcoderdataPython |
1716406 | import cloudinary
import cloudinary.uploader
import cloudinary.api
cloudinary.config(
cloud_name="grupo-dasa",
api_key="677559119568421",
api_secret="<KEY>"
)
def create_file(file):
return cloudinary.uploader.upload(file)
| StarcoderdataPython |
1647121 | <filename>gs/profile/status/change/interfaces.py
# -*- coding: utf-8 -*-
############################################################################
#
# Copyright © 2015 OnlineGroups.net and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (Z... | StarcoderdataPython |
116971 | <filename>tests/test_annotation.py
# OBSS SAHI Tool
# Code written by <NAME>, 2020.
import unittest
class TestAnnotation(unittest.TestCase):
def test_bounding_box(self):
from sahi.annotation import BoundingBox
bbox_minmax = [30, 30, 100, 150]
shift_amount = [50, 40]
bbox = Bound... | StarcoderdataPython |
3344349 | from threading import RLock
from typing import Optional
from rx.core import typing
from rx.core.typing import Disposable
class SerialDisposable(Disposable):
"""Represents a disposable resource whose underlying disposable
resource can be replaced by another disposable resource, causing
automatic disposal ... | StarcoderdataPython |
1784772 | from __future__ import annotations
from ...distributed.options import Options
from ...distributed.unit import Unit
from ...domain.sensor_type import SensorType
from ...domain.sensor_type_repository import SensorTypeRepository
from ...domain.options import Options as DomainOptions
from ..base_command import BaseCommand... | StarcoderdataPython |
3287856 | """
https://github.com/FrederikSchorr/sign-language
Train a pre-trained I3D convolutional network to classify videos
"""
import os
import glob
import time
import sys
import numpy as np
import pandas as pd
import keras
from keras import backend as K
from datagenerator import VideoClasses, FramesGenerator
from model... | StarcoderdataPython |
1700707 | <gh_stars>1-10
from polecat.project import Project as BaseProject
from .models import * # noqa
class Project(BaseProject):
pass
| StarcoderdataPython |
156376 | from __future__ import print_function, absolute_import
from .video_datasets import *
| StarcoderdataPython |
3304322 | #!/usr/bin/python3
from ast import parse
from types import new_class
from typing import DefaultDict
import config #copy config-example.py to config.py and set values
from datetime import datetime
import paho.mqtt.client as mqtt
from smip import graphql
import requests
import uuid
import argparse
import jso... | StarcoderdataPython |
3262596 | #! /bin/python3
import json
import pandas
import numpy
class mark_mandatory:
def __init__(self):
pass
# This class at the 'identifier' to the name of the mandatory fields,
def mark_as_mandatory(self, names_list, mandatory_list, mand_ident, identifier):
print('#-1')
print(numpy.n... | StarcoderdataPython |
1709687 | # Copyright 2021 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | StarcoderdataPython |
4827598 | # windows.py
import raylibpy as rl
from ctypes import byref
def main():
rl.init_window(rl.get_screen_width(), rl.get_screen_height(), "raylib [core] example - basic window")
rl.toggle_fullscreen()
camera = rl.Camera(
rl.Vector3(4.0, 2.0, 4.0),
rl.Vector3(0.0, 1.0, 0.0),
rl.Vecto... | StarcoderdataPython |
1662626 | <gh_stars>0
import math
k, b = raw_input().split(' ')
k = int(k)
b = int(b)
numbits = 0
cap = (math.pow(2, b) - 1) % 1000000009
i = 1
multiple = k * i
while multiple <= cap:
for x in range(0, 32):
numbits += (multiple >> x) & 1
i += 1
multiple = k * i
print numbits
| StarcoderdataPython |
3252638 | import random
from typing import Tuple, List
import numpy.random
from Base.bp2DState import State
from Base.bp2DBox import Box
from Base.bpReadWrite import ReadWrite
from Base.bp2DPnt import Point
def state_generator(bin_size: Tuple[int, int], box_list: List[Tuple[int, Tuple[int, int]]], path: str = None, seed: int... | StarcoderdataPython |
65684 | <reponame>cldf-datasets/rantanenurageo<filename>test.py
import sys
import csv
csv.field_size_limit(sys.maxsize)
def test_valid(cldf_dataset, cldf_logger):
assert cldf_dataset.validate(log=cldf_logger)
| StarcoderdataPython |
3236498 | <gh_stars>1-10
import time
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import requests
from collections import OrderedDict
import os
import sys
from io import BufferedReader
# sys.path.append("..")
from utils.yaml... | StarcoderdataPython |
4832718 | <gh_stars>0
"""
Selection Sort
Select an element and find the smallest number in the array and swap. continue until we reach the end of the array
Worst Case O(N2)
Average Case O(N2)
Best Case O(N2)
"""
def selection_sort(array):
n = len(array)
for i in range(n):
min_index = i
for j in range... | StarcoderdataPython |
163778 | import matplotlib as mpl
import uproot3 as uproot
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)
import scipy
import numpy as np
import math
import pandas as pd
import seaborn as sns
import mplhep as hep
#import zfit
import inspect
import sys
... | StarcoderdataPython |
3214225 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Mapping fastq to reference genome
1. rRNA, spikein, optional
2. genome
"""
import os
import sys
import re
import io
import glob
import json
import fnmatch
import tempfile
import shlex
import subprocess
import logging
import pandas as pd
import pysam
import pybedtools
... | StarcoderdataPython |
1620244 | #-*- coding:utf-8 -*-
#
# This file is part of CoTeTo - code templating tool
#
name = 'libSimModel'
description = 'SimXML file reader, return objects from SimXML files'
version = '0.1'
author = 'EnEff-BIM team'
helptxt = """
Help yourself"""
def fetchData(uriList, systemCfg, generatorCfg, logger):
from mapapi.Map... | StarcoderdataPython |
4830109 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-09-17 09:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rideshare', '0063_auto_20170917_0930'),
]
operations = [
migrations.AddField(... | StarcoderdataPython |
1699466 | <reponame>DNL-inc/bit
from aiogram import types
from keyboards.inline import blank_callback, back_callback
from middlewares import _
from models import Subgroup, User
async def get_keyboard(group_id, editable=True, for_events=False, user=None):
keyboard = types.InlineKeyboardMarkup(row_width=1)
subg... | StarcoderdataPython |
1776781 | import matplotlib.pyplot as plt
import decimal
from datetime import datetime
ctx = decimal.Context()
ctx.prec = 20
token_store = './output/tokens.json'
plt.style.use('./assets/presentation.mplstyle')
class Chart:
@staticmethod
def generate_line_chart(coin_id, y):
x = [x for x in range(len(y))]
... | StarcoderdataPython |
2025 | # Copyright (c) 2013 - 2015 EMC Corporation.
# 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
#
# Unle... | StarcoderdataPython |
1708148 | <reponame>FowlerLab/hgvs-patterns
import unittest
import re
from mavehgvs.patterns.dna import (
dna_equal_c,
dna_equal_n,
dna_equal_gmo,
dna_sub_c,
dna_sub_n,
dna_sub_gmo,
dna_del_c,
dna_del_n,
dna_del_gmo,
dna_dup_c,
dna_dup_n,
dna_dup_gmo,
dna_ins_c,
dna_ins_n,
... | StarcoderdataPython |
4836866 | <filename>pytorch/libs/nnet/loss.py
# -*- coding:utf-8 -*-
# Copyright xmuspeech (Author: Snowdar 2019-05-29)
import numpy as np
import torch
import torch.nn.functional as F
from libs.support.utils import to_device
from .components import *
## TopVirtualLoss ✿
class TopVirtualLoss(torch.nn.Module):
""" This is... | StarcoderdataPython |
123141 | def load_key():
with open("key.key","rb") as key:
key = key.read()
return key | StarcoderdataPython |
3304132 | <gh_stars>1-10
import cProfile
import timeit
import profile
import textwrap
import functools
import time
print('Troubleshooting Python Application Development: Chapter 1')
print('-' * 79)
# --------------------------------------------------------------------------------
# 1.1
print('Measuring time between two lines ... | StarcoderdataPython |
151558 | <reponame>asantos2000/master-data-structures-algorithms<filename>lista02/majoritario_2.py
'''
majoritario(V):
E = merge_sort(V)
conte = 0
metade = V.tamanho div 2
item_anterior = E[0]
para item em E
se item == item_anterior
conte 1
se conte > metade
re... | StarcoderdataPython |
116928 | class Solution:
# Count Consecutive Groups (Top Voted), O(n) time and space
def countBinarySubstrings(self, s: str) -> int:
s = list(map(len, s.replace('01', '0 1').replace('10', '1 0').split()))
return sum(min(a, b) for a, b in zip(s, s[1:]))
# Linear Scan (Solution), O(n) time, O(1) space... | StarcoderdataPython |
66068 | from twisted.internet.protocol import Protocol
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from threading import Thread
from tpm import *
import json
import base6... | StarcoderdataPython |
3327036 | from brainiak.eventseg.event import EventSegment
from scipy.special import comb
import numpy as np
import pytest
from sklearn.exceptions import NotFittedError
def test_create_event_segmentation():
es = EventSegment(5)
assert es, "Invalid EventSegment instance"
def test_fit_shapes():
K = 5
V = 3
... | StarcoderdataPython |
3338495 | <gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("--target", type=Path, required=True)
parser.add_argument("--save_dir", ... | StarcoderdataPython |
1629776 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import csv
def getstart(file_path):
data=[]
csvFile=open(file_path,'r', errors='ignore')
reader=csv.reader(csvFile)
for line in reader:data.append(line)
return data | StarcoderdataPython |
170430 | import math
vineyard_area = int(input())
production_area = vineyard_area * (40 / 100)
kg_grape = float(input()) * production_area
vine_for_sale = int(input())
workers = int(input())
vine = kg_grape / 2.5
if vine >= vine_for_sale:
vine_left = vine - vine_for_sale
vine_for_workers = vine_left / workers
prin... | StarcoderdataPython |
152884 | import json
import textwrap
from redict import utils
class JsonMinifyTestCase:
def template(self, json_string, expected):
in_dict = json.loads(utils.json_minify(json_string))
expected_dict = json.loads(expected)
assert in_dict == expected_dict
def test_1(self):
json_string =... | StarcoderdataPython |
1777782 | <reponame>GiverPlay007/aprendendo-python
###########################
#Calcular função em Python#
###########################
calculos = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for calculo in calculos:
print('=== Calcular função de X ===')
print('Sessão', calculo)
print(' ')
a = input('Qual o valor individual?\nR:... | StarcoderdataPython |
1728101 | <filename>yui/apps/info/toranoana/tasks.py<gh_stars>10-100
import asyncio
import datetime
from collections import defaultdict
from typing import Union
import aiohttp
from more_itertools import chunked
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.sql.expression import and_
from sqlalchemy.sql.expressi... | StarcoderdataPython |
3225780 | <filename>hackerrank/algorithms/implementation/medium/extra_long_factorials/py/solution.py
#!/bin/python3
import sys
fact = lambda n: 1 if n <= 1 else n * fact(n - 1)
n = int(input().strip())
fct = fact(n)
print(fct)
| StarcoderdataPython |
1701573 | <gh_stars>1-10
"""
********************************************
test_generator_modul_test_einstellungen.py
@digitalfellowship - Stand 07/2021
Autor: <NAME>
********************************************
Dieses Modul dient der Erstellung von Testeinstellungen für einen ILIAS-Test
Es sind nicht alle Einstellmöglichkeiten ... | StarcoderdataPython |
3293930 | import pytest
import time
import stl_path
from trex_stl_lib.api import *
"""
An example on how to use TRex for functional tests
using the stateless API with service mode
"""
@pytest.mark.parametrize("protocol", ["TCP", "UDP", "ICMP"])
def test_one_packet(trex, protocol):
tx_port, rx_port = trex.get_all_ports()
... | StarcoderdataPython |
3353155 | """
# LARGEST DIVISIBLE SUBSET
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
Input: [1,2,3]
Output: [1,2] (of course, [1,3] wi... | StarcoderdataPython |
1766840 | <gh_stars>0
import numpy as np
from dezero import Variable
from dezero.utils import plot_dot_graph
import dezero.functions as F
x = Variable(np.array(1.0))
y = F.tanh(x)
x.name = 'x'
y.name = 'y'
y.backward(create_graph=True)
iters = 1
for i in range(iters):
gx = x.grad
x.clear_grad()
gx.backward(create_... | StarcoderdataPython |
3209121 | <gh_stars>0
# -*- coding: utf-8 -*-
""".. moduleauthor:: <NAME>"""
from dataclasses import dataclass
from typing import final, Optional, Dict, List
@final
@dataclass
class RtTfF:
r_tp: int = 0
r_tn: int = 0
r_fp: int = 0
r_fn: int = 0
def merge_ttff_fun(container: RtTfF, target: RtTfF, /) -> int:
... | StarcoderdataPython |
1717089 | <filename>NoSQLAttack/scanIP.py<gh_stars>1-10
import socket;
import globalVar as GlobalVar
from mongo import netAttacks
def scanMongoDBIP():
SHODAN_API_KEY = "<KEY>";
api = shodan.Shodan(SHODAN_API_KEY);
print 'Start Scanning.....'
try:
results = api.search('mongoDB')
# print 'Results fo... | StarcoderdataPython |
117396 | """Queries
This module contains MongoDB queries for the Squirrel program.
Examples
python -m unittest tests.test_queries
"""
import sys
from pprint import pprint
from typing import List
from bson import ObjectId
from pymongo import MongoClient
from pymongo.database import Database
from pymongo.errors import Serve... | StarcoderdataPython |
3396510 | <reponame>josevictorp81/Uri-questions-solutions
import math
x = input().split()
x1 = float(x[0])
y1 = float(x[1])
y = input().split()
x2 = float(y[0])
y2 = float(y[1])
print('{:.4f}'.format(math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2))) | StarcoderdataPython |
3234742 | import scrapy
from scrapy_splash import SplashRequest
from ..items import CareerspiderItem
class CareerFairSpider(scrapy.Spider):
name = "careerfair_spider"
start_urls = ['https://app.thefairsapp.com/#/fair/648/employers']
custom_settings = {
'FEED_EXPORT_FIELDS' : ["name", "industry", "job", "op... | StarcoderdataPython |
1691853 | import os
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import rcParams
import pandas as pd
from scipy.spatial import distance
from scipy.cluster import hierarchy
from sklearn.cluster import AgglomerativeClustering
os.chdir('Chapter_5')
# %%
# import all sites
conditions = [... | StarcoderdataPython |
1781973 | import unittest
from fun import greeter
class GreetingTests(unittest.TestCase):
def test_it_should_properly_greet_a_user(self):
cases = [
('<NAME>', 'Hello, <NAME>'),
('Class', 'Hello, Class')
]
for c in cases:
name = c[0]
expected = c[1]
... | StarcoderdataPython |
38655 | <reponame>sebanie15/simple_clinic
"""Console script for simple_clinic."""
import sys
import click
class ActiveDoctor(object):
def __init__(self):
self.id = 0
active = click.make_pass_decorator(ActiveDoctor, ensure=True)
@click.group()
@click.option('--id', type=int, help='')
@active
def cli(active, i... | StarcoderdataPython |
1735796 | <reponame>iyanmv/galois<gh_stars>0
def add(x, y):
"""
Adds two Galois field arrays element-wise.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.add.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
x = GF.Random(10); x
... | StarcoderdataPython |
11920 | from typing import Any, Dict, Tuple
import torch
from torch_geometric.nn import GATConv
from torch_sparse import SparseTensor, set_diag
from rgnn_at_scale.aggregation import ROBUST_MEANS
from rgnn_at_scale.models.gcn import GCN
class RGATConv(GATConv):
"""Extension of Pytorch Geometric's `GCNConv` to execute a... | StarcoderdataPython |
3306324 | <reponame>stanionascu/python-embyapi
# coding: utf-8
"""
Emby Server API
Explore the Emby Server API # noqa: E501
OpenAPI spec version: 4.1.1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class SyncModelSyncJobItem(obj... | StarcoderdataPython |
3611 | """Mobjects representing vector fields."""
__all__ = [
"VectorField",
"ArrowVectorField",
"StreamLines",
]
import itertools as it
import random
from math import ceil, floor
from typing import Callable, Iterable, Optional, Sequence, Tuple, Type
import numpy as np
from colour import Color
from PIL import I... | StarcoderdataPython |
3325404 | <gh_stars>0
# 자료정리
# 장르별로 재생횟수를 정리해야겠지 ? > 그래야 어느 노래를 먼저 틀지 알 수 있으니까
# 장르내에서 순위를 매겨서 정리 > 어떤 자료형으로 어떻게 장르별 재생횟수를 기록할 것 인가?
import collections
def solution(genres, plays) :
count_max = collections.defaultdict(int)
rank_genre = []
rank_songs = []
answer = []
for ind, (genre, play) in enumerate(zip(... | StarcoderdataPython |
72104 | <filename>GetProvince.py<gh_stars>1-10
# -*- coding: utf-8 -*-
import requests
import os
class GetProvince(object):
@staticmethod
def get_all():
url = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9044"
headers = {
"User-Agent": "Mozilla/5.0 (W... | StarcoderdataPython |
1648004 | """
This file sets a parameter for the current scence.
"""
def set_param(args, scene_root, history_db, current_scene_db):
"""sets the parameter by making a sqlite call"""
from src.praxxis.sqlite import sqlite_parameter
from src.praxxis.display import display_param
from src.praxxis.util import error
... | StarcoderdataPython |
3380937 | <filename>lib/optim/build.py<gh_stars>10-100
import torch.optim as optim
from .adamw import AdamW
from .adabound import AdaBound, AdaBoundW
from .asam import SAM, ASAM
def build_optimizer(model, args):
if args.optims == "sgd":
optimizer = optim.SGD(
filter(lambda p: p.requires_grad, model.para... | StarcoderdataPython |
3253140 | """Class implementing meta-model for a Conv3D Layer."""
from typing import Dict
from tensorflow.keras.layers import (Activation, BatchNormalization, Conv3D,
Layer)
from .regularized_meta_layer import RegularizedMetaLayer
from ..utils import distributions
class Conv3DMetaLayer(Re... | StarcoderdataPython |
118802 | # Author: <NAME>
# Davenport Lab - Penn State University
# Date: 9-2-2021
from src import *
| StarcoderdataPython |
84466 | <filename>third_party/sqlalchemy_0_7_1/sqlalchemy/ext/declarative.py
# ext/declarative.py
# Copyright (C) 2005-2011 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
Synopsis
=... | StarcoderdataPython |
1744782 | """ Helper functions and exceptions for the Zenodo extension """
from datetime import datetime
import os
import re
import tempfile
from urllib.parse import urlparse, urlencode
import zipfile
class UserMistake(Exception):
"""Raised when something went wrong due to user input"""
pass
def get_id(doi):
"""... | StarcoderdataPython |
1652447 | # coding: utf-8
from unittest import TestCase
from siebenapp.goaltree import Goals
from siebenapp.domain import (
EdgeType,
HoldSelect,
ToggleClose,
Delete,
ToggleLink,
Add,
Select,
Insert,
Rename,
)
from siebenapp.tests.dsl import build_goaltree, open_, selected, previous, clos_
... | StarcoderdataPython |
1727396 | # -*- coding: utf-8 -*-
import json
import time
from datetime import datetime as dt
from . import test_common
class TestOomusicPlaylist(test_common.TestOomusicCommon):
def test_00_create_interact(self):
"""
Test creation and basic interaction
"""
self.FolderScanObj.with_context(t... | StarcoderdataPython |
3264981 | <reponame>IBM/blackbox-adversarial-reprogramming
import tensorflow as tf
def func(train_loss, iNum, var_noises):
image_size = 299
batchsize = 10
q_batch = 1
losses = []
glist = []
##Set paramters
beta = 0.1
d = image_size*image_size*3
b_constant = d
##gradient-free... | StarcoderdataPython |
3272074 | '''
Code for "Three-dimensional imaging through scattering media based on confocal diffuse tomography"
<NAME> and <NAME>
See README file in this directory for instructions on how to setup and run the code
'''
import h5py
import time
import numpy as np
from numpy.fft import ifftn, fftn
import matplotlib.pyplot as plt
... | StarcoderdataPython |
3210840 | import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
import warnings
from matplotlib import style
from collections import Counter
style.use('fivethirtyeight')
import pandas as pd
import random
benign_class = 2
malignant_class = 4
def k_nearest_neighbors(data,predict,k=3):
if len(data) >= k:
... | StarcoderdataPython |
4829177 | import copy
import subprocess
import re
import requests
def fetch_gist(url):
"""
Get the gist url from a media content url
"""
# Get the content from the url
content = requests.get(url).content.decode()
# Find the gist url
match = re.findall("<script src(.*?)><\/script>", content)[0]
g... | StarcoderdataPython |
4805380 | <reponame>leschzinerlab/myami-3.2-freeHand
# The Leginon software is Copyright 2004
# The Scripps Research Institute, La Jolla, CA
# For terms of the license agreement
# see http://ami.scripps.edu/software/leginon-license
#
# $Source: /ami/sw/cvsroot/pyleginon/leginon.gui.wx/TargetFinder.py,v $
# $Revision: 1.19 $
# $N... | StarcoderdataPython |
1676152 | import requests
from lxml import html
from lxml.etree import tostring
class UserParser:
def set_database(self,database):
self.database = database
def set_user_id(self, id):
self.Session = requests.session()
self.trip_advisor = 'https://www.tripadvisor.ca'
self.id = id
... | StarcoderdataPython |
3326181 | import pytest
from plenum.test.bls.helper import change_bls_key, check_bls_key
from plenum.test.conftest import pool_txn_stewards_data, stewards_and_wallets
@pytest.fixture(scope="module")
def update_bls_keys(looper, tconf, nodeSet, stewards_and_wallets):
node = nodeSet[0]
steward_client, steward_wallet = st... | StarcoderdataPython |
87750 | #!/usr/bin/env python
"""
"""
from plasTeX import Command, Environment
class center(Environment):
blockType = True
class centering(center):
blockType = True
class flushleft(Environment):
blockType = True
class raggedright(flushleft):
blockType = True
class flushright(Environment):
blockTyp... | StarcoderdataPython |
165557 | # ==============================================================================
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# ==============================================================================
"""Openvino Tensorflow BiasAdd operation test
"""
from __future__ import absolu... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.