id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3420335 | import threading
import numpy as np
import cv2
from mobot.brain.agent import Agent
from mobot.utils.image_grid import ImageGrid
from mobot.utils.rate import Rate
class BallFollower(Agent):
def __init__(self):
Agent.__init__(self)
self.camera.register_callback(self.camera_cb)
self.chassis.e... | StarcoderdataPython |
3490597 | <reponame>sahilkumar15/ChatBots<gh_stars>100-1000
from rasa_sdk import Tracker
from rasa_sdk.executor import CollectingDispatcher
from typing import Dict, Text, Any, List
import requests
from rasa_sdk import Action
from rasa_sdk.events import SlotSet, FollowupAction
from rasa_sdk.forms import FormAction
# We use the... | StarcoderdataPython |
4859166 | from typing import Dict, Union, Set
from unittest import TestCase
from networkx import DiGraph
from veniq.baselines.semi._common_types import Statement, StatementSemantic
from veniq.baselines.semi._lcom2 import LCOM2
from veniq.ast_framework import ASTNode
class LCOM2TestCase(TestCase):
def test_same_semantic(... | StarcoderdataPython |
5019166 | <reponame>pylangstudy/201706
while True:
try:
x = int(input("Please enter a number: "))
break
except KeyboardInterrupt:
print("KeyboardInterrupt!!")
except ValueError:
print("Oops! That was no valid number. Try again")
| StarcoderdataPython |
4926483 | <reponame>M1kol4j/helita
"""
Set of routines to interface with MULTI (1D or _3D)
"""
import numpy as np
import os
class Multi_3dOut:
def __init__(self, outfile=None, basedir='.', atmosid='', length=4,
verbose=False, readall=False):
""" Class that reads and deals with output from multi_3d ... | StarcoderdataPython |
6551119 | """\
wxCheckBox widget configuration
@copyright: 2014-2016 <NAME>
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
config = {
'wxklass': 'wxCheckBox',
'style_defs': {
'wxCHK_2STATE': {
'desc': _('Create a 2-state checkbox. This is the default.'),
'exclu... | StarcoderdataPython |
9754497 | from django.db import models
# local imports
from authors.apps.authentication.models import User
from authors.apps.articles.models import Article
class BookmarkArticle(models.Model):
"""
Create the bookmark model
"""
user = models.ForeignKey(User, verbose_name='User', on_delete=models.CASCADE)
ar... | StarcoderdataPython |
5051001 | <filename>ethfinex/__init__.py
name = "ethfniex"
| StarcoderdataPython |
6485117 | <reponame>judaicalink/judaicalink-labs
from django.contrib import admin
from django.contrib.admin import AdminSite
import django.db.models as django_models
from . import views
from . import models
# Register your models here.
class MyAdminSite(AdminSite):
site_header = 'JudaicaLink Labs Backend'
def get_urls... | StarcoderdataPython |
352085 | # -*- coding: utf-8 -*-
"""
tkfilebrowser - Alternative to filedialog for Tkinter
Copyright 2017 <NAME> <<EMAIL>>
based on code by <NAME> copyright 1998
<http://effbot.org/zone/tkinter-autoscrollbar.htm>
tkfilebrowser is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public ... | StarcoderdataPython |
1781141 | <gh_stars>100-1000
import autosar
def setup():
ws = autosar.workspace(version="4.2.2")
package=ws.createPackage('ApplicationTypes', role='DataType')
package.createSubPackage('DataConstrs', role='DataConstraint')
package.createSubPackage('CompuMethods', role='CompuMethod')
package.createSubPa... | StarcoderdataPython |
3362717 | <gh_stars>1-10
from pydantic import create_model, validator
def create_model_for_table(tablename, cols):
def validate_length(cls, v, values, **kwargs):
col_value = v
col_length = lengths[kwargs["field"].name]
assert col_length >= len(f"{col_value}")
return col_value
lengths = ... | StarcoderdataPython |
4917897 | from secml.testing import CUnitTest
from numpy import *
from secml.data.loader import CDLRandomBlobs
from secml.optim.constraints import \
CConstraintBox, CConstraintL1, CConstraintL2
from secml.ml.features.normalization import CNormalizerMinMax
from secml.ml.classifiers import CClassifierSVM, CClassifierDecision... | StarcoderdataPython |
172031 | <gh_stars>0
import sys
import pytest
from natural import N
from uintset import UintSet
def test_len():
assert len(N) == sys.maxsize
def test_contains():
assert 0 in N
assert 1 in N
assert -1 not in N
assert 42 in N
assert sys.maxsize in N
union_cases = [
(N, UintSet()),
(... | StarcoderdataPython |
3533841 | #! /usr/bin/env python
"""
Produces classifications of MNIST so we have something to develop calibration
tools against. The classifications are saved as a pandas dataframe.
Usage:
$ ./gen_data.py --jobs 60 --output results.pkl
"""
import argparse
import multiprocessing
import time
import numpy as np
import panda... | StarcoderdataPython |
274238 | import collections.abc
import inspect
import re
import typing
import wsgiref.simple_server
import webob
import webob.exc
from . import mappers
def generate_sitemap(sitemap: typing.Mapping, prefix: list=None):
"""Create a sitemap template from the given sitemap.
The `sitemap` should be a mapping where the k... | StarcoderdataPython |
4873388 | # -*- coding: utf-8 -*-
import sys
import requests
import time
'''
Usage:
moon.py -u tomcat http://127.0.0.1:8080
shell: http://127.0.0.1:8080/201712615.jsp?pwd=<PASSWORD>&cmd=whoami
影响范围:Linux/Windows Tomcat: 7.0.0 to 7.0.79 - 官网数据
成因:Tomcat配置了可写(readonly=false),导致我们可以往服务器写文件
最好的解决方式是将 conf/web.... | StarcoderdataPython |
248995 | import json
import numpy as np
import pandas as pd
import pickle
from sklearn import ensemble
from sklearn import datasets
from sklearn.utils import shuffle
from sklearn.metrics import mean_squared_error
from mlserve import build_schema
boston = datasets.load_boston()
X, y = shuffle(boston.data, boston.target, random_... | StarcoderdataPython |
3530461 | #
# Create 2015 tazdata map from UrbanSim input layer(s) using building data and pipeline data
# Reads
# 1) UrbanSim basemap h5 (URBANSIM_BASEMAP_FILE), parcels and buildings
# 2) Development pipeline csv (URBANSIM_BASEMAP_FILE)
# 3) Employment taz data csv (EMPLOYMENT_FILE)
#
# Outputs
#
# Notes:
# - zone_id and ... | StarcoderdataPython |
9717467 | import numpy as np
from scipy import stats
import matplotlib
matplotlib.use('tkagg')
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from scipy.stats import kde
def print_stats(labels_test, labels_predict):
''''
Calculate the following statistics from machine learning tests.
RMSE, Bias,... | StarcoderdataPython |
11319206 | import numpy as np
import pandas as pd
import os, sys
from data.load_data import f
from Representation.dkt import DKT
from Representation.problem2vec import P2V
from Qmatrix.qmatrix import Qmatrix
from AFM.load_data import load_data
from DAFM.load_data import DAFM_data
import pdb
class afm_data_generator():... | StarcoderdataPython |
267290 | <reponame>Zac-HD/datacube-core<gh_stars>1-10
from __future__ import absolute_import
from .driver_cache import load_drivers
class IndexDriverCache(object):
def __init__(self, group):
self._drivers = load_drivers(group)
if len(self._drivers) == 0:
from datacube.index.index import index... | StarcoderdataPython |
9644930 | <reponame>watchdogoblivion/watchdogs-offsec<gh_stars>0
# author: WatchDogOblivion
# description: TODO
# WatchDogs Request Parser Service
import re
from collections import OrderedDict
from watchdogs.io.parsers import FileArgs
from watchdogs.base.models import AllArgs, Common
from watchdogs.utils.StringUtility import S... | StarcoderdataPython |
11303199 | <gh_stars>100-1000
import cv2
import torch
import random
import numpy as np
from .baseline.Renderer.model import FCN
from .baseline.DRL.evaluator import Evaluator
from .baseline.utils.util import *
from .baseline.DRL.ddpg import DDPG
from .baseline.DRL.multi import fastenv
from ...util.model import BenchmarkModel
from... | StarcoderdataPython |
67661 | <reponame>lcn-kul/conferencing-speech-2022<filename>src/data/extract_features/extract_features.py
import csv
import librosa
import numpy as np
from pathlib import Path
import soundfile as sf
import torch
from torchaudio.transforms import ComputeDeltas, MFCC
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Mod... | StarcoderdataPython |
8068893 | from django.contrib import admin
from .models import StudentDataDropout
# Register your models here.
admin.site.register(StudentDataDropout) | StarcoderdataPython |
11253558 | <gh_stars>0
"""Tests for filewriter.py
"""
| StarcoderdataPython |
9699196 | <filename>eb_deployer/eb_deployer.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This is the eb deploy application for manheim hello world app
from progress.spinner import Spinner
from subprocess import Popen, PIPE
import boto3
import os
import os.path
import time
client = boto3.client('elasticbeanstalk')
curre... | StarcoderdataPython |
12844959 | <filename>tripled/stack/node.py
__author__ = 'baohua'
from subprocess import PIPE, Popen
from tripled.common.constants import NODE_ROLES
class Node(object):
"""
An instance of the server in the stack.
"""
def __init__(self, ip, role):
self.ip = ip
self.role = NODE_ROLES.get(role, NO... | StarcoderdataPython |
1770963 | from django.shortcuts import render
from django.shortcuts import render, redirect
from services.models import Service
from rest_framework.views import APIView
from django.http import JsonResponse
# Create your views here.
class AllServicesAPI(APIView):
def get(self, request, *args, **kwargs):
services ... | StarcoderdataPython |
9696098 | <filename>src/service_framework/connections/__init__.py
""" Something whitty """
| StarcoderdataPython |
118744 | import string
class StringSplitter:
def __init__(self, text):
self.string = text.lower()
self.string_list = []
self.bad = set()
for punct in string.punctuation:
if punct != "'" or punct != "-":
self.bad.add(punct)
for num in '123456789... | StarcoderdataPython |
3386944 | <reponame>banerjeesujan/leetcode<filename>Interviewbit/MyMath/IB_Math_FizzBuzz.py<gh_stars>0
import time
class Solution:
# @param A : integer
# @return a list of strings Fizz Buzz FizzBuzz
def fizzBuzz(self, A):
retArray = list()
for i in range(1, A + 1):
if i % 3 == 0 and i %... | StarcoderdataPython |
124700 | <reponame>semodi/champs-scalar-coupling<gh_stars>0
import schnetpack as spk
from schnetpack.data import Structure
import torch
from torch import nn
import numpy as np
import schnetpack
class EdgeUpdate(nn.Module):
def __init__(self, n_atom_basis, n_spatial_basis):
super(EdgeUpdate, self).__init__()
... | StarcoderdataPython |
8074773 | from typing import Optional
import histomicstk as htk
import numpy as np
import scipy as sp
import skimage.color
import skimage.io
import skimage.measure
from anndata import AnnData
from scipy import ndimage as ndi
from skimage.feature import peak_local_max
from skimage.segmentation import watershed
from tqdm import tq... | StarcoderdataPython |
1654632 | import torch
import torch.nn.functional as F
from ..models.mingpt import GPT, CGPT, NoiseInjection
from tools.utils import to_cuda
from models import load_network, save_network, print_network
from tqdm import tqdm
from ..modules.vmf import nll_vMF
class Transformer(torch.nn.Module):
def __init__(self, o... | StarcoderdataPython |
5140489 | <reponame>TitanEntertainmentGroup/django-filemaker
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
__all__ = ['FileMakerError', 'FileMakerValidationError',
'FileMakerObjectDoesNotExist', 'FileMakerConnectionError',
'FileMakerSer... | StarcoderdataPython |
3387251 | <gh_stars>1-10
import typing
from TorchTSA.simulate.GARCHSim import GARCHSim
class ARCHSim(GARCHSim):
def __init__(
self,
_alpha_arr: typing.Union[float, typing.Sequence[float]],
_const: float, _mu: float = 0.0,
):
if isinstance(_alpha_arr, float) or isinstance(_a... | StarcoderdataPython |
6477219 | <filename>test_run_generated.py<gh_stars>10-100
from fable_sedlex.sedlex import from_ustring, lexbuf
from generated import lex, lexall, Token
buf = from_ustring(r'123 2345 + += 2.34E5 "sada\"sa" ')
tokens = []
EOF_ID = 0
def is_eof(x: Token):
return x.token_id == 0
print()
print(list(lexall(buf, Token, is_eof... | StarcoderdataPython |
1745951 | <filename>lifesaver/commands/core.py
# encoding: utf-8
__all__ = ["SubcommandInvocationRequired", "Command", "Group", "command", "group"]
from discord.ext import commands
class SubcommandInvocationRequired(commands.CommandError):
"""A :class:`discord.ext.commands.CommandError` that is subclass raised when a sub... | StarcoderdataPython |
3212381 | from enum import Enum
THUMBS_UP = '+' # in case you go f-string ...
class Score(Enum):
BEGINNER = 2
INTERMEDIATE = 3
ADVANCED = 4
CHEATED = 1
def __str__(self):
return f'{self.name} => {THUMBS_UP * self.value}'
@classmethod
def average(cls):
return sum([sc... | StarcoderdataPython |
1808269 | <reponame>boladmin/security_monkey
"""
.. module: security_monkey.jirasync
:platform: Unix
:synopsis: Creates and updates JIRA tickets based on current issues
.. version:: $$VERSION$$
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import datetime
import re
import time
import urllib.request, urllib.parse, urllib.error... | StarcoderdataPython |
5053407 | <gh_stars>0
from pydantic import BaseSettings
class Settings(BaseSettings):
app_name: str = "default"
admin_email: str
token: str
database_url: str
class Config:
import os
is_prod = os.environ.get('IS_HEROKU', None)
if is_prod is None:
env_file = ".env" | StarcoderdataPython |
5044771 | <reponame>hroncok/rst2txt<gh_stars>1-10
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
entry_points={
'console_scripts': [
'rst2txt = rst2txt:main',
],
},
use_scm_version=True,
)
| StarcoderdataPython |
1751472 | import gws
import gws.types as t
class ElementConfig(gws.WithAccess):
"""GWS client UI element configuration"""
tag: str #: element tag
before: str = '' #: insert before this tag
after: str = '' #: insert after this tag
class Config(gws.WithAccess):
"""GWS client configuration"""
option... | StarcoderdataPython |
1721179 | <gh_stars>100-1000
from ..utils.registry import Registry
DATASET_REGISTRY = Registry("dataset")
def build_dataset(cfg):
"""
Build the module with cfg.
Args:
cfg (dict): the config of the modules
Returns:
The built module.
"""
args = cfg
name = args.get("name")
datase... | StarcoderdataPython |
1603704 | """Bisection algorithms."""
def insort(a, x, lo=0, hi=None):
"""Insert item x in list a, and keep it sorted assuming a is sorted."""
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)/2
if x < a[mid]: hi = mid
else: lo = mid+1
a.insert(lo, x)
def bisect(a, x, lo=... | StarcoderdataPython |
6656360 | <filename>src/make_video.py
# run as: python make_video.py
import numpy as np
import os
import matplotlib.pyplot as plt
fiber = 0
model = 0
ve_path = os.path.join('..', 've_files', f'model{model}_fiber{fiber}.dat')
print('ve_path: {}'.format(ve_path))
ve = -1*np.loadtxt(ve_path, skiprows=1)
coords_path = os.path.jo... | StarcoderdataPython |
4898596 | from __future__ import print_function
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 10 13:18:46 2015
@author: nadiablago
"""
from matplotlib import pylab as plt
import glob
from astropy.io import fits as pf
import os, sys
from optparse import OptionParser
import matplotlib
import numpy as np
from astropy.wcs import... | StarcoderdataPython |
6458196 | # -*- coding: utf-8 -*-
import pydash as _
from config import settings
from . import redis_2_elasticsearch, kafka_2_elasticsearch
class Queue2ElasticsearchClient(object):
@property
def client(self):
return self.__client
def __init__(self, mode=None):
self.__switch = {
'redi... | StarcoderdataPython |
9781072 | from decimal import Decimal
import math
import numpy as np
import pandas as pd
import unittest
from hummingbot.strategy.__utils__.trailing_indicators.trading_intensity import TradingIntensityIndicator
class TradingIntensityTest(unittest.TestCase):
INITIAL_RANDOM_SEED = 3141592653
BUFFER_LENGTH = 200
def ... | StarcoderdataPython |
9688786 | <reponame>jsonchin/nba_dfs_dashboard
from .player import player_profile_endpoint, player_logs_endpoint, player_averages_endpoint
from .game import game_endpoint, game_team_specific_endpoint
from .game_date_games import game_date_games_endpoint
from .file_upload import file_upload_draftkings
from .lineups import lineups... | StarcoderdataPython |
61877 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PART... | StarcoderdataPython |
11274481 | from pymoo.algorithms.nsga2 import RankAndCrowdingSurvival
from pymoo.algorithms.so_de import DE
from pymoo.docs import parse_doc_string
from pymoo.model.population import Population
from pymoo.util.display import MultiObjectiveDisplay
from pymoo.util.dominator import get_relation
class GDE3(DE):
def __init__(se... | StarcoderdataPython |
3528388 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import requests
import json
from time import time
import datetime
from loremipsum import *
import random
import math
import os
from .. import firebase_pushid
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)... | StarcoderdataPython |
6627798 | <gh_stars>0
# Copyright (C) 2016 <NAME>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | StarcoderdataPython |
8170709 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: helm_info
short_descrip... | StarcoderdataPython |
8077561 | <reponame>meghanaravikumar/sigopt-examples
from distilbert_data_model_loaders.load_transfomer_model import LoadModel
import logging
class LoadPretrainedModel(LoadModel):
def __init__(self, model_type, model_name_or_path, cache_dir):
super().__init__(model_type)
self.model_name_or_path = model_nam... | StarcoderdataPython |
1981674 | <gh_stars>0
#!/usr/bin/env python
"""Example of a basic tractor behavior.
This module demonstrates an example behavior written in python to be
compatible with the state controller. The behavior publishes any
command received on /ex_topic directly to the corresponding topic
/state_controller/cmd_behavior.
authored by ... | StarcoderdataPython |
1918781 | <reponame>Cheaterman/PySAMP<gh_stars>10-100
import random
from samp import *
from glspawns import *
from funcs import *
from vars import *
from player import *
################################
"""
Hello dear user!
Welcome to the Python version of the original Grand Larceny gamemode!
We wanted to convert this classic ... | StarcoderdataPython |
358212 | #!/usr/bin/env python
import httplib
connection = httplib.HTTPSConnection("www.google.com", 443)
connection.request("GET", "/")
response = connection.getresponse()
print response.status
data = response.read()
print data
| StarcoderdataPython |
6440067 | <reponame>SectorLabs/django-localized-fields
from datetime import datetime
from django.core.exceptions import ImproperlyConfigured
from django.utils.text import slugify
from ..mixins import AtomicSlugRetryMixin
from ..util import get_language_codes
from ..value import LocalizedValue
from .autoslug_field import Locali... | StarcoderdataPython |
386294 | import catboost
from catboost import CatBoostClassifier
from xgboost import XGBClassifier
import gc
from sklearn.linear_model import LogisticRegression
from sklearn import preprocessing
import pandas as pd
import numpy as np
#add
#stopping dev due to xgboost issues
df_train_data = pd.read_csv('data\\full_train.csv',n... | StarcoderdataPython |
9771500 | <reponame>lleej/python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'枚举类的练习'
__author__ = 'Jacklee'
# 导入模块
#import types
# 月份常量
JAN = 1
FEB = 2
MAR = 3
# 枚举类
from enum import Enum, unique
## 第一种定义方式
@unique
class Month(Enum):
JAN = 0
FEB = 1
MAR = 2
## 第二种定义方式
WeekDay = Enum('WeekDay', ('Mon', 'Tue', 'Wed',... | StarcoderdataPython |
3534383 | # Generated by Django 3.1.3 on 2021-01-11 22:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hackathon', '0024_auto_20201103_2114'),
]
operations = [
migrations.AlterModelOptions(
name='hackteam',
options={'ve... | StarcoderdataPython |
1698709 | <reponame>TheInitializer/evolution_simulator<gh_stars>1-10
from pyglet.sprite import Sprite
import pyglet
from dna_parser import parse_dna, distance
import dna_parser
import random
from config import window_width, window_height
import food
import mutation
creatures = []
class Creature(Sprite):
signal = 0
att... | StarcoderdataPython |
6540773 | <gh_stars>0
n=sum(list(map(int,input().split())))
if n%5 or n==0:
print(-1)
else:
print(n//5)
| StarcoderdataPython |
1940004 |
import pytest
from discord.ext.test import message, verify_message, verify_embed, verify_file
pytestmark = pytest.mark.usefixtures("testlos_m")
async def test_aesthetic():
await message("^aesthetic Sphinx of black quartz, judge my vow")
verify_message("Sphinx of black quartz, judge my vow")
async def te... | StarcoderdataPython |
1947204 | from typing import Dict, List
from numpy import ndarray, zeros
import plotly.graph_objects as go
from bayesian_mmm.spend_transformation.spend_transformation import (
compute_hill,
compute_reach
)
class DiminushingReturnsVisualizor:
def __init__(self, param_nm_to_val: Dict, media_nms: List[str]) -> None:
... | StarcoderdataPython |
8126783 | <filename>ProjectInfo/tools/FeaturesToPoint.py
'''-------------------------------------------------------------------------------
Tool Name: FeaturesToPoint
Source Name: FeaturesToPoint.py
Version: ArcGIS 10.1
License: Apache 2.0
Author: <NAME>
Updated by: <NAME>
Description: Description: Create... | StarcoderdataPython |
175681 | <filename>img_upload/config.py
import os
S3_BUCKET = ""
S3_KEY = ""
S3_SECRET = ""
S3_LOCATION = 'http://{}.s3.amazonaws.com/'.format(S3_BUCKET)
DEBUG = True
PORT = 5000 | StarcoderdataPython |
11374963 | <reponame>alvarosanz/loadit
import wx
import os
from loadit.misc import humansize
from loadit.gui.table_info_dialog import TableInfoDialog
class DatabaseInfoDialog(wx.Dialog):
def __init__(self, parent, database, active_tab=0):
super().__init__(parent)
self.database = database
self.SetTit... | StarcoderdataPython |
3560673 | <gh_stars>0
from card import Card
class Player:
name : str
card : Card
def __init__(self, name, card):
self.name = name
self.card = card
| StarcoderdataPython |
3306669 | <reponame>ec1340/ReLSO-Guided-Generative-Protein-Design-using-Regularized-Transformers<filename>relso/optim/optim_algs.py
"""
Optimization algorithms
"""
import numpy as np
import numpy.ma as ma
import numpy.linalg as LA
import copy
from tqdm import tqdm
from scipy.spatial import distance
from sklearn.neighbors i... | StarcoderdataPython |
6510551 | <gh_stars>1-10
# coding: utf-8
from pycocotools.coco import COCO
import argparse
import numpy as np
import skimage.io as io
import matplotlib.pyplot as plt
import pylab
import os, os.path
import pickle
from tqdm import tqdm
parser = argparse.ArgumentParser(description="Preprocess COCO Labels.")
#dataDir='/share/data... | StarcoderdataPython |
4956576 | <filename>st2tests/st2tests/fixturesloader.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Ver... | StarcoderdataPython |
8018654 | <gh_stars>1-10
from pathlib import PosixPath
import botocore
from ..util.log import Log, log_call
from .client import with_client
_log = Log('s3.api')
@with_client
@log_call('s3.api', 'Making api call `{func}` {kwargs}')
def ls(client, bucket = None):
if bucket is None:
_log.debug("Bucket not provided, listing u... | StarcoderdataPython |
3352981 | import json
import re
from datetime import datetime
# Read my timeline
with open('myTimeline.json', 'r', encoding='utf-8') as f:
timeline = json.loads(f.read())
# Read stock JSON data
with open('../LS/isins.json', 'r', encoding='utf-8') as f:
lsIsins = json.loads(f.read())
# All stocks crawled from TR
with o... | StarcoderdataPython |
4911556 | <reponame>bcherry/bcherry
def deposit(amt):
f = open('data')
bal = int(f.readline())
f.close()
f = open('data','w')
| StarcoderdataPython |
6461676 | """
PostgreSQL accounts and databases for members and societies.
"""
from functools import wraps
from typing import Optional, List, Set, Tuple, Union
from psycopg2.extensions import connection as Connection, cursor as Cursor
from srcf.database import Member, Society
from srcf.database.queries import get_member, get_... | StarcoderdataPython |
11372494 | #https://www.kaggle.com/kyakovlev/ieee-simple-lgbm
# General imports
import numpy as np
import pandas as pd
import os, sys, gc, warnings, random, datetime
import time
import pickle
from sklearn import metrics
from sklearn.model_selection import train_test_split, KFold
from sklearn.preprocessing import LabelEncoder
fro... | StarcoderdataPython |
6461708 | <filename>PIP/Minor Assignment 7/a7q2.py
def cumulative(lst):
c_lst=[ ]
length=len(lst)
c_lst=[ sum(lst[0:x:1]) for x in range(0, length +1)]
return c_lst[1:]
lst=[1,2,3,4,5]
print(cumulative(lst))
| StarcoderdataPython |
5055805 | <gh_stars>10-100
#-*- coding: utf-8 -*-
import random,io
import matplotlib.pyplot as plt
import numpy as np
from .public import *
图表颜色 = [
'#F0F8FF', '#FAEBD7', '#00FFFF', '#7FFFD4', '#F0FFFF', '#F5F5DC', '#FFE4C4', '#FFEBCD', '#8A2BE2', '#A52A2A',
'#DEB887', '#5F9EA0', '#7FFF00', '#D2691E', '#FF7F50', '#6495... | StarcoderdataPython |
4890657 | import numpy as np
class Image:
'''
Class to hold image data
Attributes
-----------
img: np.ndarray
numpy ndarray containing the image as grayscale float values,
should be normalized to [0, 1.0]
timestamp: astropy.time.Time
Time when the image was taken
timestamp: ... | StarcoderdataPython |
4944561 | from .compressor import *
from .pop import *
| StarcoderdataPython |
1902043 | <reponame>Schwarzbaer/behavior_machine
from behavior_machine.library import WaitState, IdleState
import pytest
from behavior_machine.board import Board
from behavior_machine.core import State, StateStatus, Machine
class SetState(State):
_val: str
_key: str
def __init__(self, name, key, val):
su... | StarcoderdataPython |
9644434 | import argparse
import collections
import json
import logging
from pathlib import Path, PurePath
from utils.log import setup_logging
def main():
with open(__file__, 'r') as f:
_source = f.read()
# Use first line of file docstring as description if it exists.
parser = argparse.ArgumentParser(
... | StarcoderdataPython |
5160040 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'loginPage.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import ... | StarcoderdataPython |
11208644 | """Merge Stardist Masks."""
| StarcoderdataPython |
6556768 | #!/usr/bin/env python
__author__ = "<NAME>"
__copyright__ = "Copyright 2021, The MUDCake Project"
__credits__ = "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
__license__ = """MIT License
Copyright (c) 2021 MUDCake Project
Permission is hereby granted, free of charge, to a... | StarcoderdataPython |
5142843 | import hashlib
import os
try:
import cart
from utils import random_id_from_collection
except ImportError:
import pytest
import sys
if sys.version_info < (3, 0):
pytestmark = pytest.mark.skip
else:
raise
def test_children(datastore, client):
submission_id = random_id_from_c... | StarcoderdataPython |
253634 | <filename>class1/p34_GradientTape.py
import tensorflow as tf
with tf.GradientTape() as tape:
x = tf.Variable(tf.constant(3.0))
y = tf.pow(x, 2)
grad = tape.gradient(y, x)
print(grad)
| StarcoderdataPython |
4812779 | <filename>fraud_networks/tests/test_dispersion_trees.py
from fraud_networks import DispersionTree, DispersionEdges
#from utilities.dispersion_trees import DispersionTree, DispersionEdges
from fraud_networks.utilities import test_data
import networkx as nx
def test_DispersionEdges():
disp_edges = DispersionEdges(t... | StarcoderdataPython |
4899545 | """
:Copyright: 2006-2021 <NAME>
:License: Revised BSD (see `LICENSE` file for details)
"""
from unittest.mock import patch
import pytest
from pytest import raises
from byceps.events.ticketing import TicketsSold
from byceps.services.shop.order import action_service, action_registry_service
from byceps.services.shop.... | StarcoderdataPython |
1626871 | import csv
import numpy as np
from typing import Dict, List
from PyQt5.QtGui import QImage, QColor
import src.core.config as config
def parse(path: str, num_classes: int) -> Dict[int, List[np.ndarray]]:
with open(path, newline='\n') as csv_file:
data_set = prepare_data_set_dict(num_classes)
data_... | StarcoderdataPython |
1701629 | import unittest
import os
import tempfile
from filecmp import cmp
from subprocess import call
import sys
import py_compile
#python -m unittest tests/test_coverage_filter.py
class CoverageFilterTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
#locate the bin and test_data directories
... | StarcoderdataPython |
6561340 | # from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow import keras
from time import strftime
from corl.model.tf2.common import DelayedCosineDecayRestarts
class GlobalStepMarker(keras.layers.Layer):
'''
Record global steps.
'''
... | StarcoderdataPython |
11283913 | <reponame>gafusion/omas
'''pypi setup file
-------
'''
# --------------------------------------------
# external imports
# --------------------------------------------
import os
import sys
with open(os.path.abspath(str(os.path.dirname(__file__)) + os.sep + 'version'), 'r') as _f:
__version__ = _f.read().strip()
... | StarcoderdataPython |
4814504 | from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Activation, MaxPooling2D, Conv2D
from keras import optimizers
from keras import regularizers
from keras import applications
def model(img_size, num_class):
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape... | StarcoderdataPython |
310690 | """The tests for the notify.persistent_notification service."""
from homeassistant.components import notify
import homeassistant.components.persistent_notification as pn
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
async def test_async_send_message(hass: HomeAssis... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.