id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
3298701 | from datetime import datetime, timedelta
from enum import Enum, auto
STATUS_MESSAGE_TIMEOUT = timedelta(seconds=5)
class WorkerState(Enum):
"""
The state of a worker (i.e. a file-writer instance).
"""
IDLE = auto()
WRITING = auto()
UNKNOWN = auto()
UNAVAILABLE = auto()
class WorkerStat... | StarcoderdataPython |
6453467 | <filename>Vertical Sticks.py
# -*- coding: utf-8 -*-
"""
Problem Statement
Given an array of integers Y=[y1,y2,…,yn], we have n line segments, such that, the endpoints of ith segment are (i,0)
and (i,yi). Imagine that from the top of each segment a horizontal ray is shot to the left, and this ray stops when it
touches... | StarcoderdataPython |
11202781 | """Module for running PyVVO. This module is run by the platform (see
platform_config.json). The program expects two arguments: simulation ID
and simulation request.
Relevant documentation from GridAPPS-D can be found `here
<https://gridappsd.readthedocs.io/en/latest/using_gridappsd/index.html#id7>`__.
Since the link I... | StarcoderdataPython |
12841390 | from typing import Type
from django.db.migrations.operations.base import Operation
from django.db.models import Model
class AddAuditOperation(Operation):
reduces_to_sql = True
reversible = True
enabled = True
def __init__(self, model_name, audit_rows=True, audit_text=False, excluded=('created', 'mod... | StarcoderdataPython |
233677 | <gh_stars>1-10
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2021- QuOCS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#... | StarcoderdataPython |
5029845 | """
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
import sys
import logging
import six
try:
from json.decoder import JSONDecodeError
except ImportError:
JSONDecodeError = ValueError
from yaml.parser import ParserError, ScannerError
from yaml import YA... | StarcoderdataPython |
371817 | import cpg_scpi
from time import sleep
def main():
cpg = cpg_scpi.CircuitPlayground()
cpg.test_ledDemo()
# cpg.test_led()
# value = cpg.acc()
# print(f'acc: {value}')
# value = cpg.light()
# print(f'light: {value}')
cpg.close()
print()
print(f'Closed connection to CPG. {cpg.is... | StarcoderdataPython |
5160669 | <reponame>mvinyard/python-developer-kit
__module_name__ = "_dynamical_import_of_function_from_string.py"
__author__ = ", ".join(["<NAME>"])
__email__ = ", ".join(["<EMAIL>",])
# import packages #
# --------------- #
from importlib import import_module
def _dynamical_import_of_function_from_string(
package, mod... | StarcoderdataPython |
396917 | # Copyright (c) 2013 Mirantis 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 or agreed to in writi... | StarcoderdataPython |
11218810 | <gh_stars>1-10
from output.models.ms_data.identity_constraint.id_z006_xsd.id_z006 import (
AType,
BType,
BsType,
CType,
CsType,
RType,
Root,
)
__all__ = [
"AType",
"BType",
"BsType",
"CType",
"CsType",
"RType",
"Root",
]
| StarcoderdataPython |
9639700 | import os
import platform
from distutils.core import setup, Extension
virtualenv_path = os.environ.get('VIRTUAL_ENV')
include_dirs = filter(None, [os.environ.get('INCLUDE_DIRS')])
library_dirs = filter(None, [os.environ.get('LIBRARY_DIRS')])
if virtualenv_path:
include_dirs.append('%s/include' % virtualenv_path)... | StarcoderdataPython |
87498 | <filename>projects/es.um.unosql.subtypes/python/src/charts/GanttChart.py
import numpy as np
import matplotlib.pyplot as pyplot
import matplotlib.font_manager as font_manager
from matplotlib.dates import WEEKLY,MONTHLY, DateFormatter, rrulewrapper, RRuleLocator
from .ChartData import ChartData
class GanttChart:
__c... | StarcoderdataPython |
11364865 | # Pulls all the other functions together to make magic!
#
# Author: <NAME> Last modified by <NAME>
# Date: 26 November 2018
# Python version: 3.7
import os
from onsset import *
import pandas as pd
import tkinter as tk
from tkinter import filedialog, messagebox
root = tk.Tk()
root.withdraw()
root.attributes("-topmost"... | StarcoderdataPython |
3248148 | <reponame>derekray311511/permatrack
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
import numpy as np
import torch
import json
import cv2
import os
import math
from ..video_dataset import VideoDataset
class PDTracking(Video... | StarcoderdataPython |
1771344 | <filename>tlux/approximate/apos/test/compare_versions.py
import fmodpy
import os
import numpy as np
_this_dir = os.path.dirname(os.path.abspath(__file__))
# Build a class that contains pointers to the model internals, allowing
# python attribute access to all of the different components of the models.
class AposModel:... | StarcoderdataPython |
4957753 | <filename>cloud/lab2/push.py
import boto3
from botocore.exceptions import NoCredentialsError
import time
import csv
def upload_to_aws(local_file, bucket, s3_file):
s3 = boto3.client('s3')
try:
s3.upload_file(local_file, bucket, s3_file)
#print("Upload Successful")
return True
... | StarcoderdataPython |
12828985 | <reponame>sreichl/genomic_region_enrichment
#!/bin/env python
import pandas as pd
import pickle
import os
import numpy as np
import gseapy as gp
# utils for manual odds ratio calculation
def overlap_converter(overlap_str, bg_n, gene_list_n):
overlap_n, gene_set_n = str(overlap_str).split('/')
return odds_rati... | StarcoderdataPython |
11308513 | import tweepy
import sqlite3
import os
import tempfile
from PIL import Image
import twitter_credentials
auth = tweepy.OAuthHandler(twitter_credentials.consumer_key, twitter_credentials.consumer_secret)
auth.set_access_token(twitter_credentials.access_token_key, twitter_credentials.access_token_secret)
api = tweepy.A... | StarcoderdataPython |
1743354 | <filename>spinnaker_swagger_client/api/task_controller_api.py<gh_stars>0
# coding: utf-8
"""
Spinnaker API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/... | StarcoderdataPython |
6693929 | <reponame>CloudI/CloudI<filename>src/tests/messaging/messaging.py<gh_stars>100-1000
#!/usr/bin/env python
#-*-Mode:python;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*-
# ex: set ft=python fenc=utf-8 sts=4 ts=4 sw=4 et nomod:
#
# MIT License
#
# Copyright (c) 2012-2021 <NAME> <<EMAIL>>
#
# Permission ... | StarcoderdataPython |
1841711 | <filename>beartype_test/a00_unit/a00_util/mod/test_utilmoddeprecate.py
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **Python module deprecation** unit tests.
This... | StarcoderdataPython |
92373 | from .binarytrees import *
| StarcoderdataPython |
1944884 | <gh_stars>1-10
from django.core.exceptions import ValidationError
from rest_framework import serializers
from .models import Order
class OrderSerializer(serializers.ModelSerializer):
"""Serializer definition for Order."""
status = serializers.CharField(source="get_status_display", read_only=True)
class ... | StarcoderdataPython |
1898675 | <filename>stats_bbox_tr.py
import os
from os import listdir
from os.path import join
from bbox_tr import bbox_tr_get_wh
in_dir = r'E:\SourceCode\Python\TRD\DOTA'
out_dir = r'E:\SourceCode\Python\TRD'
cls_stats = {}
valid_objs = 0
total_objs = 0
for i in os.listdir(in_dir):
image_id,image_ext = os.pa... | StarcoderdataPython |
179100 | #!/usr/bin/python3.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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 app... | StarcoderdataPython |
11288249 | #%%
import os
import numpy as np
import matplotlib.pyplot as plt
import json
from soil_classifier.dataset import Landsat
from soil_classifier.models import minimals as models_lib
from soil_classifier.utils import fpga_report, load_model
from soil_classifier.utils import model_checkout, ip_checkout
from soil_classifi... | StarcoderdataPython |
2409 | from __future__ import (division)
from pomegranate import *
from pomegranate.io import DataGenerator
from pomegranate.io import DataFrameGenerator
from nose.tools import with_setup
from nose.tools import assert_almost_equal
from nose.tools import assert_equal
from nose.tools import assert_not_equal
from nose.tools im... | StarcoderdataPython |
1878965 | #!env python3
from flask import Flask, request, redirect
from hashlib import sha256
import hmac
import base64
import time
import urllib
# allow for relative importing if run directly
if __name__ == "__main__":
from config import secrets, reports, listen_port
else:
from .config import secrets, reports, listen_p... | StarcoderdataPython |
4914264 | import willie, sys, json
from os.path import expanduser
def setup(bot):
global twitchlist
with open("{0}/.willie/conf-module/streams.json".format(expanduser("~"))) as f: # loads streams.json from USER_HOME/.willie/conf-module/
twitchlist = json.load(f)
def lookup_twitch():
global twitchlist
tw... | StarcoderdataPython |
3554338 | <reponame>cyrilbois/PFNET.py<gh_stars>1-10
#***************************************************#
# This file is part of PFNET. #
# #
# Copyright (c) 2015-2017, <NAME>. #
# #
# PFNET is released und... | StarcoderdataPython |
1653995 | # -------------------------------------------------------------------------
#
# Part of the CodeChecker project, under the Apache License v2.0 with
# LLVM Exceptions. See LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# ---------------------------------------------------... | StarcoderdataPython |
381610 | import typing
import sys
import numpy as np
import numba as nb
from numba import njit, i8
@njit
def seg_f(
a: int,
b: int,
) -> int:
if a >= b: return a
return b
@njit
def seg_e() -> int:
return 0
@njit
def build_seg(
raw: np.array,
) -> np.array:
n = raw.size
a = np.zeros(
n << 1,
d... | StarcoderdataPython |
8159608 | import os
import math
import time
import cv2 as cv
import numpy as np
from age_gender_ssrnet.SSRNET_model import SSR_net_general, SSR_net
from time import sleep
# Desired width and height to process video.
# Typically it should be smaller than original video frame
# as smaller size significantly speeds up processing a... | StarcoderdataPython |
238135 | from flask import Blueprint
user_blueprint = Blueprint('user', __name__, template_folder='templates')
from . import routes | StarcoderdataPython |
3393583 | <reponame>dualtob/FaceIDLight<gh_stars>1-10
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, includi... | StarcoderdataPython |
4962561 | <reponame>apourchot/to_share_or_not_to_share<filename>models/nasbench_201/graph_sampler.py
import pickle
import numpy as np
class GraphSampler(object):
"""
Sample architectures uniformly from available dataset
"""
def __init__(self, dataset_path, **kwargs):
super(GraphSampler, self).__init__(... | StarcoderdataPython |
141505 | #!/usr/bin/python
# coding=utf-8
##########################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from diamond.collector import Collector
from solr import SolrColl... | StarcoderdataPython |
8056765 | <gh_stars>10-100
import jsonschema
import kayvee
import logging
schema = {
"type": "object",
"name": "Volume backup schedule",
"properties": {
"max_snapshots": {"type": "number"},
"interval": {"type": "string"},
"name": {"type": "string"},
},
"additionalPropertie... | StarcoderdataPython |
3326336 | from unittest.mock import patch, mock_open
from django.test import TestCase
# Import module
from backend.file_manager import *
METADATA_EXAMPLE = "59°23'19.2\"N 17°55'35.4\"E (59.388668, 17.926501)\n2018-09-06 15:45:59.603 " \
"(2018-09-06 15:45:59)\n(Test camera name)"
class GetSourceFolde... | StarcoderdataPython |
3218619 | <reponame>davilamds/py_dss_interface<filename>tests/py_dss_interface/test_reclosers.py
# -*- coding: utf-8 -*-
# @Time : 09/07/2021 02:16 AM
# @Author : <NAME>
# @Email : <EMAIL>
# @File : test_reclosers.py
# @Software : VSCode
import pytest
class TestReclosers13Bus:
@pytest.fixture(autouse=True)
... | StarcoderdataPython |
8078907 | import os
import numpy as np
import torch
import torch.nn as nn
try:
dictionary = np.load('grid_embedding.npy').item()
print "[Dictionary] Loading Existing Embedding Dictionary"
except IOError as e:
dictionary = {'new':-1}
print "[Dictionary] Building New Word Embedding Dictionary"
#word = ['hello','world','e... | StarcoderdataPython |
6444555 | """
Content rendering functionality
Note that this module is designed to imitate the front end behavior as
implemented in Markdown.Sanitizer.js.
"""
import re
import markdown
# These patterns could be more flexible about things like attributes and
# whitespace, but this is imitating Markdown.Sanitizer.js, so it us... | StarcoderdataPython |
5034476 | from django.test import TestCase
from django.conf import settings
import json
import time
import os
from newt.tests import MyTestClient, newt_base_url, login
try:
from newt.local_settings import test_machine as machine
except ImportError:
machine = "localhost"
class JobTests(TestCase):
fixtures = ["test_f... | StarcoderdataPython |
384567 | import numpy as np
def convmat2D(A, P, Q):
'''
:param A: input is currently whatever the real space representation of the structure is
:param P: Pspecifies max order in x (so the sum is from -P to P
:param Q: specifies max order in y (so the sum is from -Q to Q
:return:
'''
N = A.shape;
... | StarcoderdataPython |
11314010 | <gh_stars>10-100
#Modified from https://github.com/hvy/chainer-inception-score
import math
import chainer
from chainer import Chain
from chainer import functions as F
from chainer import links as L
from chainer import Variable
from chainer.functions.activation.relu import ReLU
from chainer.functions.pooling.average_po... | StarcoderdataPython |
4967967 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
__pkginfo__ = {}
with open("jinsi/__pkginfo__.py") as fh:
exec(fh.read(), __pkginfo__)
class Info:
version = __pkginfo__.get("version", None)
setuptools.setup(
name="jinsi",
version=Info.version,
author="<NAM... | StarcoderdataPython |
19039 | <reponame>webguru001/Python-Django-Web<filename>Francisco_Trujillo/Assignments/registration/serverre.py
from flask import Flask, render_template, request, redirect, 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 = 'irtndvieurnvi... | StarcoderdataPython |
5175794 | <filename>2nd/generate_1m_numbers.py
# <NAME>,Tzu-Heng's Work
# generate a file with 1,000,000 numbers
# Mailto: <EMAIL>
# Github: github.com/lzhbrian
# Linkedin: linkedin/in/lzhbrian
import random
fp = open('./Numbers.txt','w')
length = 1000000
min_x = 0
max_x = 60000
count = 0
for x in xrange(0,length):
print ... | StarcoderdataPython |
1658189 | from typing import Callable
import numpy as np
from .Wavelet import Wavelet
from .WaveletHelper import inverse_transform
class AbstractWaveletInverseTransform(object):
def __init__(self,
wavelet: Wavelet):
self.wavelet = wavelet
def transform(self,
build_matrix: Cal... | StarcoderdataPython |
1732368 | from base64 import b64encode
from tornado_http_auth import DigestAuthMixin, BasicAuthMixin, auth_required
from tornado.testing import AsyncHTTPTestCase
from tornado.web import Application, RequestHandler
credentials = {
'user1': '<PASSWORD>',
'user2': '<PASSWORD>',
}
class BasicAuthHandler(BasicAuthMixin, ... | StarcoderdataPython |
8184314 | <gh_stars>0
import scipy
import matplotlib.pyplot as plt
import numpy as np
import ahrs
import pandas as pd
import scipy.signal as signal
import scipy.integrate as intg
from numpy import pi
from scipy.fftpack import fft, ifft, dct, idct, dst, idst, fftshift, fftfreq
from numpy import linspace, zeros, array, pi, sin, co... | StarcoderdataPython |
4821269 | import functools
from typing import Any, Callable, Dict, Optional, Union
def skip_invocation(determinator: Optional[Union[str, bool, Callable[[Dict[str, Any], Any], bool]]] = None) -> Union[Callable, None]:
"""
A decorator which allows to skip decorated function's execution if certain conditions are met.
... | StarcoderdataPython |
1778212 | <gh_stars>0
import calendar
import time
for x in range(2000, 2031):
y = calendar.isleap(x)
print(f'YEAR {x} -> LEAP_YEAR = {y}')
for d in calendar.day_name:
print(d)
print('NOW IS', time.ctime())
XLIST = [10, 20, 30, 40]
for x in XLIST:
print(f'x = {x} ...')
time.sleep(5) | StarcoderdataPython |
11375329 | <gh_stars>10-100
# Author: <NAME> <<EMAIL>>
# Copyright (c) 2021 <NAME>
#
# This file is part of Monet.
from ..visualize.util import DEFAULT_PLOTLY_COLORS, DEFAULT_GGPLOT_COLORS
def get_default_cluster_colors(colorscheme: str = None):
cluster_colors = {}
if colorscheme == 'plotly':
numeric_colors = ... | StarcoderdataPython |
3447343 | import numpy as np
from numpy import ndarray
from yacs.config import CfgNode
from albumentations import OneOf, Compose, MotionBlur, MedianBlur, Blur, RandomBrightnessContrast, GaussNoise, \
GridDistortion, Rotate, HorizontalFlip, CoarseDropout, Cutout
from .grid_mask import GridMask
from typing import Union, List, ... | StarcoderdataPython |
3357869 | <filename>BSSN/UIUCBlackHole.py
# This module sets up UIUC Black Hole initial data in terms of
# the variables used in BSSN_RHSs.py
# Authors: <NAME>, zachetie **at** gmail **dot** com
# <NAME>, terrencepierrej **at** gmail **dot** com
# <NAME>
# ## This module sets up initial data for a merging bla... | StarcoderdataPython |
324655 | # Copyright 2021 The Kubeflow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | StarcoderdataPython |
397448 | # Copyright (C) 2009 Canonical Ltd
# Licenced under the txaws licence available at /LICENSE in the txaws source.
from twisted.trial.unittest import TestCase
from txaws.ec2 import model
class SecurityGroupTestCase(TestCase):
def test_creation_defaults(self):
group = model.SecurityGroup("sg-a3f2", "name",... | StarcoderdataPython |
1844356 | <filename>api.py
"""
This is the main Flask application for Danslist.
All endpoints were built using Flask for routing functionality,
Jinja2 for templating, and SQLAlchemy for database interaction.
"""
# Imports
from functools import wraps
from flask import (Flask, render_template, redirect, url_for,
... | StarcoderdataPython |
3233500 | import sys
import beepy
import datetime as dt
import os
import time
from random import randint
import http.client
import json
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
"""
This Script uses an API endpoint to determine if a vaccination is available.
This Script assumes:
1. You... | StarcoderdataPython |
8117854 | <filename>tests/test_cinefiles.py
import pytest, os, shutil
import glob
from pprint import pprint
from lxml import html
import cinefiles.cinefiles as cf
def test_import():
import cinefiles
movies = [ '5th Element','Amour','Astronaut Farmer',
'Down Periscope','Grand Budapest Hotel, The (2014)',
... | StarcoderdataPython |
11266130 | <reponame>michael-huber2772/portfolio-dashboard
# Generated by Django 3.1.2 on 2020-10-27 10:59
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0002_product_productprice'),
]
operations = [
migrations.AlterField(
... | StarcoderdataPython |
5097647 | <filename>utils/embedding_utils.py
import numpy as np
import gensim
class Embedding:
def __init__(self, f, corpus, max_document_length):
if ".txt" in f:
model = gensim.models.KeyedVectors.load_word2vec_format(f, binary=False)
else:
model = gensim.models.KeyedVectors.load_word2vec_format(f, binary=True)
w... | StarcoderdataPython |
1791557 | from setuptools import setup
def readme():
with open('README.md') as f:
README = f.read()
return README
setup(
name='master-slave',
version='1.0.0',
description='package to communicate with infected devices trought a local network',
long_description=readme(),
long_d... | StarcoderdataPython |
3549887 | <filename>Security/src/proj_brlp.py
import csv
import cvxopt
from cvxopt import solvers
import numpy as np
A_mat = []
R_mat = []
alpha = []
G = []
h = []
high_entropy_policy = []
class State:
def __init__(self, ind, name, actions):
self.index = ind
self.name = name
self.possibleAct... | StarcoderdataPython |
3277716 | MAKEFILE_BASE = """
clean: netsim-clean nso-clean ansible-clean
dev: netsim start-netsim nso dev-sync-to deploy-dev
nso:
-@ncs-setup --dest .
-@echo "Starting local NSO instance..."
-@ncs
ansible-clean:
-@rm *.retry > /dev/null
start-netsim:
-@ncs-netsim start
netsim-clean:
-@echo "Stopping All Netsim Inst... | StarcoderdataPython |
3287982 | <filename>Test/astc_size_binary.py
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# -----------------------------------------------------------------------------
# Copyright 2019-2020 Arm Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in comp... | StarcoderdataPython |
267361 | <reponame>nilsvu/spectre
# Distributed under the MIT License.
# See LICENSE.txt for details.
import numpy as np
def compute_piecewise(x, rotor_radius, inner_value, outer_value):
radius = np.sqrt(np.square(x[0]) + np.square(x[1]))
if (radius > rotor_radius):
return outer_value
else:
return... | StarcoderdataPython |
6402217 | <filename>code/WV.py
# https://dhhr.wv.gov/COVID-19/Pages/default.aspx
import csv
from datetime import datetime
import json
import os
from urllib.request import urlopen, Request
import requests
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from se... | StarcoderdataPython |
3550222 | <filename>ArraysAndSorting/CuttingBoards.py
# Importing standard libraries
import sys
'''
Produces mincost for the cuts. Follows merge sort's merge procedure after
sorting the arrays according to the cost (in descending order). Also as the
elements are merged, corresponding counts are merged (horizontal or... | StarcoderdataPython |
11203834 | """
Scematic Diagram of PCA
-----------------------
Figure 7.2
A distribution of points drawn from a bivariate Gaussian and centered on the
origin of x and y. PCA defines a rotation such that the new axes (x' and y')
are aligned along the directions of maximal variance (the principal components)
with zero covariance. ... | StarcoderdataPython |
4930612 | # __init__.py for python to treat folder as module | StarcoderdataPython |
21679 | #!/usr/bin/env python3
'''
The MIT License (MIT)
Copyright (c) 2014 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limi... | StarcoderdataPython |
6626922 | <gh_stars>1-10
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by <NAME>, <EMAIL>, All rights reserved.
# LLNL-CODE-647... | StarcoderdataPython |
3507733 | webpageTokenUrls = [
('ahj-set-maintainer', {}),
('ahj-remove-maintainer', {}),
('create-api-token', {}),
('edit-review', {}),
('edit-update', {}),
('edit-deletion', {}),
('edit-addition', {}),
('user-update', {}),
('active-user-info', {}),
('comment-submit', {}),
('djos... | StarcoderdataPython |
9622653 | import math
import vector
import parametrize_from_file
from pytest import approx
from voluptuous import Schema, Optional
from parametrize_from_file.voluptuous import Namespace
with_math = Namespace('from math import *')
with_vec = with_math.fork('from vector import *')
@parametrize_from_file(
schema=Schema({
... | StarcoderdataPython |
6662925 | from __future__ import annotations
from dataclasses import dataclass
import glob
from pathlib import Path
from typing import Callable, Generic, List, Tuple, TypeVar, Union, Optional
from kgdata.spark import get_spark_context
from sm.misc import deserialize_byte_lines, deserialize_lines, identity_func
from tqdm import ... | StarcoderdataPython |
8161240 | <reponame>bate/c3nav<gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-05-10 13:30
from __future__ import unicode_literals
import c3nav.mapdata.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
... | StarcoderdataPython |
55000 | # flake8: noqa
__version__ = "0.1.4"
from .quantity_array import QuantityArray
from .quantity_set import QuantitySet
| StarcoderdataPython |
1904710 | ##
# Exploit Title: Schneider Electric InduSoft/InTouch DoS
# Date: 06/11/2019
# Exploit Author: <NAME>
# CVE : CVE-2019-3946
# Advisory: https://www.tenable.com/security/research/tra-2018-07
# Affected Vendors/Device/Firmware:
# - InduSoft Web Studio v8.1 or prior
# - InTouch Machine Edition 2017 v8.1 or prior
##
i... | StarcoderdataPython |
346639 | <gh_stars>0
# encoding: utf-8
__author__ = "<NAME>"
# Taken and adapted from: https://github.com/wdika/NeMo/edit/main/tests/collections/common/loss_inputs.py
from dataclasses import dataclass
import numpy as np
import torch
from tests.collections.common.pl_utils import NUM_BATCHES
@dataclass(frozen=True)
class Lo... | StarcoderdataPython |
6608028 | <reponame>DudeNr33/pyinstaller-versionfile<filename>test/unittest/test_writer.py
"""
Author: <NAME>
Unit tests for pyinstaller_versionfile.writer.
"""
try:
from unittest import mock
except ImportError:
import mock # Python 2.7
import pytest
from pyinstaller_versionfile.writer import Writer
from pyinstaller_... | StarcoderdataPython |
9690872 | # -*- coding:utf-8 -*-
from re import sub
from itertools import islice
'''
如何调整字符串的文本格式
'''
# 将日志文件中的日期格式转变为美国日期格式mm/dd/yyyy
# 使用正则表达式模块中的sub函数进行替换字符串
with open("./log.log","r") as f:
for line in islice(f,0,None):
#print sub("(\d{4})-(\d{2})-(\d{2})",r"\2/\3/\1",line)
# 可以为每个匹配组起一个别名
print... | StarcoderdataPython |
128302 | import config
from database import RedditOutfitsDatabase
from util_reddit import generate_thread_ids
'''
This script is ran according to Malefashionadvice's, Femalefashionadvice's, and Streetwear's weekly thread(s) schedules.
'''
def process_threads(thread_ids: list, database):
'''
Given a list of threads ID... | StarcoderdataPython |
6592198 | from .base import Marshal, ConstReader, FixedSizer, EMPTY_CONTEXT, MinMax
from .errors import InstructError, InvalidValueError
from ._compat import pad
PADDING_DIRECTION_NONE = 0
PADDING_DIRECTION_RIGHT = 1
PADDING_DIRECTION_LEFT = 2
PADDING_DIRECTION_BOTH = 3
def _strip(obj, dir, padding):
if dir == PADDING_D... | StarcoderdataPython |
4855317 | """Example of a single file flask application that uses and open notify API"""
from flask import Flask, redirect
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
import requests
# Create Flask application instance
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite3"
... | StarcoderdataPython |
12844097 | ###############################################################################
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"). #
... | StarcoderdataPython |
9646830 | <reponame>Forbu/fourier_neural_operator
"""
@author: <NAME> This file is the Fourier Neural Operator for 2D problem such
as the Navier-Stokes equation discussed in Section 5.3 in the
[paper](https://arxiv.org/pdf/2010.08895.pdf), which uses a recurrent structure
to propagates in time.
this part of code is taken from :
... | StarcoderdataPython |
11234635 | from getFolderFromRepo import *
def test_proper_filepath():
def is_valid_filepath(path: str) -> bool:
# should start with /
# should not end with /
# so it should be / or /a or /a.../b
assert path.startswith("/")
if len(path) != 1:
assert not path.endswith("/")
... | StarcoderdataPython |
3254863 | import numpy as np
import h5py
import os
from wormpose.dataset.loader import load_dataset
def save_results(dataset_loader, dataset_path, results_root_dir):
dataset = load_dataset(dataset_loader, dataset_path)
all_scores = []
all_theta = []
for video_name in sorted(os.listdir(results_root_dir)):
... | StarcoderdataPython |
8112844 | <gh_stars>1-10
#!/usr/bin/python
#
# Copyright 2017 Google 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 appl... | StarcoderdataPython |
3447483 | try:
from normatrix.source.file_parser import CFileParse
from normatrix.source.config import TypeLine
except ModuleNotFoundError:
from normatrix.normatrix.source.file_parser import CFileParse
from normatrix.normatrix.source.config import TypeLine
import re
reg = re.compile('^(?!.*=)(\w{1,} {0,1}){2,}\... | StarcoderdataPython |
3204007 | <filename>vscreenml_v2/binana/_cli_params/__init__.py<gh_stars>0
# This file is part of BINANA, released under the Apache 2.0 License. See
# LICENSE.md or go to https://opensource.org/licenses/Apache-2.0 for full
# details. Copyright 2020 <NAME>. | StarcoderdataPython |
1784457 | from datetime import date
trab = {}
trab["Nome"] = str(input("Nome: "))
Nascimento = int(input("Ano de nascimento: "))
trab["idade"] = date.today().year - Nascimento
trab["CTPS"] = int(input("CTPS (0 não tem): "))
if trab["CTPS"] == 0:
print(30*'-=')
print(trab)
print(f"Nome tem o valor de {trab['Nome']} \n... | StarcoderdataPython |
6557537 | <reponame>objarni/remind-tests<filename>browser.py
# coding: utf-8
# Standard
import time
# Third party
from selenium import webdriver
class BrowserSimulator():
def __init__(self, headless=True):
if headless:
from pyvirtualdisplay import Display
display = Display(visible=0, size... | StarcoderdataPython |
6992 | import requests
from bs4 import BeautifulSoup
def recursiveUrl(url, link, depth):
if depth == 5:
return url
else:
print(link['href'])
page = requests.get(url + link['href'])
soup = BeautifulSoup(page.text, 'html.parser')
newlink = soup.find('a')
if len(newlink) =... | StarcoderdataPython |
8167195 | from django.contrib import admin
from .models import Message
class MessageAdmin(admin.ModelAdmin):
list_display = ('message', 'room', 'created')
admin.site.register(Message, MessageAdmin)
| StarcoderdataPython |
8096850 | import unittest
from yomi.main import convert
class YomiTestCase(unittest.TestCase):
def setUp(self):
print("setUp!!")
def tearDown(self):
print("tearDown!!")
def test_yakiniku(self):
self.assertEqual(convert('焼肉定食'), ['ヤ', 'キ', 'ニ', 'k', 'テ', 'イ', 'シ', 'ョ', 'k'])
| StarcoderdataPython |
6472196 | import numpy as np
from layer import Layer
from coder import Coder
class Sequencer(object):
def __init__(self, sequence_layer, input_layers):
self.sequence_layer = sequence_layer
self.input_layers = input_layers
self.transits = []
def add_transit(self, new_state=None, **input_states):... | StarcoderdataPython |
165477 | <filename>scrawl/pages_utils.py
import os
from flask import current_app, safe_join
from scrawl.utils import find_pages, full_directory_remove
def get_pages(work_directory: str):
pages = []
dir_content = os.listdir(work_directory)
for name in dir_content:
fullname = os.path.join(work_directory,... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.