id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
218666 | <reponame>nam-pi/data_conversion
"""The module for the Namespace class.
Classes:
Namespace
"""
from rdflib import Namespace
from modules.cli_param import Env
def _base_ns(resource: str) -> Namespace:
return Namespace(
Env.data_namespace_prefix + resource + "/"
if Env.data_namespace_prefix.e... | StarcoderdataPython |
5125551 | #!/usr/bin/env python
from __future__ import print_function
import angles
import math
import os.path
import rospy
from geometry_msgs.msg import Point, Pose, PoseStamped, Quaternion
from nav_msgs.msg import Odometry, Path
from tf.transformations import euler_from_quaternion, quaternion_from_euler
POSE_FORMAT = """\
... | StarcoderdataPython |
364628 | import string
import time
letters = string.ascii_letters
char_list = list(letters)
char_tuple = tuple(letters)
char_set = set(letters)
print(char_list)
def membership_test(n,container):
for i in range(n):
if 'z' in container:
pass
#test array
start = time.perf_counter()
membership_test(1000000... | StarcoderdataPython |
3227212 | <filename>v1/banks/urls.py
from django.urls import path
from .views.bank import BankView
urlpatterns = [
# Banks
path('banks', BankView.as_view()),
]
| StarcoderdataPython |
3382134 | import rss_reader_kapitonov
def main():
rss_reader_kapitonov.main()
| StarcoderdataPython |
331409 | # Configuration file for the Sphinx documentation builder.
#
# Full list of options can be found in the Sphinx documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
import re
import sys
from pathlib import Path
# Set package variables and add to path
package_name = "hijri_converter"
package_p... | StarcoderdataPython |
4822547 | <reponame>YufeiCui/CSCA48
# Provided by Dr. <NAME> & <NAME>. Edited by <NAME>
class EmptyStackException(Exception):
pass
class Stack(object):
''' this class defines a LIFO/FILO stack of items and raise an exception in case the Stack is empty where pop() or
top() is requested '''
def __init__(self):... | StarcoderdataPython |
1796529 | <gh_stars>1-10
xs_gen = """\
set title "[CHAR] {reactor} Cross Section Generator"
set acelib "{xsdata}"
% --- Matrial Definitions ---
% Initial Fuel Stream
mat fuel -{fuel_density}
{fuel}
% Cladding Stream
mat cladding -{clad_density}
{cladding}
% Coolant Stream
mat coolant -{cool_density} moder lwtr 1001
{cool... | StarcoderdataPython |
6468259 | print ("H<NAME>!")
a = int(input ("How many maytes are there?"))
if a < 2:
print("There are 2 maytes here!")
| StarcoderdataPython |
4832496 | """
This is a python file to control and get information about optical drives.
Eventually aim to handle CD, DVD , BluRay on Windows and Linux
"""
import subprocess
class ODMedia:
def __init__(self):
self.path_root = r"C:\Program Files (x86)\CDBurnerXP\cdbxpcmd.exe"
#Safety check for known situat... | StarcoderdataPython |
1897954 | """
Во входном файле (вы можете читать данные из sys.stdin, подключив библиотеку sys) записан текст. Словом считается
последовательность непробельных символов идущих подряд, слова разделены одним или большим числом пробелов или
символами конца строки. Определите, сколько различных слов содержится в этом тексте.
Формат... | StarcoderdataPython |
6578380 | <reponame>vidakDK/colour<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .datasets import * # noqa
from . import datasets
from .prediction import (corresponding_chromaticities_prediction_CIE1994,
corresponding_chromaticities_prediction_CMCCAT2000,
... | StarcoderdataPython |
3390559 | <reponame>fyrestartr/Readers-Underground<gh_stars>1-10
from os import listdir, remove
from os.path import join, normpath
from utils.zip import unzip
class FolderItemsUnzipper:
def __init__(self, folder_path):
self.folder_path = folder_path
def run(self):
for file in listdir(self.folder_path):... | StarcoderdataPython |
11254418 | <reponame>qe-team/marmot
import sys
from subprocess import Popen, PIPE
from marmot.features.feature_extractor import FeatureExtractor
from marmot.exceptions.no_data_error import NoDataError
from marmot.exceptions.no_resource_error import NoResourceError
class POSFeatureExtractor(FeatureExtractor):
"""
POS fo... | StarcoderdataPython |
3351061 | <reponame>htlcnn/ironpython-stubs<gh_stars>100-1000
# encoding: utf-8
# module Grasshopper.Kernel.Special.SketchElements calls itself SketchElements
# from Grasshopper,Version=1.0.0.20,Culture=neutral,PublicKeyToken=dda4f5ec2cd80803
# by generator 1.145
""" NamespaceTracker represent a CLS namespace. """
# no impo... | StarcoderdataPython |
12823676 | import time
from PIL import Image
import hashlib
import numbers
from google.cloud import pubsub_v1
from typing import List
from fastapi import APIRouter, Depends, UploadFile, File, Form, HTTPException
from starlette.requests import Request
from func_timeout import func_set_timeout
from sqlalchemy.orm import Session
f... | StarcoderdataPython |
3578627 | #!/usr/bin/env python
import pyspark
import sys
if len(sys.argv) != 3:
raise Exception("Exactly 2 arguments are required: <inputUri> <outputUri>")
inputUri=sys.argv[1]
outputUri=sys.argv[2]
sc = pyspark.SparkContext()
lines = sc.textFile(sys.argv[1])
words = lines.flatMap(lambda line: line.split())
wordCounts = w... | StarcoderdataPython |
9798346 | # -*- coding: utf-8 -*-
from django import template
from djR.conf import DEFAULT_DB
register = template.Library()
@register.simple_tag
def get_default_db():
return DEFAULT_DB | StarcoderdataPython |
3263496 | <gh_stars>1-10
from myoperator import RowOperator
import math,sys
class TFIDF(RowOperator):
"""
Generate cleaned word vectors and respective count vector
and term idf vector.
term idf = log(total number of terms in the dataset /
number of documents where terms ap... | StarcoderdataPython |
6559191 | <reponame>MRossol/plotting
"""
Plotting of 3D arrays in 2D plots
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import numpy.ma as ma
import seaborn as sns
from plotting.base import plotting_base
def heatmap_plot(data, **kwargs):... | StarcoderdataPython |
1784122 | <gh_stars>0
"""Trino integration tests.
These rely on having a Trino+Hadoop cluster set up.
They also require a tables created by make_test_tables.sh.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from pyhive import trino
from pyhive.tests.dbapi_test_case import with_cursor, with... | StarcoderdataPython |
5156804 | <filename>python/tests/test_node_port.py<gh_stars>1-10
from ionpy import Node, Port, Type, TypeCode
def test_node_port():
t = Type(code_=TypeCode.Int, bits_=32, lanes_=1)
port_to_set = Port(key='iamkey', type=t, dim=3)
ports = [ port_to_set, ]
n = Node()
n.set_port(ports)
port_to_get = n.g... | StarcoderdataPython |
3466121 | #!/usr/bin/env python
import rospy
from std_msgs.msg import Bool
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
from geometry_msgs.msg import TwistStamped, Twist
import math
from twist_controller import Controller
from yaw_controller import YawController
from pid import PID
from lowpa... | StarcoderdataPython |
8085879 | <filename>order.py
#!/usr/bin/env python
import argparse, os, sys, signal
sourcedir=os.path.dirname(os.path.abspath(__file__))
cwdir=os.getcwd()
sys.path.append(sourcedir)
from pythonmods import runsubprocess
def default_sigpipe():
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def positiveint(x):
x = int(x)
... | StarcoderdataPython |
3233562 | """create video table3
Revision ID: c74dc70ede84
Revises: <PASSWORD>
Create Date: 2021-09-23 20:58:02.017347
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c74dc70ede84'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
... | StarcoderdataPython |
8012913 | <gh_stars>10-100
import json
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
def read_pvuv_data():
"""
read pv uv data
:return:list,ele = (date,pv,uv)
"""
data = []
with open('./data/pvuv.txt') as fo:
linenum = 0
for r... | StarcoderdataPython |
9648782 | from .summary import Summary
__all__ = ["Summary"]
| StarcoderdataPython |
3421432 | #!/usr/bin/env python
import yaml
import json
my_list = range(5)
my_list.append('Python Programming')
my_list.append('Is Fun')
my_list.append({})
my_list[-1]['IP_ADDR'] = '10.10.10.239'
my_list[-1]['HOSTNAME'] = 'testbox'
my_list[-1]['DOMAIN_NAME'] = 'someplace.net'
with open("Lesson1Number6_create_first_yaml.yml", ... | StarcoderdataPython |
4800065 | <reponame>theanshulcode/Automatic-License-Number-Plate-Recognition-System
import numpy as np
import cv2
from PIL import Image
import pytesseract as tess
def clean2_plate(plate):
gray_img = cv2.cvtColor(plate, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray_img, 110, 255, cv2.THRESH_BINARY)
if cv2.waitKe... | StarcoderdataPython |
6408647 | from django.contrib.admin.sites import AdminSite
from django.core import mail
from django.test import TestCase
from django.utils import timezone
from django_q.models import Schedule
import recurrence
from qatrack.notifications.models import (
RecipientGroup,
ServiceEventReviewNotice,
UnitGroup,
)
from qatr... | StarcoderdataPython |
9681214 | <gh_stars>10-100
n=int(input("enter a number: "))
i=1
while i<=n:
j=i
c=0
k=j
while j>0:
print(k," ",sep='',end="")
k=k+n-1-c
j-=1
c+=1
i+=1
print()
'''
output:
enter a number: 9
1
2 10
3 11 18
4 12 19 25
5 13 20 26 31
6 14 21 27 32 36
7 15 22 28 33 37 40
8 16 23 29 34 38 41 43
9 17 24 30 35 39 42... | StarcoderdataPython |
6563341 | # -*- coding: utf-8 -*-
from typing import List
import pandas as pd
from zvt.api.kdata import get_kdata_schema
from zvt.contract.api import decode_entity_id
from zvt.contract.drawer import Drawer, ChartType
from zvt.utils import to_pd_timestamp
def compare(entity_ids, schema_map_columns: dict = None, chart_type: Ch... | StarcoderdataPython |
6473798 | import sys
import csv
def main():
# check to make sure the number of arguments passed in are correct
if len(sys.argv) != 3:
print("Usage: dna.py [csv file] [dna text file]")
sys.exit(1)
# AGATC,TTTTTTCT,AATG,TCTAG,GATA,TATC,GAAA,TCTG
# DnaSTR = ["AGATC", "AATG", "TATC"]
names = []... | StarcoderdataPython |
240083 | import pyjion
import pyjion.dis
import pytest
@pytest.mark.optimization(level=1)
def test_import(capsys):
def _f():
print("foo foo")
return 2
assert _f() == 2
info = pyjion.info(_f)
assert info['compiled']
pyjion.dis.dis(_f)
captured = capsys.readouterr()
assert "ldarg.1" ... | StarcoderdataPython |
8162430 | <reponame>fragro/Open-Assembly
from django.contrib import admin
from models import DashboardPanel
admin.site.register(DashboardPanel)
| StarcoderdataPython |
3498993 | # -*- coding: utf-8 -*-
import os
import pytest
import logging
from phk_logger import __version__
from phk_logger import PHKLogger as Logger
@pytest.fixture(scope='session')
def log_file(request):
# Will be executed before the first test
f = open(request.param, 'wt')
f.close()
f = open(request.param... | StarcoderdataPython |
4987806 | <reponame>elyase/polyaxon
from django.contrib import admin
class JobStatusAdmin(admin.ModelAdmin):
readonly_fields = ('created_at',)
| StarcoderdataPython |
11267824 | #!/usr/bin/env python3
from pv.data import PVData, PVWR
import requests
import datetime
import pytz
import sys
local = pytz.timezone("Europe/Berlin")
class PVRestApi:
pvdata = PVData()
host = "http://127.0.0.1"
url = "/rawdata.html"
def __init__(self, host="http://127.0.0.1", url="/... | StarcoderdataPython |
3265321 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#File from
#https://github.com/dthierry/k_aug/blob/ma57/test/pyomo_/sens_kaug_dcdp.py
from __future__ import division
from __future__ import print_function
from pyomo.environ import *
from pyomo.opt import SolverFactory, ProblemFormat
from shutil import copyfile
"""Exampl... | StarcoderdataPython |
9663421 | <reponame>aragilar/NewsBlur
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from vendor.paypal.standard.forms import PayPalStandardBaseForm
from vendor.paypal.standard.pdt.models import PayPalPDT
class PayPalPDTForm(PayPalStandardBaseForm):
class Meta:
model = PayPalPDT | StarcoderdataPython |
6657804 | runn = True
while run
input_value = input("Enter student's score or type "Exit" to quit":)
score = float(input_value)
if score >= 90 and score <= 100:
print(" student wins laptop")
elif score >= 60 and score <= 89:
print(" student wins tablet")
elif score >= 0 and score <= 59:
print(" student wins nothing")... | StarcoderdataPython |
1765812 | <gh_stars>0
# Returns (first, last]) index of target value in the array
# 0 1 2 3 4 5 6 7 8 9 10
arr = [5, 5, 7, 7, 8, 8, 8, 8, 10, 10, 12]
target = 8
# Returns leftmost index of the target
def get_pos(arr, target):
n = len(arr)
lower = 0
upper = n - 1
pos = n
while lower <= upper:... | StarcoderdataPython |
27705 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import enum
import json
import os
import plistlib
import subprocess
import time
import tools
import requests
python_script_debug_enable = False # 是否开启debug模式 用于测试脚本
pwd = os.getcwd() # 当前文件的路径
ios_project_path = os.path.abspath(os.path.dirname(
pwd) + os.path.sep... | StarcoderdataPython |
4988474 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place... | StarcoderdataPython |
368411 | # This module is automatically generated by autogen.sh. DO NOT EDIT.
from . import _Generic
class _Ansible(_Generic):
_type = "ansible"
_icon_dir = "resources/generic/ansible"
class Ansible(_Ansible):
_icon = "Ansible.png"
class Collection(_Ansible):
_icon = "Collection.png"
class Module(_Ansib... | StarcoderdataPython |
9636075 | <reponame>SimmonsRitchie/topojoin
import pytest
from topojoin.helper import get_topo_features
from topojoin.topojoin import TopoJoin
from pathlib import Path
def test_topojson_init(topo_path, csv_path):
""" Test that TopoJoin instance is initialized and attribs are properly set """
topojoin_obj = TopoJoin(to... | StarcoderdataPython |
6463473 | import utils
import logging
import json
import re
import urllib
import random
import counters
import specialcases
from SteamAPI.Users import *
from datastore.models import *
from datetime import datetime, timedelta
from google.appengine.api import mail
from config import *
from bs3.BeautifulSoup import BeautifulSoup
fr... | StarcoderdataPython |
308981 | <reponame>foreignbill/eoj3
from rest_framework.views import APIView
from rest_framework.response import Response
from account.models import User
from problem.models import Problem
from account.permissions import is_admin_or_root
from django.db.models import Q
from django.urls import reverse
from functools import red... | StarcoderdataPython |
3549394 | import urllib2
import logging
from lxml import html
# Default logger
logger = logging.getLogger('spotify2piratebay')
def fetch_url(url):
""" Fetches a URL and returns contents - use opener to support HTTPS. """
# Fetch and parse
logger.debug(u'Fetching %s', url)
# Use urllib2 directly for enabled ... | StarcoderdataPython |
3497452 | <reponame>SubTheSandwich/YouTube-to-Mp3
#hi!
import os
import subprocess
from pydub import AudioSegment
url = input("Please enter your url: ")
ask = str(input("File name?"))
def main():
try:
if os.path.exists('file.m4a'):
os.remove('file.m4a')
subprocess.call(['youtube-dl', '-f', '140... | StarcoderdataPython |
8163053 | from multiprocessing import Process, Pipe
from random import random
import matplotlib.pyplot as plot
from control import TransferFunction, feedback, step_response, series, step_info
default_generations = 150
default_population = 50
default_crossover = 0.6
default_mutation = 0.25
F = TransferFunction(1, [1, 6, 11, 6, ... | StarcoderdataPython |
11341048 | <filename>brainfrick/__init__.py
from .__main__ import __version__
from .interpreter import Interpreter
def main(argv):
file = " ".join(argv)
bf = Interpreter(file=file)
bf.run() | StarcoderdataPython |
3398483 | from sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve, auc
def get_metrics(predicted_label, labels, predicted_score=None, is_binary_task=True):
if is_binary_task:
tp, fp, fn, tn = get_confusion_matrix(predicted_label, labels)
roc_auc = roc_auc_score(y_true=labels, y_score=predict... | StarcoderdataPython |
6591544 | # Generated by Django 3.2.6 on 2021-09-13 09:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('board', '0006_alter_stor... | StarcoderdataPython |
11380640 | <filename>Command Line Programs/mapIt.py
#! python3
# mapIt.py
# Launches a map in the browser using an address
# from the command line or clipboard
import webbrowser, sys, logging, pyperclip
if len(sys.argv) > 1:
# From command line
address = ' '.join(sys.argv[1:])
else:
# From clipboard
... | StarcoderdataPython |
5169837 | <reponame>jaswinder9051998/Resources<gh_stars>100-1000
#Count files with a .py extension in root1 directory and its subdirectories
#This solution works for the previous exercise as well with one file in a directory
import glob
file_list = glob.glob("subdirs/**/*.py", recursive=True)
print(len(file_list))
| StarcoderdataPython |
11269382 | # Copyright 2016 ZTE Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | StarcoderdataPython |
8182875 | <filename>yolo3/det_visualizer.py
import os
import cv2
import uuid
import numpy as np
import shutil
from tensorflow.keras.callbacks import Callback
from .models import yolo_anchors, yolo_anchor_masks, yolo_tiny_anchors, yolo_tiny_anchor_masks
from .convert import make_eval_model_from_trained_model
from .utils import dr... | StarcoderdataPython |
1783649 | <gh_stars>1-10
import abc
from .. import exceptions
from .. import contextManagers
## @todo Should we just assume all validation of supplied entity references,
## etc is taken care of in the Manager/Entity abstraction, to avoid doubling
## the work, if a host already tests whether or not something is a ref before
## ... | StarcoderdataPython |
6410716 | <reponame>djtorch26/MorningAssistant
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 02:12:33 2020
@author: Dawson
"""
from gtts import gTTS
from . import FileManager as fmanager
#import playsound
import shutil
import pygame
import os
nuggetSpeech = fmanager.readNuggetFile()
def speak(text):
tts = gTTS(text=... | StarcoderdataPython |
87999 | <reponame>Ahlyab/udemy-course-grabber
from pack import functions
from pack import banner
no = int(1)
def write_coupons (list_of_coupons_and_title):
global no
for indx, coupon_and_title in enumerate(list_of_coupons_and_title):
title, link = coupon_and_title.split('||')
coupons_file.w... | StarcoderdataPython |
1678841 | <reponame>wangcj05/sciann
""" Utilities to process functionals.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sciann
def is_functional(f):
""" Checks whether `f` is a functional object.
# Arguments
f: an object to be tested.... | StarcoderdataPython |
3588707 | class Array:
def __init__(self):
self._row_len = 0
self._data = []
@property
def rows(self):
return len(self._data)
def add_row(self, row: str):
if self._row_len == 0:
self._row_len = len(row)
elif self._row_len != len(row):
raise ValueEr... | StarcoderdataPython |
196912 | <reponame>tomviner/dojo-tcp-generator
import socket
import random
if __name__ == '__main__':
HOST = '127.0.0.1'
PORT = 8080
def process_data(data):
answers = [
b"No You " + data,
b"Tell that to your sister and/or brother!",
b"You didn't!",
b"That d... | StarcoderdataPython |
3345620 | <reponame>ttrummel/pandapipes
# Copyright (c) 2020 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
from pandapower.control import run_control as run_contro... | StarcoderdataPython |
1858244 | """
mbed OS
Copyright (c) 2011-2016 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... | StarcoderdataPython |
3360936 | <filename>tensor2tensor/models/research/autoencoders.py
# coding=utf-8
# Copyright 2018 The Tensor2Tensor 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.or... | StarcoderdataPython |
4870098 | <filename>tests/test_create_project.py
import os
import subprocess
from click.testing import CliRunner
def test_create_app(project):
os.environ['MASHINA_SETTINGS_MODULE'] = '%s.config.settings' % project
from mashina.commands import createapp
runner = CliRunner()
result = runner.invoke(createapp, ['a... | StarcoderdataPython |
299030 | from typing import Optional
class Node:
def __init__(self, key: int, val: int) -> None:
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int) -> None:
self.capacity = capacity
self.dic = dict()
... | StarcoderdataPython |
1744869 | <filename>Darlington/phase2/Data Structure/day 58 solution/qtn10.py
#program to group a sequence of key-value pairs into a dictionary of lists.
from collections import defaultdict
class_roll = [('v', 1), ('vi', 2), ('v', 3), ('vi', 4), ('vii', 1)]
d = defaultdict(list)
for k, v in class_roll:
d[k].append(v)
print(s... | StarcoderdataPython |
8142012 | import numpy as np
def from_data_file(data_dir):
""" This function reads the data that we use in this demo."""
data=dict()
import scipy.io as sio
data_file = sio.loadmat(data_dir+'/data_train.mat')
data['train']=dict()
data['train']['inputs'] = data_file['inputs']
data['train']['target... | StarcoderdataPython |
6476215 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from application import bootstrap
from cherrypy.process.plugins import Daemonizer
bootstrap()
# debugging purpose, e.g. run with PyDev debugger
if __name__ == '__main__':
import sys ;
import cherrypy
if '--daemon' in sys.argv :
Daemonizer(cherrypy.en... | StarcoderdataPython |
9729055 | <reponame>Testing4AI/DeepJudge
import numpy as np
import scipy.stats
from tensorflow.keras.models import Model
import tensorflow.keras.backend as K
DIGISTS = 4
def Rob(model, advx, advy):
""" Robustness (empirical)
args:
model: suspect model
advx: black-box test cases (adversarial examples)... | StarcoderdataPython |
4875928 | import os
import sys
from configparser import ConfigParser
import platform
import logging as log
from func import Func
import argparse
try:
if getattr(sys, 'frozen', False):
script_dir = os.path.dirname(sys.executable)
else:
script_dir = os.path.dirname(os.path.realpath(__file__))
config =... | StarcoderdataPython |
1922928 | '''Tests for Bruker format conversion.
Copyright <NAME>, University of Oxford 2021
Subject to the BSD 3-Clause License.
'''
import subprocess
from pathlib import Path
import json
import numpy as np
from .io_for_tests import read_nifti_mrs
# Data paths
bruker_path = Path(__file__).parent / 'spec2nii_test_data' / 'b... | StarcoderdataPython |
9631206 | <gh_stars>0
# Generated by Django 3.2.6 on 2021-08-14 22:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('collect', '0006_alter_courseinfo_name'),
]
operations = [
migrations.RemoveField(
model_name='raceinfo',
name='c... | StarcoderdataPython |
285763 | <gh_stars>0
patches = [
{
"op": "remove",
"path": "/PropertyTypes/AWS::S3::StorageLens.S3BucketDestination/Properties/Encryption/Type",
},
{
"op": "add",
"path": "/PropertyTypes/AWS::S3::StorageLens.S3BucketDestination/Properties/Encryption/PrimitiveType",
"value": "J... | StarcoderdataPython |
5137465 | <reponame>heminsatya/aurora<gh_stars>1-10
################
# Dependencies #
################
import importlib
from aurora.security import request, redirect, check_cookie, get_cookie, check_session, get_session, set_session
from aurora.helpers import app_exists
from flask.views import View
####################
# Contr... | StarcoderdataPython |
9697537 | <gh_stars>0
"""
Tests for the implementation of the GroupwiseStratifiedKFold
"""
import math
from groupwise_stratified_kfold import (
GroupwiseStratifiedKFold,
RepeatedGroupwiseStratifiedKFold,
)
from groupwise_stratified_kfold.kfold import (
absolute_class_counts,
diff_distribution,
join_distribu... | StarcoderdataPython |
12835853 | class Solution:
def isValid(self, s: str) -> bool:
stack = []
d = {"]": "[", "}": "{", ")": "("}
for char in s:
# Opening
if char in d.values():
stack.append(char)
elif char in d.keys():
if stack == [] or d[char] != stack.po... | StarcoderdataPython |
6525966 | import os
import random
import shutil
import tarfile
import cv2
import numpy as np
from keras.utils import Sequence
from utilities import download_file, download_image_cv2_urllib
class DataGen(Sequence):
"""
This generator downloads one tar file at each epoch. Extracts and selects the valid images from it to... | StarcoderdataPython |
3504882 | # Write a program to fill the screen horizontally and vertically with your name. [Hint: add the
# option end= '' into the print function to fill the screen horizontally.]
for i in range(100):
for j in range(100):
print('AhmadAbdulrahman', end='')
print('') # to start a new line
| StarcoderdataPython |
5163423 | # -*- coding: utf-8 -*-
"""
makeplot.py
make a figure from the data selected
"""
import sys
import os
from glob import glob
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class MakePlot(... | StarcoderdataPython |
3359091 | #
#Chequea si un numero es primo o no
#Devuelve True si es primo sino devuelve False
def primeNumber(n):
#Por definicion de primo
if(n == 0 or n == 1 or n < 0):
return False
elif(n == 2):
return True
else:
#Checkeo para que sea primo me alcansa con probar
#1 que no... | StarcoderdataPython |
3237574 | import logging
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import RedirectResponse
from prometheus_fastapi_instrumentator import Instrumentator
from api import metadata
from core.config import (
CORS_ORIGINS,
CURRENT_API_VERSION,
DOCS_URL,
... | StarcoderdataPython |
3316860 | <filename>setup.py
from distutils.core import setup
setup(
name = 'uwuizer',
packages = ['uwuizer'],
version = '1.0.1',
license='MIT',
description = 'uwu text generator ٩(◕‿◕。)۶',
author = '<NAME>',
author_email = '<EMAIL>',
url = 'https://github.com/Philinphiladelphia/uwu',
download_url = '... | StarcoderdataPython |
1784180 | import json
from pathlib import Path
import numpy as np
from podm.podm import get_pascal_voc_metrics, MetricPerClass
from tests.utils import load_data, assert_results, load_data_coco
def test_sample2():
dir = Path('tests/sample_2')
gt_BoundingBoxes = load_data(dir / 'groundtruths.json')
pd_BoundingBoxes... | StarcoderdataPython |
1706153 | <gh_stars>0
'''
print( )
print('DESAFIO 1')
nome = input ('Qual seu nome?')
print('Ola ' +nome+ ' Seja bem vindx!')
print( )
print('------- DESAFIO 02 -------')
dia = input ('Qual o dia que você nasceu?')
mes = input ('Qual o mês que você nasceu?')
ano = input ('Qual o ano que você nasceu?')
print('Certo. Você nasceu n... | StarcoderdataPython |
9667759 | <filename>libs/voting.py<gh_stars>1-10
'''
Simplistic voting which keeps track of voters in a poll and can tally the results
This is used by the advancedvote command & reaction package
@author: NGnius
'''
class Poll():
'''Base class for voting systems that everything below extends
This class should never be u... | StarcoderdataPython |
4893526 | #!/usr/bin/python
# Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, t... | StarcoderdataPython |
6411745 | import random
from src.player.IBot import *
from src.action.IAction import *
class RandomBot(IBot):
def moveRandomly(self, board) -> IAction:
validPawnMoves = board.storedValidPawnMoves[self.pawn.coord]
return random.choice(validPawnMoves)
def placeFenceRandomly(self, board) -> IA... | StarcoderdataPython |
1933729 | import inspect
def af_set_var(name,val, layer = 2):
stack = inspect.stack()
inspect.getargvalues(stack[layer].frame).locals[name]=val
def af_get_var(name, layer = 2):
stack = inspect.stack()
return inspect.getargvalues(stack[layer].frame).locals[name]
def func(*args):
def _():
... | StarcoderdataPython |
206970 | # This is the sales.
| StarcoderdataPython |
5184986 | import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
#Getting the data
def get_data(filename ='../data/raw/data.csv' ):
data = pd.read_csv(filename).values
#Shuffling the data
np.random.shuffle(data)
labels = data[:, -1]
images = data[:,:-1]
#Converting the int... | StarcoderdataPython |
366876 | with open('input.txt') as file:
data = file.read()
data = data.splitlines()
depart_timestamp = int(data[0])
ids = []
for v in data[1].split(","):
if v.isdigit():
v = int(v)
ids.append(v)
time_to_wait = 9999999999999999999
best_id = 0
for id in ids:
if id == 'x':
continue
# prin... | StarcoderdataPython |
6617641 | class BiblioAD:
def capturar(this,datos):
# 1. Abrir el archivo
archivo = open("Libros.txt","a")
# 2. Escribir, guardar o almacenar los datos en el archivo
archivo.write(datos+"\n")
# 3. Cerrar el archivo
archivo.close()
return "Datos a c... | StarcoderdataPython |
1887761 | <filename>IOatmos.py
import time
from datetime import datetime, timedelta
import os, sys, string
from netCDF4 import Dataset
import numpy as np
"""
Created by <NAME>
https://github.com/trondkr/model2roms
"""
def help ():
"""
This function generates the initial netcdf atmospheric forcing file for the U and V w... | StarcoderdataPython |
1902365 | <gh_stars>0
from requests_html import HTMLSession, AsyncHTMLSession
def checkAmazonPrice(url):
found = False
while not found:
try:
session = HTMLSession()
r = session.get(url)
price_html = r.html.find('#priceblock_ourprice', first=True)
price = price_htm... | StarcoderdataPython |
6475160 | <gh_stars>0
class Solution:
"""
第一次用时:63min
总用时:88min
时间复杂度:O(n)
空间复杂度:O(n)
思路:将子序列和分别与max、0比较,小于0当做0对待。
"""
def XXX(self, nums: List[int]) -> int:
my_max=nums[0]
subArraySum=nums[0]
if subArraySum<0:
subArraySum=0
for i in range(1,len(nums)):... | StarcoderdataPython |
1795728 | <filename>microsim/utilities.py
# Contains some useful utility functionality
import os
from urllib.request import urlopen
import requests
import tarfile
import pandas as pd
from typing import List
from tqdm import tqdm
from microsim.column_names import ColumnNames
class Optimise:
"""
Functions to optimise th... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.