id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
1736004 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import sy... | StarcoderdataPython |
1971030 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Deployment toolkit
'''
import os,re
from datetime import datetime
from fabric.api import *
env.user = 'root'
env.sudo_user = 'root'
env.hosts = ['10.104.128.190']
_TAR_FILE = 'dist-xilingxue.tar.gz'
_REMOTE_TMP_TAR = '/tmp/%s' % _TAR_FILE
_REMOTE_BASE_DIR = '/srv/xil... | StarcoderdataPython |
386767 | <filename>fruit/api/serializers.py
from fruit.models import Fruit
from rest_framework import serializers
class FruitDefaultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Fruit
fields = ["id", "name", "description"]
class FruitDetailSerializer(FruitDefaultSerializer):
... | StarcoderdataPython |
6462401 | import os
import sys
import random
import logging
import pkgutil
import importlib
import click
import numpy as np
from qtpy.uic import loadUi
from qtpy.QtGui import QIcon
from qtpy.QtCore import QTimer, Qt, Signal
from qtpy.QtWidgets import QApplication, QDialog, QMainWindow
import astropy.units as u
from astropy.mo... | StarcoderdataPython |
365598 | from django import forms
from django.forms import formset_factory
from . import models
class ThermalSourceForm(forms.ModelForm):
scheme_image = forms.FileField(required=False)
def save(self, commit=True):
if self.cleaned_data.get('scheme_image') is not None \
and hasattr(self.cleaned... | StarcoderdataPython |
8089321 | <reponame>wlmwng/urlExpander
"""
This module extends the package's core functions to collect information related to news articles.
The NewsContent class acts as a template which is filled out by the fetching functions.
The output of every fetching function is a stringified JSON object, which can be
written to a .jsonl ... | StarcoderdataPython |
5002922 | <filename>{{ cookiecutter.project_slug }}/{{ cookiecutter.pkg_name }}/{{ cookiecutter.first_app_name }}/apps.py<gh_stars>1-10
from django.apps import AppConfig
class {{ cookiecutter.first_app_name.split('_')|map('capitalize')|join('') }}Config(AppConfig):
name = '{{ cookiecutter.pkg_name }}.{{ cookiecutter.first_... | StarcoderdataPython |
1720032 | import phonenumbers
from authy.api import AuthyApiClient
from flask import current_app as app
from flask import flash, g, request, session
def parse_phone_number(full_phone):
"""
Parses the phone number from E.164 format
:param full_phone: phone number in E.164 format
:returns: tuple (country_code, p... | StarcoderdataPython |
11235319 | <gh_stars>0
import numpy as onp
import casadi as cas
def clip(
x,
min,
max
):
"""
Clip a value to a range.
Args:
x: Value to clip.
min: Minimum value to clip to.
max: Maximum value to clip to.
Returns:
"""
return onp.fmin(onp.fmax(x, min), max)... | StarcoderdataPython |
6627301 | <filename>lib/sensor.py
import pigpio
class Sensor:
ax=0
ay=0
az=0
mx=0
my=0
mz=0
def __init__(self, pi):
self.pi = pi
self.acc = self.pi.i2c_open(1, 0x19, 0)
self.pi.i2c_write_byte_data(self.acc,0x20,0x37)
self.mag = self.pi.i2c_open(1, 0x1e, 0)
... | StarcoderdataPython |
159582 | from onelang_core import *
from enum import Enum
import OneLang.One.Ast.AstTypes as astTypes
import OneLang.One.Ast.Types as types
class DETECTION_MODE(Enum):
ALL_IMPORTS = 1
ALL_INHERITENCE = 2
BASE_CLASSES_ONLY = 3
class GraphCycleDetector:
def __init__(self, visitor):
self.node_is_in_path =... | StarcoderdataPython |
11289911 | <reponame>antonelloceravola/ToolBOSCore
# -*- coding: utf-8 -*-
#
# Custom package settings
#
# Copyright (C)
# Honda Research Institute Europe GmbH
# Carl-Legien-Str. 30
# 63073 Offenbach/Main
# Germany
#
# UNPUBLISHED PROPRIETARY MATERIAL.
# ALL RIGHTS RESERVED.
#
#
BST_useClang = True
# EOF
| StarcoderdataPython |
5085539 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-28 03:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('conference', '0001_initial'),
]
operations = [
migrations.AlterField(
... | StarcoderdataPython |
12800707 | #!/usr/bin/env python
from __future__ import division, absolute_import, print_function
from future.builtins import super
from iris_sdk.models.base_resource import BaseResource
from iris_sdk.models.data.totals import TotalsData
XML_NAME_TOTALS = "Quantity"
XPATH_TOTALS = "/totals"
class Totals(BaseResource, TotalsDa... | StarcoderdataPython |
1801371 | <reponame>pablogs98/lithops
#
# (C) Copyright Cloudlab URV 2020
#
# 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 appli... | StarcoderdataPython |
11318544 | word = input("Enter a string: ")
word = word.split(", ")
hnum = 0
dic = {}
for elm in word:
elm = int(elm)
if hnum == 0:
hnum = elm
elif hnum < elm:
hnum = elm
print(hnum)
for elm in word:
flag = True
for i in range(2,hnum//2):
elm = int(elm)
if elm%i==0:
... | StarcoderdataPython |
3365040 | <reponame>feloundou/safe-experts<filename>algos/make_experts.py<gh_stars>0
from agent_utils import Expert
from adabelief_pytorch import AdaBelief
import gym
import safety_gym
from ppo_algos import MLPActorCritic
from utils import setup_logger_kwargs, mpi_fork
ENV_NAME = 'Safexp-PointGoal1-v0'
# # make expert
# exp... | StarcoderdataPython |
9730692 | # Copyright 2021, The TensorFlow Federated 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 o... | StarcoderdataPython |
11240824 | <gh_stars>0
import tensorflow as tf
import os
import numpy as np
from fetcher import *
def load_ellipsoid_as_tensor():
pkl = pickle.load(open('utils/ellipsoid/info_ellipsoid.dat', 'rb'))
coord = pkl[0]
pool_idx = pkl[4]
faces = pkl[5]
lape_idx = pkl[7]
edges = []
for i in range(1, 4):
... | StarcoderdataPython |
9650033 | # Copyright 2018 Red Hat, 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 writing, ... | StarcoderdataPython |
6493741 | import torch
import numpy as np
from data.agent_vocab import AgentVocab
from .metadata_helper import get_shapes_metadata, get_metadata_properties
from .dataloader_helper import get_shapes_features, get_shapes_dataloader
from enums.dataset_type import DatasetType
from models.shapes_receiver import ShapesReceiver
from... | StarcoderdataPython |
388285 | '''
GSLCodeGenerators for code that uses the ODE solver provided by the GNU Scientific Library (GSL)
'''
import os
import re
import sys
import numpy as np
from brian2.units.fundamentalunits import fail_for_dimension_mismatch
from brian2.core.variables import AuxiliaryVariable, ArrayVariable, Constant
from brian2.core... | StarcoderdataPython |
11253887 | <filename>002_merge_json.py
import sys
import urllib
import json
import argparse
import urllib.request
import time
import os
import requests
import glob
import hashlib
files = glob.glob("data/tmp/*.json")
arr = []
for i in range(len(files)):
file = files[i]
if i % 100 == 0:
print(i+1, len(files))
... | StarcoderdataPython |
9796753 | <filename>tests/test_gravity_ingestor.py
# coding: utf-8
import os
import unittest
import pandas as pd
import numpy as np
import datetime
from dgp.lib import gravity_ingestor as gi
class TestGravityIngestor(unittest.TestCase):
def test_read_bitfield_default(self):
status = pd.Series(data=[21061]*5)
... | StarcoderdataPython |
12852987 | from math import ceil, floor, trunc
x = 1.4
y = 2.6
print(floor(x), floor(y))
print(floor(-x), floor(-y))
print(ceil(x), ceil(y))
print(ceil(-x), ceil(-y))
print(trunc(x), trunc(y))
print(trunc(-x), trunc(-y))
| StarcoderdataPython |
8040624 | '''
Copyright 2019 Secure Shed Project Dev 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... | StarcoderdataPython |
3377036 | <filename>tools/find_missing.py
# -*- coding: utf-8 -*-
# find missing glyphs needed to render given txt's
import json
def find_missing(pths):
missing = {}
for p in pths:
txt = open(p,'r').read()
js = json.loads(open("./dist/min-trad-compiled.json",'r').read())
for c in txt:
... | StarcoderdataPython |
9783480 | import logging
from gym import envs
from gym.envs.registration import register
logger = logging.getLogger(__name__)
# Register openai's environments as multi agent
# This should be done before registering new environments
env_specs = [env_spec for env_spec in envs.registry.all() if 'gym.envs' in env_spec.entry_point... | StarcoderdataPython |
1780968 | <filename>nicos_sinq/amor/setups/virtual_source.py
description = 'Virtual source for the Selene guide'
devices = dict(
dvv = device('nicos_sinq.amor.devices.virtual_source.NumberSwitcher',
description = 'Diaphragm virtual Source Vertical',
mapping = {
1: 0.,
2: 45.,
... | StarcoderdataPython |
3549520 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 17:35:32 2020
@author: lutra
"""
import sqlite3
PC_lab = False
if PC_lab:
main = '/home/shiri/plasmid_project/Phage_like_plasmids/PLP_final/'
else:
main = '/data/Current_work/Phage_like_plasmids/PLP_final/'
print(main)
proj = 'SS... | StarcoderdataPython |
1884165 | # Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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 applicab... | StarcoderdataPython |
11267193 | <reponame>openedx/edx-celeryutils
"""
Testing persistent tasks.
A task built with the LoggedTask base class is imported from test_utils.tasks.
* simple_logged_task -
Emits an "INFO" level log statement as soon as the task returns.
Note that this will occur after the task runs if the task is run und... | StarcoderdataPython |
3456767 | <gh_stars>0
import re
import random
import itertools
import math
from collections import defaultdict
import botconfig
import src.settings as var
from src.utilities import *
from src import channels, users, debuglog, errlog, plog
from src.functions import get_players, get_all_players, get_main_role
from src.decorators ... | StarcoderdataPython |
4825437 | <reponame>ducluongtran9121/Web-Application-Project
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.db import models
# Create your models here.
class MemberManager(BaseUserManager):
def create_user(self, code, email... | StarcoderdataPython |
4970914 | <filename>examples/idioms/programs/094.1101-print-type-of-variable.py
"""Print type of variable.
Print the name of the type of _x. Explain if it is a static type or dynamic type.
This may not make sense in all languages.
Source: programming-idioms.org
"""
# Implementation author: nickname
# Created on 2016-02-18T... | StarcoderdataPython |
48038 | #-*- coding:utf-8 -*-
from __future__ import print_function
import os,sys,sip,time
from datetime import datetime,timedelta
from qtpy.QtWidgets import QTreeWidgetItem,QMenu,QApplication,QAction,QMainWindow
from qtpy import QtGui,QtWidgets
from qtpy.QtCore import Qt,QUrl,QDate
from Graph import graphpage
from layout impo... | StarcoderdataPython |
6595633 | import cupy as np
def soft_py(x, tau):
threshed = np.maximum(np.abs(x)-tau, 0)
threshed = threshed*np.sign(x)
return threshed
def ht3(x, ax, shift, thresh):
C = 1./np.sqrt(2.)
if shift == True:
x = np.roll(x, -1, axis = ax)
if ax == 0:
w1 = C*(x[1::2,:,:] + x[0::2, :, :])
... | StarcoderdataPython |
1825996 | <reponame>NoListen/RL-forest<gh_stars>1-10
# https://github.com/openai/baselines/baselines/ddpg/main.py
# the TensorBoardOutputFormat of logger of baselines is perfect.
import argparse
import time
import os
from tempfile import mkdtemp
import sys
import json
# import gym_starcraft.envs.war_map_battle_env as sc
# impor... | StarcoderdataPython |
5019354 | <reponame>DistributedML/Biscotti
import pdb
import pandas as pd
import os
import numpy as np
# input_file_directory = "FedSys_Azure"
# output_file_directory = input_file_directory + "_parsedResults/"
# total_nodes = 100
# numRuns=1
def parse_logs():
acceptedUpdates = 0
rejectedUpdates = 0
fname = "pingValues... | StarcoderdataPython |
55980 | <filename>aplpy/tests/setup_package.py
def get_package_data():
return {
_ASTROPY_PACKAGE_NAME_ + '.tests': ['coveragerc', 'data/*/*.hdr', 'baseline_images/*.png']}
| StarcoderdataPython |
6468105 | from typing import _Final
from typing import _GenericAlias
from typing import _Immutable
from typing import _SpecialForm
from typing import _tp_cache
from typing import _type_check
__all__ = ["Constant"]
class SubscriptableAlias(_Final, _Immutable, _root=True):
__slots__ = ("_name", "_doc")
def __new__(cls,... | StarcoderdataPython |
60344 | from sklearn.base import BaseEstimator
import yake
from ._prep import TextPrep
class YakeTextPrep(TextPrep, BaseEstimator):
"""
Remove all text except meaningful key-phrases. Uses [yake](https://github.com/LIAAD/yake).
Arguments:
top_n: number of key-phrases to select
unique: only return... | StarcoderdataPython |
5151682 | #!/usr/bin/env python3
from typing import List, Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteMiddle(self, head: [ListNode]) -> Optional[ListNode]:
p1 = head
p2 = p3 = head
length = 0
while p1:
length += 1
p1 = p... | StarcoderdataPython |
1766346 | #!/usr/bin/python
import time
import sys
import subprocess
import psycopg2
import argparse
#Start time for processing file
def start_time():
starttime = time.asctime(time.localtime(time.time()))
print starttime
return starttime
#First Line
def first_line(filename):
firstline = subprocess.check_output(... | StarcoderdataPython |
12834921 | # Generated by Django 2.2.12 on 2020-05-14 22:02
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('products', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields... | StarcoderdataPython |
11295983 | import sublime
import sublime_plugin
from .qpython.qtype import QException
from socket import error as socket_error
import numpy
import datetime
from . import q_chain
from . import QCon as Q
from . import util
#for testing in console
#from qpython import qconnection
#q = qconnection.QConnection(host = 'localhost', p... | StarcoderdataPython |
3449779 | <gh_stars>0
from setuptools import setup
if __name__ == "__main__":
try:
setup()
except Exception as e:
print(
f"Exception occurred: {e}"
"please ensure you have the right version of python and the most updated version of setuptools and wheels"
"python --ver... | StarcoderdataPython |
3534716 | import json
import plotly
from plotly.graph_objs import Bar
from flask import Flask
from flask import render_template, request, jsonify
from sklearn.externals import joblib
from sqlalchemy import create_engine
import sys, os
# import libraries
import nltk
nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger'... | StarcoderdataPython |
177356 | <reponame>bird-house/malleefowl<filename>malleefowl/processes/wps_workflow.py
import os
import yaml
from pywps import Process
from pywps import ComplexInput
from pywps import ComplexOutput
from pywps import Format, FORMATS
from pywps.app.Common import Metadata
from malleefowl.workflow import run
import logging
LOGGE... | StarcoderdataPython |
6545535 | <reponame>AngelBrisco/SubPixelConvolution-in-Keras
import numpy as np
from tensorflow.keras.layers import *
from tensorflow.keras import backend as K
import tensorflow as tf
__all__ =["SubpixelLayer2D","conv_up","SubpixelLayer2D_log"]
class SubpixelLayer2D(Layer):
def __init__(self,filters=None,ksz=1, scale=2, *... | StarcoderdataPython |
9690116 | <reponame>aluoch-sheila/NEIGHBOURHOOD<gh_stars>0
from django.test import TestCase
from .models import Neighbourhood, Profile,Business,Join,Posts
from django.contrib.auth.models import User
# TESTING NEIGHBOURHOOD CLASS
class NeighbourhoodTestClass(TestCase):
'''
Test Neighbourhood class and its methods and fun... | StarcoderdataPython |
4947373 | <gh_stars>1-10
from typing import Dict, cast
from django.core import signing
from django.core.files.storage import default_storage
from django.urls import reverse
import pytest
import requests
from rest_framework.test import APIClient
from s3_file_field._sizes import mb
from .fuzzy import URL_RE, UUID_RE, Re
def t... | StarcoderdataPython |
8036245 | #!/usr/bin/env python
#####################
# Calibrates a given filter
#####################
import sys, os, optparse, re, unittest, inspect
import numpy, astropy, astropy.io.fits as pyfits
if __name__ == '__main__':
import matplotlib
matplotlib.use('PS')
from matplotlib import pylab
pylab.ioff()
el... | StarcoderdataPython |
11285039 | import fnmatch
import re
from validator.constants import BUGZILLA_BUG
from validator.compat import (FX4_DEFINITION, FX5_DEFINITION, FX6_DEFINITION,
FX7_DEFINITION, FX8_DEFINITION, FX9_DEFINITION,
FX11_DEFINITION, FX12_DEFINITION, TB7_DEFINITION,
... | StarcoderdataPython |
3219258 | <reponame>andrewgailey/robogen
# Gir by InvaderZim
# http://robotgame.org/viewrobot/5740
from random import choice
import rg
class defaultdict(dict):
def __init__(self, default_factory=None, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.default_factory = default_factory
def __ge... | StarcoderdataPython |
8142989 | #!/usr/bin/env python
import brawlbracket
import argparse
parser = argparse.ArgumentParser(description='Run the BrawlBracket server.')
parser.add_argument('-d', '--debug', dest='debugMode', action='store_true',
help='run in debug mode')
parser.set_defaults(debugMode=False)
args = parser.parse_args(... | StarcoderdataPython |
1750470 | <gh_stars>0
class Solution:
def maxArea(self, height: list) -> int:
max_cheng = 0
i = 0
j = len(height) - 1
while i < j:
cheng = min(height[i], height[j]) * (j - i)
max_cheng = max(max_cheng, cheng)
if height[i] <= height[j]:
i += 1... | StarcoderdataPython |
3474290 |
from sympy import Symbol, log, sqrt, series, exp
K = Symbol("K")
S = Symbol("S")
softness = Symbol("softness")
x = Symbol("x")
def f(x):
return 10 * log (K * (1 + x)) / log(10)
def g(x):
return -(S-1)/(20*S) * (sqrt(f(x)**2 + softness**2) + f(x))
def h(x):
return exp(g(x) * log(10))
poly = series(... | StarcoderdataPython |
3592643 | CONVERTERS_PREFIX = '_converters'
SERVER_URL = 'https://www.inf.unibz.it'
MODEL_DIR_URL = SERVER_URL + '/~hbabii/pretrained_models'
CONVERTERS_URL= MODEL_DIR_URL + CONVERTERS_PREFIX
LIST_PREFIX = '_list'
MODEL_LIST_URL = MODEL_DIR_URL + LIST_PREFIX
PATH_TO_MODELS_ON_SERVER = '/home/students/hbabii/public_html/pretraine... | StarcoderdataPython |
9618682 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import globalFunctions
import re
import os
import logging
class ReadComicOnlineTo(object):
def __init__(self, manga_url, download_directory, chapter_range, **kwargs):
current_directory = kwargs.get("current_directory")
conversion = kwargs.get("conver... | StarcoderdataPython |
8161723 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Exaplanation: github_listmyrepos.py. enumerate all of your repositories
Usage:
$ python github_listmyrepos.py [ options ]
Style:
Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html
@name github_listmyrepos.py
@vers... | StarcoderdataPython |
1823189 | #%%
'''
Used to create diagrams for Descriptive Stat worksheet
'''
import csv, seaborn as sns, pandas as pd
flavor_counts = {}
with open('../../Datasets/icecream.csv', 'r') as f:
data = csv.DictReader(f)
for row in data:
current_flavor = row['flavor']
if current_flavor not in flavor_counts:
flavor_c... | StarcoderdataPython |
1990041 | <filename>Python/Algorithm/LoopEscope.py
import random
def main():
ponto = 0
letra = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
while True:
rletra = letra[random.randint(0, 25)]
print (rletra)
print ('Sua pontuação é... | StarcoderdataPython |
6408549 | print("""
/$$$$$ /$$$$$$$ /$$ /$$
|__ $$ | $$__ $$ | $$ | $$
| $$ | $$ \ $$ /$$$$$$$ /$$$$$$ /$$$$$$ | $$ /$$
| $$ /$$$$$$| $$$$$$$ /$$__ $$ /$$__ $$ /$$__ $$| $$ /$$/
/$$ | $$|______/| $$__ $$| $$ ... | StarcoderdataPython |
9656464 | <reponame>augastinklazar8673/Password-strength-prediction-model
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pds
import numpy as npy
import seaborn as sb
import warnings
warnings.filterwarnings('ignore')
# In[4]:
data = pds.read_csv('D:\password-strength\data.csv', error_bad_lines = False)
dat... | StarcoderdataPython |
3539472 | <filename>scripts/examples/tools/autoruns.py
# Tool Imports
from bph.tools.windows.autoruns import BphAutoruns as Autoruns
# Core Imports
from bph.core.server.template import BphTemplateServer as TemplateServer
from bph.core.session import BphSession as Session
from bph.core.sample import BphLabFile as LabFile
... | StarcoderdataPython |
11228363 | # coding: utf-8
from __future__ import absolute_import
import datetime
import re
import importlib
import six
from huaweicloudsdkcore.client import Client, ClientBuilder
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcore.utils import http_utils
from huaweicloudsdkcore.sdk_stream_request imp... | StarcoderdataPython |
5080422 | <gh_stars>0
#!/usr/bin/env python
# coding: utf-8
# # Introduction to Cufflinks
# This library binds the power of plotly with the flexibility of pandas for easy plotting.
# ## Import Libraries
# In[1]:
import pandas as pd
import numpy as np
import cufflinks as cf
import chart_studio.plotly as py
from plotly.o... | StarcoderdataPython |
1696448 | # emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ... | StarcoderdataPython |
1705753 | <filename>src/attrbench/metrics/sensitivity_n/result.py<gh_stars>0
from typing import List
import h5py
import numpy as np
from attrbench.metrics import MaskerActivationMetricResult
from attrbench.lib import NDArrayTree
class SensitivityNResult(MaskerActivationMetricResult):
inverted = False
def __init__(se... | StarcoderdataPython |
6537952 | ## 搜索旋转排序数组
class Solution:
def search(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) >> 1
if (nums[mid] < nums[0]) == ( target < nums[0]):
if (nums[mid] < target):
lo = mid + ... | StarcoderdataPython |
322685 | <reponame>wiboticalex/pyuavcan
# Copyright (c) 2019 UAVCAN Consortium
# This software is distributed under the terms of the MIT License.
# Author: <NAME> <<EMAIL>>
import os
import sys
import time
import gzip
import typing
import pickle
import base64
import pathlib
import logging
import itertools
import dataclasses
i... | StarcoderdataPython |
11383525 | <gh_stars>1-10
from rest_framework import serializers
from transformation.models import TransformationXput, TransformationInput, \
TransformationOutput, XputStructure
class XputStructureSerializer(serializers.ModelSerializer):
class Meta:
model = XputStructure
fields = (
"compoundd... | StarcoderdataPython |
3233868 | import pytest
from grep_func import grep_func
import sys
if sys.version_info[0] == 2:
from io import BytesIO as StringIO
else:
from io import StringIO
import re
from colorama import Fore
def test_grep():
import logging
pattern = "basic"
sys.stdout = StringIO()
grep_func.grep_func(logging,... | StarcoderdataPython |
11361535 | #%%
import pandas as pd
import datetime as dt
from datetime import date, timedelta, datetime
import requests
import urllib.request, json, os, itertools, threading, time, sys
#%%
def call_api():
api_url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/locations?datasetid=GHCND&locationcategoryid=ZIP' + '&units=standard... | StarcoderdataPython |
1853549 | <gh_stars>0
import getpass
import json
import pathlib
import socket
import subprocess
import urllib.request
GITLAB_BASE_URL = "https://gitlab.YOURCOMPANY.com"
user_name = getpass.getuser()
user_password = getpass.getpass()
ssh_key_path = pathlib.Path.home().joinpath(".ssh", "id_ed25519")
if ssh_key_path.is_file():
... | StarcoderdataPython |
3440155 | from enum import Enum
class Colors(Enum):
BLACK = 0
GRAY = 1
WHITE = 2
def dfs(v, graph, colors):
colors[v] = Colors.GRAY
for neighbor in graph[v]:
if (colors[neighbor] == Colors.GRAY) or (colors[neighbor] == Colors.WHITE and dfs(neighbor, graph, colors)):
return True
c... | StarcoderdataPython |
98944 | <gh_stars>0
from abc import abstractmethod, abstractproperty
import csv
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING, Union
if TYPE_CHECKING:
from xvfb import Xvfb # type: ignore
SubProc = Any # subprocess.Popen[AnyStr]
class TokenLocation(Enum):
COOKIE = 1
... | StarcoderdataPython |
6420334 |
#********************************************************************
# File: blocks_series2.py
# Author: <NAME>
#
# Description:
# Series 2 blocks
#
# Copyright (c) 2017 by Cisco Systems, Inc.
#
# ALL RIGHTS RESERVED. THESE SOURCE FILES ARE THE SOLE PROPERTY
# OF CISCO SYSTEM... | StarcoderdataPython |
5048466 | from spaceone.api.sample.v1 import helloworld_pb2, helloworld_pb2_grpc
from spaceone.core.pygrpc import BaseAPI
class HelloWorld(BaseAPI, helloworld_pb2_grpc.HelloWorldServicer):
pb2 = helloworld_pb2
pb2_grpc = helloworld_pb2_grpc
def say_hello(self, request, context):
params, metadata = self.pa... | StarcoderdataPython |
9750385 | <filename>hw3/language_model.py<gh_stars>0
import numpy as np
from segtok import tokenizer
import torch as th
from torch import nn
# Using a basic RNN/LSTM for Language modeling
class LanguageModel(nn.Module):
def __init__(self, vocab_size, rnn_size, num_layers=1, dropout=0):
super().__init__()
... | StarcoderdataPython |
3446386 | <gh_stars>1-10
"""This is SWAMP: Solving structures With Alpha Membrane Pairs
This module implements useful classes and methods used across all modules in SWAMP
"""
__author__ = "<NAME>"
__credits__ = "<NAME>, & <NAME>"
__email__ = "<EMAIL>"
import sys
import os
import gzip
import shutil
import tempfile
import loggi... | StarcoderdataPython |
1623923 | import numpy as np
import pickle
import os
import matplotlib.pylab as plt
plt.close('all')
def save_obj(obj, name ):
with open(name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name ):
with open(name + '.pkl', 'rb') as f:
return pickle.load(f)
d = load_obj('... | StarcoderdataPython |
238601 | import sqlite3
def get_users():
conn = sqlite3.connect("data/manage_RP")
sql = '''
select * from dbuser where delete_flg = 'false' order by userid
'''
data = conn.execute(sql).fetchall()
conn.close()
return data
def get_user_by_id(user_id):
conn = sqlite3.connect("data/manage_RP")
... | StarcoderdataPython |
368433 | from django.shortcuts import render, redirect
from django.urls import reverse
from django.http import HttpResponse
from c4.celery import app
from movies.models import Movie
from movies.tasks import search_and_save
import urllib.parse
from celery.exceptions import TimeoutError
def search(request):
# Retrieves se... | StarcoderdataPython |
3318188 | from django.views.generic.base import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.conf import settings
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.viewsets import ViewSet
from rest_framework.decorator... | StarcoderdataPython |
5183378 | <reponame>xiaoluo91/whatshap
"""
Print the square of a number
This is an example subcommand. The first line above is a short summary description
of what the command does. It is shown when running whatshap --help. Make it short!
To add a new subcommand:
* Copy this module to a new file and adjust it to your needs. Th... | StarcoderdataPython |
342150 | <reponame>FranciscoAT/adventOfCode2017<gh_stars>0
def main():
sequence = input().split(',')
programs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
program_string = ''.join(programs)
seen = [program_string]
for index in range(1000000000):
for comma... | StarcoderdataPython |
5055880 | #!/usr/bin/env python
#
# Copyright 2007 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 applicable law o... | StarcoderdataPython |
4937262 | <filename>filter.py
import argparse
import cv2
import os
import re
class imgProcess:
def __init__(self, targetDir, sampleDir, fileType, height, width):
'''
targetDir: path to the target image
sampleDir: path to the directory containing sample images
height & with: size of... | StarcoderdataPython |
1755143 |
# from rhombus.models.core import *
from rhombus.models.core import BaseMixIn, Base, Column, relationship, types, deferred, ForeignKey, backref, UniqueConstraint, object_session, Sequence
from rhombus.models.ek import EK
from rhombus.models.user import User, Group
# from rhombus.lib.roles import *
from rhombus.lib imp... | StarcoderdataPython |
8197755 | import mne
import pandas as pd
import numpy as np
from scipy.signal import spectrogram
from sklearn.svm import LinearSVC, SVC
import matplotlib.pyplot as plt
import matplotlib
class ssvep:
def __init__(self, set_fontsize=True, fontsize=22):
"""
Parameters
----------
set_fontsize : b... | StarcoderdataPython |
9701986 | <gh_stars>10-100
import os
from graphviz import Digraph
from yattag import Doc, indent
class HTML:
"""
This contains helper functions for creating HTML files with yattag.
Parameters
----------
outFile: str
Output file
"""
def __init__(self, outFile):
"""This function init... | StarcoderdataPython |
4874204 | import unittest
import riemann
from riemann import simple
from riemann import tx as txn
from riemann.tests import helpers
class TestSimple(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
riemann.select_network('bitcoin_main')
def test_output(self):
for i in range(l... | StarcoderdataPython |
8005861 | <filename>src/pyspiffe/workloadapi/jwt_source.py
"""
This module defines the source for JWT Bundles and SVIDs.
"""
from abc import ABC, abstractmethod
from typing import Optional, Set
from pyspiffe.bundle.jwt_bundle.jwt_bundle import JwtBundle
from pyspiffe.spiffe_id.spiffe_id import TrustDomain
from pyspiffe.svid.jw... | StarcoderdataPython |
11378770 | <reponame>KaustubhKekre/homeland
from django.urls import path
from .views import register_view, login_view, logout_view, dashboard_view
app_name = 'accounts'
urlpatterns = [
path('dashboard', dashboard_view, name='dashboard'),
path('signup', register_view, name='register'),
path('login', login_view, name=... | StarcoderdataPython |
3539125 | <reponame>cowboycow4/cms
"""
Unit and regression test for the hey package.
"""
# Import package, test suite, and other packages as needed
import hey
import pytest
import sys
def test_hey_imported():
"""Sample test, will always pass so long as import statement worked"""
assert "hey" in sys.modules
| StarcoderdataPython |
395154 | from flask import Flask
import json
import os
from flask_sqlalchemy import SQLAlchemy
def open_settings():
with open("settings.json", "r") as file:
args = json.load(file)
return args
db = SQLAlchemy()
settings = open_settings()
DB_NAME = settings["db_name"]
host = settings["host"]... | StarcoderdataPython |
372217 | from PySide2.QtCore import QMetaObject, QObject, QRect, QSize
from PySide2.QtGui import QKeySequence
from PySide2.QtWidgets import (
QAction,
QGridLayout,
QLayout,
QMenu,
QMenuBar,
QSplitter,
QStatusBar,
QTabWidget,
QWidget,
)
from nexus_constructor.instrument_view.instrument_view i... | StarcoderdataPython |
11338389 | <gh_stars>0
"""\
Python code generator
@copyright: <NAME>
@copyright: 2002-2007 <NAME>
@copyright: 2012-2016 <NAME>
@copyright: 2016-2021 <NAME>
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
import os, os.path, random, re
from codegen import BaseLangCodeWriter, BaseSourceFileContent
import... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.