id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
8143362
import glob import os import sys import ftrace import argparse import time from ftrace import Ftrace, Interval from pandas import Series from saber_common import execCmd from saber_common import get_out_systrace_path if __name__ == '__main__': parser = argparse.ArgumentParser(description='get atrace/ddr/gpu/snoc l...
StarcoderdataPython
12842410
<gh_stars>10-100 # Write a program to find the nth super ugly number. # Super ugly numbers are positive numbers # whose all prime factors are in the given prime list primes of size k. # Example: # Input: n = 12, primes = [2,7,13,19] # Output: 32 # Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the ...
StarcoderdataPython
1810780
<gh_stars>1-10 """ Tests for warnings context managers """ from __future__ import division, print_function, absolute_import import sys import warnings import numpy as np from nose.tools import assert_equal from nose.tools import assert_raises from ..testing import (error_warnings, suppress_warnings, ...
StarcoderdataPython
9714214
<gh_stars>0 """ 2D plotting funtions """ from mpl_toolkits.mplot3d import Axes3D import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from matplotlib import cm import h5py import argparse import numpy as np from os.path import exists import seaborn as sns def plot_2d_contour(surf_file, su...
StarcoderdataPython
11297484
import itertools import jinja2 import os import re import tempfile import subprocess from server import highlight from tests import OkTestCase, skipIfWindows _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)') def striptags(s): stripped = _striptags_re.sub('', s) return jinja2.Markup(stripped).unescape() d...
StarcoderdataPython
9660320
#! /usr/bin/env python # A rather specialized script to make sure that a symbolic link named # RCS exists pointing to a real RCS directory in a parallel tree # referenced as RCStree in an ancestor directory. # (I use this because I like my RCS files to reside on a physically # different machine). import os def main(...
StarcoderdataPython
8138739
<filename>server-socket.py<gh_stars>0 import socket import mongoconn as CONN import json s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ip='192.168.1.103' s.bind((ip,1238)) s.listen(2) while True: clientsocket, address = s.accept() clientsocket.send(bytes("connection established","utf-8")) cliente = ...
StarcoderdataPython
11275481
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license. """ import logging import ujson as json from urllib.parse import urlparse from django.conf import settings from rest_framework.exceptions import Valid...
StarcoderdataPython
3576601
""" AERoot main module """ from enum import IntEnum, auto from aeroot.avd import Avd, AVDError, AmbiguousProcessNameError class ProcessNotRunningError(Exception): pass class AERootError(Exception): pass class Mode(IntEnum): PID = auto() NAME = auto() class AERoot: def __init__(self, options): ...
StarcoderdataPython
3467284
<gh_stars>0 from flask import Flask, render_template from flask import request from flask.ext import restful from flask.ext.restful import reqparse from tasks.League import League from tasks.Fixture import Fixture import csv import os app = Flask(__name__) @app.route('/') def index(): print request.url return rende...
StarcoderdataPython
4949164
# Author: <NAME> # Last modified: 5/12/2018 # CONFIG FOR SYSTEM DEVICES # ARDUINO arduino_serial_port = "/dev/ttyACM0" arduino_baud = 9600 arduino_timeout = 0 # RPI CAMERA camera_resolution = (720, 480)
StarcoderdataPython
1928057
# from test import create_app from app import create_app app = create_app()
StarcoderdataPython
3462242
from keras.models import model_from_json import numpy as np from PIL import Image, ImageFilter import PIL.ImageOps from collections import Counter import argparse as ap # fix random seed for reproducibility seed = 7 np.random.seed(seed) # Get the path of the training set parser = ap.ArgumentParser() parser.add_argum...
StarcoderdataPython
1773574
<reponame>jpodivin/pystrand import multiprocessing as mp import uuid from pystrand.populations import BasePopulation from pystrand.selections import RouletteSelection, ElitismSelection, BaseSelection from pystrand.mutations import BaseMutation, PointMutation from pystrand.loggers.csv_logger import CsvLogger from pystr...
StarcoderdataPython
12844977
<reponame>lucaspfigueiredo/elt-pipeline<filename>plugins/operators/vivareal_operator.py import json import logging from hooks.vivareal_hook import VivarealHook from airflow.utils.decorators import apply_defaults from airflow.models.baseoperator import BaseOperator from airflow.providers.amazon.aws.hooks.s3 import S3Ho...
StarcoderdataPython
11253281
<gh_stars>100-1000 # coding=utf-8 from migrate.versioning import api from app.config import SQLALCHEMY_DATABASE_URI from app.config import SQLALCHEMY_MIGRATE_REPO from app import db import os.path if __name__ == '__main__': db.create_all() if not os.path.exists(SQLALCHEMY_MIGRATE_REPO): api.create(SQL...
StarcoderdataPython
3510010
""" This tool returns the R length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order. """ from itertools import combinations Sk = input().split() S = Sk[0] k = int(Sk[1]...
StarcoderdataPython
6658544
<reponame>twisted/imaginary # -*- test-case-name: imaginary.test.test_language -*- """ Textual formatting for game objects. """ import types from string import Formatter import attr from zope.interface import implements, implementer from twisted.python.components import registerAdapter from imaginary import iimag...
StarcoderdataPython
4919790
"""This module provides auth views.""" import uuid from http import HTTPStatus from aiohttp import web from aiojobs.aiohttp import spawn from aiohttp_jinja2 import render_template from app.cache import ( cache, RESET_PASSWORD_CACHE_KEY, RESET_PASSWORD_CACHE_EXPIRE, CHANGE_EMAIL_CACHE_KEY, CHANGE_...
StarcoderdataPython
1903492
from django.contrib import admin from .models import Balance, User # Register your models here. admin.site.register(User) admin.site.register(Balance)
StarcoderdataPython
6687266
<reponame>justnclrk/Python from flask import Flask, render_template, redirect, request, session, flash import re EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') app = Flask(__name__) app.secret_key = 'KeepItSecretKeepItSafe' @app.route('/') def reg(): return render_template('index.html'...
StarcoderdataPython
1956302
# -*- coding: utf-8 -*- import torch import torch.onnx import torch.onnx.symbolic_helper import torch.onnx.utils import torch.nn as nn import numpy as np from collections import OrderedDict from . import register from . import mask_utils from . import function_module from typing import Dict, List from torchpruner.op...
StarcoderdataPython
6413377
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-29 06:03 import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [("blog", "0003_auto_20170926_0641")] operations = [ migrations.AddField( model_na...
StarcoderdataPython
3457718
# 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 writing, software # distributed under t...
StarcoderdataPython
397878
# -*- coding: utf-8 -*- """ Created on Wed Jun 14 10:05:36 2017 @author: jel2 """ import pandas as pd #### this version resets the index of X in the returned table def getSubtable(X,dictColumn='DETAILS'): X=X.reset_index() t=list(X) t.remove(dictColumn) return(X[t].join(pd.DataFrame.fro...
StarcoderdataPython
1712286
<reponame>sieniven/spot-it-3d import cv2 import math import numpy as np import time import queue from camera_stabilizer import stabilize_frame from camera_stabilizer import Camera from filterpy.kalman import KalmanFilter from filterpy.common import Q_discrete_white_noise from scipy.spatial import distance from scipy.o...
StarcoderdataPython
186967
<reponame>sarthakeddy/Codeforces-Profile-Viewer import requests import json import xlsxwriter c=0 while True: if c==0: cf_id=input("Enter your codeforces id : ") c+=1 else: cf_id=input("Enter your codeforces id again\n") link='https://www.codeforces.com/profile/'+cf_id check=requests.get(link) display="INV...
StarcoderdataPython
4955635
# AST tree class Node: def __init__(self, value): self.value = value self.children = [] tree = Node('A') tree.children.append(Node('B')) tree.children.append(Node('C')) def print_node_value(value): print(value) def visit(node, handle_node): handle_node(node.value) for child in node....
StarcoderdataPython
9672375
#!/usr/bin/python3 # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file import os,sys,re from waflib import Options,TaskGen,Task,Utils from waflib.TaskGen import feature,after_method @feature('msgfmt') def apply_msgfmt(self): for lang in self.to_list...
StarcoderdataPython
11347539
<reponame>jianershi/algorithm<gh_stars>1-10 """ 442. Implement Trie (Prefix Tree) https://www.lintcode.com/problem/implement-trie-prefix-tree/description answer modified based on 令狐冲's answer https://www.jiuzhang.com/solution/implement-trie-prefix-tree/ """ class TrieNode: def __init__(self): self.children ...
StarcoderdataPython
3475729
import json import pathlib import typing from functools import lru_cache from fastapi import FastAPI, Request from fastapi.openapi.utils import get_openapi from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.responses import PlainTextResponse, Response from . import __version__ as ...
StarcoderdataPython
1832056
<gh_stars>1-10 from __future__ import absolute_import from __future__ import division from __future__ import print_function from builtins import zip from builtins import range from builtins import object import numpy as np from . import crystal def bijk_to_coord(prim,bijk,sd=(True,True,True)): """Convert the bij...
StarcoderdataPython
107626
<gh_stars>0 #!/usr/bin/env python """rundevel.py -- script to run current code Usage: [interpreter] rundevel.py [run|rebot] [options] [arguments] Examples: ./rundevel.py --name Example tests.txt # run with python ./rundevel.py run --name Example tests.txt # same as above jython rundevel.py ...
StarcoderdataPython
4924113
import json from pathlib import Path import pandas as pd def spi_hierarchy(): 'data/spi2019.xlsx の最後のシートに記載されているSPI指標の定義から階層構造を構成する' def rec(defs, keys): indices = list(defs.keys())[:3] dimensions = dict() for _, row in defs.iterrows(): if pd.notna(row).all(): ...
StarcoderdataPython
3542748
<gh_stars>1-10 def florida_getEnhancedLocation(location): return add_state(location, "Florida")
StarcoderdataPython
8124601
class Circulo: def calcular_area(self, pi, raio): return pi*raio*raio def calcular_perimetro(self, pi, raio): return 2*pi*raio circulo = Circulo() print(circulo.calcular_area(3.14, 10)) print(circulo.calcular_perimetro(3.14, 10))
StarcoderdataPython
136140
<reponame>yanshengjia/algorithm<gh_stars>10-100 """ Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n) complexity. Example: Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]....
StarcoderdataPython
5173800
<gh_stars>0 import socket s= socket.socket() # connect to the host print("Socket Name: " ,socket.gethostname()) s.connect((socket.gethostname(),12346)) print("Connection created : ",s.recv(512)) while True: data = s.recv(512) print('data long is ',len(data)) print(data.decode(),end='\n') if (len(data) < 1): break...
StarcoderdataPython
6691611
<reponame>langgithub/LangSpider #!/usr/bin/env python3 # -*- coding:utf-8 -*- # author:yuanlang # creat_time: 2020/7/16 上午10:34 # file: utils.py import hashlib import click def get_redis_task_key_name(site_type, crawl_type): return '{}_{}_tasks'.format(site_type, crawl_type) def get_headers_from_text(text): ...
StarcoderdataPython
160701
<reponame>Mopolino8/pylbm # Authors: # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD 3 clause """ Example of a two velocities scheme for the shallow water system d_t(h) + d_x(q) = 0, t > 0, 0 < x < 1, d_t(q) + d_x(q^2/h+gh^2/2) = 0, t > 0, 0 < x < 1, """ import sympy as sp import pylbm # pylin...
StarcoderdataPython
6596093
t=int(input()) while(t>0): l=[] l1=[] j=[] j1=[] t=t-1 d=int(input()) while(d>0): d=d-1 day,p=map(int,input().split()) l.append(day) j.append(p) q=int(input()) while(q>0): l2=l.copy() j2=j.copy() q=q-1 ...
StarcoderdataPython
12855106
<filename>server/tests/test_api.py # @file # # FadZmaq Project # Professional Computing. Semester 2 2019 # # Copyright FadZmaq © 2019 All rights reserved. # @author <NAME> <EMAIL> # @author <NAME> <EMAIL> import json # Tests that the server is up at all. def test_index(client): response = clie...
StarcoderdataPython
6431711
from __future__ import unicode_literals import pytest from aocd.models import User @pytest.fixture(autouse=True) def mocked_sleep(mocker): no_sleep_till_brooklyn = mocker.patch("time.sleep") return no_sleep_till_brooklyn @pytest.fixture def aocd_dir(tmp_path): data_dir = tmp_path / ".config" / "aocd" ...
StarcoderdataPython
11330616
<gh_stars>1-10 # VQC implemented in pennylane. import os import json import pennylane as pnl from pennylane import numpy as np import autograd.numpy as anp from pennylane.optimize import AdamOptimizer import matplotlib.pyplot as plt from . import feature_maps as fm from . import variational_forms as vf from .terminal...
StarcoderdataPython
1977456
<filename>api/app/games/codenames/events/utils.py """ This module contains utility functions required by the Codenames game event handlers. """ import functools import json import random from flask_socketio import emit from flask_login import current_user from sqlalchemy import func from app import db from app.game...
StarcoderdataPython
6599728
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'measurement.ui' # # Created by: PyQt5 UI code generator 5.7.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Measurement(object): def setupUi(self, Measurement): ...
StarcoderdataPython
3360394
<filename>server/pythonScripts/subscriber.py<gh_stars>0 import paho.mqtt.client as paho import paramiko import json broker = "localhost" topic = "new" port = 1883 def on_connect(client, userdata, flags, rc): # The callback for when the client connects to the broker #print("Connected with result code {0}"....
StarcoderdataPython
1974037
import torch import torchvision import torch.nn as nn import torch.nn.functional as F class Autoencoder(nn.Module): def __init__(self): super(Autoencoder, self).__init__() self.encoder = nn.Sequential( nn.Conv2d(3, 6, kernel_size=5), nn.ReLU(True), nn.Conv2d(6,...
StarcoderdataPython
3426501
<reponame>haribommi/vaapi-fits ### ### Copyright (C) 2018-2019 Intel Corporation ### ### SPDX-License-Identifier: BSD-3-Clause ### from ....lib import * from ..util import * from .encoder import EncoderTest spec = load_test_spec("jpeg", "encode") class JPEGEncoderTest(EncoderTest): def before(self): vars(self)...
StarcoderdataPython
53447
#GamePlay.py #<NAME>, <NAME>, <NAME> """This module contains the functions needed to support pentago gameplay. A pentago gameboard is represented by a 6x6 2D array. Each location on the board is initialized to "" and is set to 0 or 1 when the player or the AI respectively places a marble on that location. Each ar...
StarcoderdataPython
3515674
<reponame>Doomsk/QChat import abc import random import time from qchat.device import LeadDevice, FollowDevice from qchat.ecc import ECC_Golay from qchat.log import QChatLogger from qchat.messages import PTCLMessage, BB84Message, SPDSMessage, DQKDMessage LEADER_ROLE = 0 FOLLOW_ROLE = 1 IDLE_TIMEOUT = 60 BYTE_LEN = 8 RO...
StarcoderdataPython
3259207
<reponame>klarh/geometric_algebra_attention<filename>geometric_algebra_attention/keras/Multivector2MultivectorAttention.py from tensorflow import keras from .. import base from .MultivectorAttention import MultivectorAttention class Multivector2MultivectorAttention(base.Multivector2MultivectorAttention, MultivectorAt...
StarcoderdataPython
1928577
import os from dotenv import load_dotenv import psycopg2 import traceback load_dotenv("./.env.local") con = cur = db = None if 'DATABASE_URI' in os.environ: DATABASE_URL = os.environ['DATABASE_URI'] else: raise ValueError('Env Var not found!') def connect(): global con, cur, db try: con = p...
StarcoderdataPython
1679817
<gh_stars>0 #!/usr/bin/python # -*- coding: utf-8 -*- # # author <NAME> <EMAIL> # date 2015/11/27 import baseHandler import tornado.web from modules.db import db import constants import json """ determine whether the specified category is exist """ class IsCategoryExistHandler(baseHandler.RequestHandler): @tornad...
StarcoderdataPython
5083621
<reponame>aherrera1721/hyhelper<filename>HyHelper/__init__.py from .HyHelper_traj import * from .HyHelper_plot import * from .HyHelper_filters import * from .AutoSplit import * print('All files imported successfully. Welcome to HyHelper!')
StarcoderdataPython
5063851
import pika import datetime from PikaBus.abstractions.AbstractPikaBus import AbstractPikaBus from PikaBus.PikaBusSetup import PikaBusSetup def MessageHandlerMethod(**kwargs): """ A message handler method may simply be a method with som **kwargs. The **kwargs will be given all incoming pipeline data, the b...
StarcoderdataPython
3251557
<filename>end_to_end_tests/golden-record-custom/custom_e2e/__init__.py<gh_stars>0 """ A client library for accessing My Test API """ from .wrapper import MyTestAPIClient, SyncMyTestAPIClient
StarcoderdataPython
287583
<reponame>tagr-dev/tagr import unittest import pandas as pd from tagr.tagging.artifacts import Tagr class TaggingTest(unittest.TestCase): def __init__(self, *args, **kwargs): self.tag = Tagr() super().__init__(*args, **kwargs) def test_artfact_is_returned(self): # Arrange tes...
StarcoderdataPython
349295
<filename>test/solution_tests/chk/test_pricing_service.py from lib.solutions.CHK.pricing_service import PricingService from lib.solutions.CHK.sku_service import SkuService from unittest.mock import MagicMock from pytest import mark # getting a bit like an integration test here @mark.parametrize("basket_string,expected...
StarcoderdataPython
5045743
import torch import torch.nn.functional as f from torch import nn import numpy as np import pandas as pd class Critic(nn.Module): def __init__(self, input_dim): super(Critic, self).__init__() self._input_dim = input_dim # self.dense1 = nn.Linear(109, 256) self.dense1 = nn.Linear(sel...
StarcoderdataPython
3352359
<gh_stars>1-10 from unittest.mock import MagicMock, call, ANY import pytest from openeo.internal.process_graph_visitor import ProcessGraphVisitor def test_visit_node(): node = { "process_id": "cos", "arguments": {"x": {"from_argument": "data"}} } visitor = ProcessGraphVisitor() visit...
StarcoderdataPython
11202024
import strax import numpy as np from straxen.common import pax_file, get_resource, get_elife, first_sr1_run from straxen.itp_map import InterpolatingMap export, __all__ = strax.exporter() @export @strax.takes_config( strax.Option('trigger_min_area', default=100, help='Peaks must have more area ...
StarcoderdataPython
8107745
from cassandra.cqlengine import columns from cassandra.cqlengine.models import Model class SampleCoverage(Model): __keyspace__ = 'coveragestore' sample = columns.Text(primary_key=True, partition_key=True) amplicon = columns.Text(primary_key=True) run_id = columns.Text(primary_key=True) library_na...
StarcoderdataPython
3375805
""" This script demonstrates the following: - How to scan a target host for known ports and other port ranges from 0 - 65536 My primary focus while coding this script is LEARN how to program in Python. It is NOT my intention to cause any harm to 3rd parties (people and/or organizations) Example: python po...
StarcoderdataPython
1696107
"""A package for computing overall grades in courses @ UCSD.""" from .io import ( read_egrades_roster, read_canvas, read_gradescope, write_canvas_grades, write_egrades, ) from .gradebook import Gradebook, Assignments from .scales import ( DEFAULT_SCALE, ROUNDED_DEFAULT_SCALE, map_scores...
StarcoderdataPython
9603050
import sys def printing(count,num): print(num," *",count," =",num*count) def main(): num=sys.argv[1] num=int(num) til=int(sys.argv[2]) count=1 while(count<=til): printing(count,num) count=count+1 #main starts from here main()
StarcoderdataPython
4841285
<gh_stars>1-10 '''Definición de esquemas de JSON.''' esquema_alumno = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "Nombre": {"type": "string", "minLength":1, }, "Primer Apellido": {"type": "string", ...
StarcoderdataPython
181224
<gh_stars>1-10 """Data structures to represent server information.""" from ark_rcon.datastructures.players import Players from ark_rcon.datastructures.logline import LogLine __all__ = ['Players', 'LogLine']
StarcoderdataPython
70239
<filename>2021/07.py from statistics import mean, median import math with open("input.txt") as fin: positions = [int(i) for i in fin.read().split(",")] def p1(): m = median(positions) return sum(abs(m - x) for x in positions) def p2(): m = mean(positions) res = float("inf") for m in range(...
StarcoderdataPython
8093325
<reponame>mkazmier/torchmtlr import pytest import torch import numpy as np from torchmtlr.utils import encode_survival, make_time_bins bins = torch.arange(1, 5, dtype=torch.float) testdata = [ (3., 1, torch.tensor([0, 0, 0, 1, 0]), bins), (2., 0, torch.tensor([0, 0, 1, 1, 1]), bins), (0., 1, torch.tensor...
StarcoderdataPython
3303610
"""This module purse VOH website to get the contents for podcast feed. """ import collections from urllib.parse import urljoin, urlparse, urlunparse import datetime import re import pytz import requests from bs4 import BeautifulSoup from podcasts_utils import get_true_url def get_articles_from_html(soup, url, no_it...
StarcoderdataPython
4879504
<gh_stars>1-10 import os, zipfile, random, string import fnmatch import numpy as np from datetime import datetime __all__ = ['dayends_from_timestamp', 'in_area', 'greate_circle_distance', 'randstr', 'zipdir', 'zippylib', 'normalized'] try: from matplotlib.patches import FancyArrowPatch, Circle __a...
StarcoderdataPython
1715807
import collections import logging import pprint class PprintArgsFilter(logging.Filter): '''Use pprint/pformat to pretty the log message args ie, log.debug("foo: %s", foo) this will pformat the value of the foo object. ''' def __init__(self, name="", defaults=None): super(PprintArgsFilter...
StarcoderdataPython
3576727
<reponame>francois-vincent/simply # encoding: utf-8 import os.path from simply import ROOTDIR from simply.backends import docker, get_class from simply.utils import ConfAttrDict def test_version(): version = docker.docker_version() assert len(version.split('.')) == 3 def test_build(): docker.image_del...
StarcoderdataPython
6411243
# Generated by Django 2.0.10 on 2019-01-31 13:28 import articles.models from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('articles', '0...
StarcoderdataPython
4957032
# Library Imports import os import gym import numpy as np from GAIL import Agent abs_path = os.getcwd() # Load the Environment env = gym.make('CartPole-v1') # Load the Expert Dataset and Agent expert_obs = np.load( abs_path+'/Expert/data/expert_DatasetStates.npy', allow_pickle=False) expert_actions = np.load( ...
StarcoderdataPython
8132090
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
StarcoderdataPython
3294671
<reponame>stfung77/django-polaris """ This module tests the `/deposit` endpoint. Celery tasks are called synchronously. Horizon calls are mocked for speed and correctness. """ import json from unittest.mock import patch import jwt import time import pytest from stellar_sdk import Keypair, MuxedAccount from polaris i...
StarcoderdataPython
4827564
<filename>src/tests/functional/orga/test_auth.py import pytest from django.urls import reverse @pytest.mark.django_db def test_orga_successful_login(client, user, template_patch): user.set_password('<PASSWORD>') user.save() response = client.post(reverse('orga:login'), data={'username': user.nick, 'passwo...
StarcoderdataPython
8038332
# import Kratos from KratosMultiphysics import * from KratosMultiphysics.FSIApplication import * # Import Kratos "wrapper" for unittests import KratosMultiphysics.KratosUnittest as KratosUnittest # Import the tests o test_classes to create the suits ## SMALL TESTS from convergence_accelerator_test import ConvergenceA...
StarcoderdataPython
6424075
<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- #__Refer___ : https://www.exploit-db.com/exploits/38901/ import re def assign(service, arg): if service == "php_utility_belt": return True, arg def audit(arg): url = arg+'ajax.php' POST_Data = "code=fwrite(fopen('shell.php'...
StarcoderdataPython
12807624
<reponame>UCD4IDS/sage "Plotting utilities" # **************************************************************************** # Distributed under the terms of the GNU General Public License (GPL) # # This code is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied w...
StarcoderdataPython
171280
<gh_stars>1-10 # -*- coding: utf-8 -*- from __future__ import unicode_literals from signbank.settings.base import * # settings.base imports settings_secret # The following settings are defined in settings_secret: # SECRET_KEY, ADMINS, DATABASES, EMAIL_HOST, EMAIL_PORT, DEFAULT_FROM_EMAIL # Debug should be True in dev...
StarcoderdataPython
3383559
<gh_stars>0 import os from os import listdir from os.path import join, isdir, basename import sys base_dir = 'CTFS-2021' prefix = '/ctf-writeups-2021' ctf_path = sys.argv[1] full_path = join(prefix,base_dir,ctf_path) def link(path): full_path = join(prefix,base_dir,path) return f'## [{basename(path)}]({full_...
StarcoderdataPython
11259082
from selenium import webdriver import pickle import time import os """ options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument("--test-type") options.binary_location = "/" """ profile = webdriver.FirefoxProfile() profile.set_preference('browser.download.folderList', ...
StarcoderdataPython
6440458
import os import logging import codecs __log_dir='/home/aistudio/logs' train_params = { "img_size": [3,224,224], "class_num": -1, "image_num": -1, "label_dict":{}, "data_dir": '/home/aistudio/data/data504/vegetables', 'train_list': 'train_labels.txt', 'eval_list': 'eval_labels.txt', 'l...
StarcoderdataPython
1979075
from typing import ClassVar, TypeVar from typing_extensions import Self from dubious.discord import api, enums, make from dubious.Interaction import Ixn, makeIxn from dubious.Machines import Check, Command, Handle from dubious.Pory import Chip, Pory class Pory2(Pory): """ A collection of `Command`-wrapped met...
StarcoderdataPython
3383413
<filename>tests/s3_manager_test.py<gh_stars>0 import pytest from logger import logger from ..manager.s3_manager import download_from_s3, upload_to_s3_repo_sofr @pytest.mark.skip(reason="temp") def test_download_from_s3(): download_path = "/tmp/package.zip" s3_path = "s3://eternity02.deployment/lambda/data-coll...
StarcoderdataPython
11285478
"""Implements and manages all sub-problems""" import logging from abc import ABC import numpy as np from pyomo.core import ConcreteModel, Param, RangeSet, Var, ConstraintList, \ Objective, minimize, maximize from pyomo.core.expr.visitor import identify_variables, replace_expressions from pyomo.environ import Bina...
StarcoderdataPython
3469218
<filename>src/simplelayout/cli/__init__.py<gh_stars>0 from simplelayout.cli.cli_generate import get_options # noqa
StarcoderdataPython
1977173
from discord.ext import commands import discord voice_setting = """ `::voice <音声の種類(A,B,C,Dのいずれか)>` で音声の種類を変更できます。 `::speed <スピード>` でスピードの変更ができます。デフォルトは1.0です。 `::pitch <ピッチ>` でピッチの変更ができます。デフォルトは0.0です。 """ def yomiage(a): return '読み上げる' if a else '読み上げない' class VoiceSetting(commands.Cog): def __init__(self, bot...
StarcoderdataPython
8095714
# flake8: noqa from __future__ import annotations def check_pickle(xThing, lTested = None): # https://stackoverflow.com/a/50049341/545637 # FIXME: clean up an use exceptions import pickle lTested = [] if lTested is None else lTested if id(xThing) in lTested: return lTested sType = ty...
StarcoderdataPython
3202695
import time from functools import lru_cache from trie import PrefixTree class NumberConverter(object): def __init__(self): self.trie = PrefixTree() with open('words_en.txt') as file: lines = [line.rstrip('\n') for line in file] for line in lines: self.trie...
StarcoderdataPython
1812996
<filename>miku/http.py import asyncio from typing import Any, Dict, Union import aiohttp from .query import Query, QueryFields, QueryOperation from .fields import * from .media import Anime, Manga, Media from .character import Character from .paginator import Paginator from .user import User from .image import Image f...
StarcoderdataPython
6416880
def test_contour_levels(app, data_image): viewer = app.imshow(data=data_image) widget_state = viewer._layout_layer_options.layers[0]['layer_panel'] layer_state = widget_state.layer_state layer_state.level_mode = "Custom" widget_state.c_levels_txt = '1e2, 1e3, 0.1, .1' assert layer_state.levels ...
StarcoderdataPython
1771662
# Copyright 2020 The Private Cardinality Estimation Framework 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 b...
StarcoderdataPython
3283452
<filename>model.py from __future__ import print_function import matplotlib as mpl mpl.use('Agg') # Don't open display import matplotlib.pyplot as plt import numpy as np import io import logging import graphlab as gl from datetime import datetime from termcolor import colored, cprint import mailer import os import json...
StarcoderdataPython
3236005
# -*- coding: utf-8 -*- import sys import numpy as np import tables import cPickle as pickle from Dpmm import DPMM from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser ### Job submit script for Gibbs sampling on reference population model # read arguments p = ArgumentParser(formatter_class=ArgumentDefau...
StarcoderdataPython
1644514
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import numpy.testing as npt import pytest import pytest_check as check from astropop.image_processing.imarith import imarith from astropop.framedata import FrameData # TODO: Test with None FrameData # TODO: Test with None scalar valu...
StarcoderdataPython
5112130
<filename>examples/blink_example.py from pywire import * counter = Signal(26) def increment(x): return x+1 counter.drive(increment, args=counter) led1 = Signal(1, io="out", port="P134") def blink(slow_clock): if slow_clock > 2**25: return 1 else: return 0 led1.drive(blink, args=(co...
StarcoderdataPython