id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
88425
<gh_stars>0 class GuidAttribute: """ Supplies an explicit System.Guid when an automatic GUID is undesirable. GuidAttribute(guid: str) """ def ZZZ(self): """hardcoded/mock instance of the class""" return GuidAttribute() instance=ZZZ() """hardcoded/returns an instance of the class""" def __init...
StarcoderdataPython
3297403
<filename>controllers/merchants_controller.py from flask import Blueprint, Flask, render_template, request, redirect from models.merchant import Merchant import repositories.transaction_repository as transaction_repo import repositories.merchant_repository as merchant_repo import repositories.tag_repository as tag_rep...
StarcoderdataPython
3204177
<filename>BackEnd/src/app/domain/collections/transactions/transactionsDatabaseAccess.py from src.app.domain.collections.transactions.transactionsDatabaseUtility import * import src.app.domain.collections.transactions.transactionsQueries as transactionsQueries import src.app.domain.collections.portfolios.portfoliosData...
StarcoderdataPython
7896
## Program: VMTK ## Language: Python ## Date: January 12, 2018 ## Version: 1.4 ## Copyright (c) <NAME>, <NAME>, All rights reserved. ## See LICENSE file for details. ## This software is distributed WITHOUT ANY WARRANTY; without even ## the implied warranty of MERCHANTABILITY or FITNESS FOR A PAR...
StarcoderdataPython
3215002
<reponame>djaodjin/djaodjin-signup # Copyright (c) 2019, Djaodjin Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice,...
StarcoderdataPython
50289
""" Use a common library (skimage) as a source of truth for experimental images to analyze """ import skimage import pathlib import numpy as np import matplotlib.pyplot as plt from PIL import Image def saveImage(data: np.ndarray, name: str): # save it to disk repoRoot = pathlib.Path(__file__).parent.parent ...
StarcoderdataPython
4835234
# As documented in the NRPy+ tutorial module # Tutorial-RK_Butcher_Table_Generating_C_Code_new_way.ipynb, # this module will produce the required C codes for # allocating required memory Method of Lines (MoL) timestepping, # implementing MoL timestepping, and deallocating memory # Authors: <NAME> # <N...
StarcoderdataPython
3236038
import string from typing import Dict, List, Tuple import numpy as np import pandas as pd import scipy.stats from .exposure import compute_exposure from .models import ExpModel __all__ = ["SignalGenerator"] class SignalGenerator: """Class for generating sample signals.""" def __init__( self, ...
StarcoderdataPython
3218038
<reponame>Preocts/twwordmap from typing import Any from typing import Dict from typing import List class Includes: tweets: List[Any] users: List[Any] places: List[Any] media: List[Any] polls: str @classmethod def build_obj(cls, obj: Dict[str, Any]) -> "Includes": """Build object""...
StarcoderdataPython
1769596
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
StarcoderdataPython
3385435
# -*- coding: utf-8 -*- import sys #网易数据来源 import traceback import pandas as pd from pandas.tseries.offsets import * from sqlalchemy import text import numpy as np from webapp.services import db, db_service as dbs from flask import current_app as app from datetime import datetime def getFinanceDataFromNet(code): ...
StarcoderdataPython
109269
import operator, msgpack, nltk, math, sys, os from nltk.corpus import stopwords from datetime import datetime from tqdm import tqdm from argparse import ArgumentParser import numpy as np import dateutil.parser from utils import settings, liwc_keys, lsm_keys, open_for_write, DEFAULT_TIMEZONE from normalizer import e...
StarcoderdataPython
1639529
"""This file contains tests for new features/changes that haven't been designated to a file yet. Feel free to use this function as a playground to test your changes & additions.""" #TODO: Depth of ImageVolume from test_vars import *
StarcoderdataPython
4841260
import argparse class ParseableObject: PARSER_NAME = "parse" HELP = "Default parseable object" def __init__(self): pass @classmethod def get_parser(cls): parser = argparse.ArgumentParser(description=cls.HELP, add_help=False) cls.add_arguments(parser) return parser...
StarcoderdataPython
35339
<filename>app/editor/animation_editor/animation_tab.py from app.resources.resources import RESOURCES from app.extensions.custom_gui import ResourceListView from app.editor.data_editor import SingleResourceEditor from app.editor.base_database_gui import DatabaseTab from app.editor.animation_editor import animation_mod...
StarcoderdataPython
3316268
<gh_stars>0 import itertools import random import string from functools import reduce import PIL from PIL import Image, ImageDraw, ImageFont # block of letters # # numbers at top, each one is an index into the block, row-wise. these are general clues for the # rest of the puzzle # # lastly, each letter is a colour. t...
StarcoderdataPython
1661316
#!/usr/bin/python import sys import json param_file=sys.argv[1] param_name=sys.argv[2] with open(param_file) as data_file: data = json.load(data_file) try: value = data['parameters'][param_name]['value'] except: sys.stderr.write('cannot get parameter value\n') else: print value
StarcoderdataPython
3395058
<gh_stars>0 import io, sys, typing, datetime from .common import Report, readable_message, Event ################################################################################ def not_colored(s, *args, **kwargs): return s try: from termcolor import colored except ImportError: colored = not_colored ###...
StarcoderdataPython
4106
<filename>base/site-packages/django_qbe/urls.py # -*- coding: utf-8 -*- from django.conf.urls.defaults import patterns, url from django_qbe.exports import formats urlpatterns = patterns('django_qbe.views', url(r'^$', 'qbe_form', name="qbe_form"), url(r'^js/$', 'qbe_js', name="qbe_js"), url(r'^results/bookm...
StarcoderdataPython
4842991
<filename>report_generator/controller/report_generator_cli.py import logging import pkg_resources import click import pandas as pd import report_generator.config as report_generatorconfig import report_generator.analyzer.generic as ag import report_generator.viewer.text as vtext import report_generator.analyzer.plott...
StarcoderdataPython
1730457
<reponame>amol-/blackhole import shelve import atexit import threading from multiprocessing.managers import SyncManager class KeyManager: def __init__(self): self._lock = threading.Lock() self._shelve = shelve.open("./shelve.db", writeback=True) def get_key(self, key): with se...
StarcoderdataPython
3288434
import discord from discord.errors import InvalidArgument from redbot.core import commands, Config, checks from redbot.core.utils.menus import DEFAULT_CONTROLS, menu class NonNitroEmoji(commands.Cog): def __init__(self, bot): self.bot = bot self.config = Config.get_conf(self, identifier=345...
StarcoderdataPython
3213008
#z .util zaimportuj util z .. zaimportuj subpackage
StarcoderdataPython
3283591
import numpy as np import numba as nb from neutralocean.traj import _ntp_bottle_to_cast @nb.njit def bfs_conncomp1(G, A, r): """ Find the Connected Component containing 1 reference location using Breadth-first Search Parameters ---------- G : ndarray of bool A 1D array of logicals. ...
StarcoderdataPython
3348166
import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '../../'))
StarcoderdataPython
135639
<gh_stars>1-10 """ stk.logging.py Utility library for logging with qi. """ __version__ = "0.1.2" __copyright__ = "Copyright 2015, Aldebaran Robotics" __author__ = 'ekroeger' __email__ = '<EMAIL>' import functools import traceback import qi def get_logger(session, app_id): """Returns a qi logger object.""" ...
StarcoderdataPython
1720737
import RPi.GPIO as gpio import time import twilioMessaging as twilio gpio.setmode(gpio.BOARD) gpio.setup(16, gpio.IN) def parse(database): """ Parses the database file type database: file rtype: dict (with 'id' as key and 'mobile no.' as value) """ db = {} for line in database: line = line.strip() ...
StarcoderdataPython
39556
<gh_stars>1-10 from Pluto.Systems.Systems import *
StarcoderdataPython
1603687
import discord import threading import asyncio from discord.ext import commands from collections import Counter #the poll cog class class Poll(commands.Cog): def __init__(self, bot): self.bot = bot self.votes = [] self.voters = [] self.options = [] self.polll = False ...
StarcoderdataPython
44435
from django.views.generic import ListView, DetailView, TemplateView, CreateView, UpdateView, DeleteView from board.models import Post from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from mysite.views import OwnerOnlyMixin from django.conf import settings #--- ListView c...
StarcoderdataPython
1620477
friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends: print('Happy New Year:', friend) for i in range(len(friends)): friend = friends[i] print('Happy New Year:', friend)
StarcoderdataPython
98582
<filename>hackathonbaobab2020/execution/__init__.py from .run_batch import * import warnings try: from .benchmark import * except ImportError: warnings.warn( "To use the benchmark functions, you need to install the benchmark dependencies: \n`pip install hackathonbaobab2020[benchmark]`" )
StarcoderdataPython
3201234
<reponame>arunkumarang/python<gh_stars>0 #!/usr/bin/python import sys def main(): guest_lists = ['senthil', 'raj', 'ameen'] guest_lists.insert(0, 'naveen') guest_lists.insert(2, 'prabhu') guest_lists.append('ragu') print() removed_person = guest_lists.pop() print("Sorry " +...
StarcoderdataPython
183538
<filename>ca-majority.py import pycxsimulator from pylab import * width = 50 height = 50 numberOfStates = 2 r = 1 def initialize(): global time, config, nextConfig time = 0 config = zeros([height, width]) for x in range(width): for y in range(height): config[y...
StarcoderdataPython
3212964
from __future__ import unicode_literals import abc import logging import six import semantic_version from lymph.utils import observables, hash_id from lymph.core.versioning import compatible, serialize_version logger = logging.getLogger(__name__) # Event types propagated by Service when instances change. ADDED = '...
StarcoderdataPython
3260536
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from argparse import ArgumentParser, FileType from collections import OrderedDict from tempfile import NamedTemporaryFile, mkdtemp import numpy as np from pyfr.inifile import Inifile from pyfr.progress_bar import ProgressBar from pyfr.readers.native...
StarcoderdataPython
1747141
<reponame>jonashagstedt/django-jsx from django.template import RequestContext from django.test import TestCase from django_jsx.templatetags import djangojs from django_jsx.templatetags.djangojs import JsMissingTemplateDirException class TestLoader(TestCase): def test_render_template(self): """ Ren...
StarcoderdataPython
3207663
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
StarcoderdataPython
3316044
<filename>space_manager/membership/views.py from rest_framework.views import APIView from rest_framework.response import Response from . import models, serializers from space_manager.users import models as users_models from space_manager.payment import models as payment_models from space_manager.payment import serializ...
StarcoderdataPython
4807764
# Generated by Django 3.0.2 on 2020-04-08 00:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('calendarMod', '0006_auto_20200408_0033'), ] operations = [ migrations.RenameField( model_name='event', old_name='month_name'...
StarcoderdataPython
101411
from driver_class import DataDriver import mysql.connector from mysql.connector import errorcode from getpass import getpass class MySQLDataDriver(DataDriver): def load(self): mysql_config = { "connect": { "host": self.config.get("host") or "localhost", "port": ...
StarcoderdataPython
51513
import pytest from jobs.statuses import JobStatus @pytest.mark.parametrize( "code,value", [ (JobStatus.SENT_TO_DPS, "SENT_TO_DPS"), (JobStatus.PROCESSED_BY_DPS, "PROCESSED_BY_DPS"), (JobStatus.COMPLETE, "COMPLETE"), (JobStatus.NOTIFIED_VALIDATION_FAILED, "NOTIFIED_VALIDATION_FA...
StarcoderdataPython
3301728
import logging import os import random import shutil import subprocess import sys import tempfile import time from ipaddress import ip_address import dpkt import pytest import deckard from contrib.namespaces import LinuxNamespace from networking import InterfaceManager def set_coverage_env(path, qmin): """Sets ...
StarcoderdataPython
65956
<filename>first.py from locorobo import LocoRobo from locorobo import MotorDirection from locorobo import Data from locorobo import WaitType from locorobo import Song from locorobo import Note def get_robot(robots, name): robot = None # Search through robots found during the scan for # the one we want ...
StarcoderdataPython
37611
import json import argparse import pprint import csv parser = argparse.ArgumentParser(description="parse squad qa into scv") parser.add_argument("--input", type=str) parser.add_argument("--output", type=str) args = parser.parse_args() input_file = args.input output_file = args.output with open(input_file, 'r') as f: ...
StarcoderdataPython
193268
from pathlib import Path import click import pytest from _pytest.config import Config as PytestConfig import ape from ape.logging import logger from ape.utils import ManagerAccessMixin from ape_console._cli import console from .contextmanagers import RevertsContextManager class PytestApeRunner(ManagerAccessMixin):...
StarcoderdataPython
1701169
from datetime import datetime from loguru import logger from home_guardian.repository.model.trained_face import TrainedFace @logger.catch def save_or_update(username: str) -> TrainedFace: """ Save or update a trained face. :param username: The username of the trained face. :return: a new trained fac...
StarcoderdataPython
3398435
<reponame>athos-ribeiro/atomic-reactor """ Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. Combines the module information looked up by pre_resolve_module_compose, combines it with additional info...
StarcoderdataPython
175793
<reponame>Foxtrot-813/Youtube-Playlist-Downloader import os import re from pytube import Playlist url = input("Playlist link:\n") choice = int(input("Please choose one of the options:\n1-Audio\n2-Video\n3-Quit\n")) playlist = Playlist(url) if choice == 3: exit(1) def get_audio(): print(f'Download...
StarcoderdataPython
3278436
<gh_stars>0 import json import os import zipfile from django.contrib.auth.hashers import check_password, make_password from django.http import HttpResponse, FileResponse, StreamingHttpResponse from django.shortcuts import render # Create your views here. from RootAPP.models import PathItem, FileItem from UserAPP.model...
StarcoderdataPython
1663317
from django.shortcuts import render from visitantes.models import Visitante from django.utils import timezone from django.contrib.auth.decorators import login_required @login_required def index(request): todos_visitantes = Visitante.objects.order_by("-horario_chegada") visitantes_aguardando = todos_visitant...
StarcoderdataPython
64196
<gh_stars>1-10 try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='djangoool', version=__import__('djangoool').__version__, description='A Django interface to the pycountry module.', author='<NAME>', author_email...
StarcoderdataPython
1702712
<reponame>mbonsma/PhD-materials #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 28 14:46:00 2021 @author: madeleine This script loads simulation files and processes them into an array, then updates all_data.csv Requires all_data.csv to be available in the same folder Requires all_params.csv to ...
StarcoderdataPython
3394022
from django.conf.urls import url,include from django.contrib import admin from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings from photos import views as photo_views #differentiates the two from django.conf.u...
StarcoderdataPython
138583
""" Generate C++ character set conversion tables. This script takes the conversion tables from https://encoding.spec.whatwg.org as its input, performs some tweaks, and generates forward and reverse compressed conversion tables. For conversions in both directions, the code 0xFFFD will indicate a failed character conve...
StarcoderdataPython
130441
from typing import List, Optional import base58 from common.serializers.serialization import proof_nodes_serializer, \ state_roots_serializer from plenum.common.txn_util import get_type, get_payload_data, get_seq_no, reqToTxn from sovtoken.messages.validation import static_req_validation from plenum.server.ledge...
StarcoderdataPython
3362213
""" Problem 9 Special Pythagorean triplet """ from utility.decorators import timeit, printit def is_pythag(a, b, c): return a**2 + b**2 == c**2 def is_answer(a, b, c): return a+b+c == 1000 @printit @timeit def run(): a, b, c = 1, 1, 1 s = 1000 found = False for a in range(1, int(s...
StarcoderdataPython
3358002
from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Reference(models.Model): title = models.CharField(max_length = 250) description = models.CharField(max_length=250) ## description = models.TextField() link...
StarcoderdataPython
24245
from uncertainties import ufloat from utilities import min_value, max_value def main(): print 'Plate motion rate parallel to section' print plate_motion() print 'Shortening (including ductile) from bed-length' print bed_length_shortening() print 'Estimated total shortening accomodated by OOSTS' ...
StarcoderdataPython
3384508
<gh_stars>0 #!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """code generator for OpenGL ES 2.0 conformance tests.""" import os import re import sys def ReadFileAsLines(filename...
StarcoderdataPython
1756453
""" Copyright: MAXON Computer GmbH Author: <NAME> Description: - Reads the Float value of the first channel available from a Volume stored in a Volume Builder. Class/method highlighted: - maxon.frameworks.volume.GridAccessorInterface - GridAccessorRef.GetValue() """ import c4d import maxon from maxon.fra...
StarcoderdataPython
3311029
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/chart_plot_bar.ipynb (unless otherwise specified). __all__ = ['PlotBar'] # Cell from .chart import Chart from .base_plot import BasePlot from .data_model import construct_categorical_data import pandas as pd from bokeh.models.ranges import FactorRange, Range1d fro...
StarcoderdataPython
32662
# Pro-Football-Reference.com # TEAMS import re, os import uuid import json from datetime import datetime, date, time from bs4 import BeautifulSoup import bs4 from Constants import * from PathUtils import * from PluginSupport import * from Serialization import * from StringUtils import * import ProFoo...
StarcoderdataPython
194511
<filename>gpsTime.py<gh_stars>0 import numpy as np from math import modf import datetime as dt import calendar def cal2jd(yr,mn,dy) : """ CAL2JD Converts calendar date to Julian date using algorithm from "Practical Ephemeris Calculations" by <NAME> (Springer-Verlag, 1989). Uses astronomical year for ...
StarcoderdataPython
1796163
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-30 07:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
StarcoderdataPython
3398881
from ...isa.inst import * import numpy as np class Fnmadd(Inst): name = 'fnmadd.s' def golden(self): return -self['rs1']*self['rs2']-self['rs3']
StarcoderdataPython
135728
<filename>ui/NommageTitleWindow.py import sys from PyQt5.QtCore import pyqtSlot, QPoint, Qt, QRect,pyqtSignal from PyQt5.QtWidgets import (QMainWindow, QApplication, QPushButton, QHBoxLayout, QVBoxLayout, QTabWidget, QWidget, QAction,QMessageBox, QLabel, QSizeGr...
StarcoderdataPython
1724091
# Generated by Django 2.1.1 on 2018-09-25 16:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('dominio', '0002_auto_20180925_1330'), ('dominio', '0003_turno'), ] operations = [ ]
StarcoderdataPython
3236529
<filename>gym_cellular_automata/forest_fire/utils/config.py import numpy as np # Load the YAML configuration file into a python dict def get_config_dict(file): import yaml yaml_file = open(file) yaml_content = yaml.load(yaml_file, Loader=yaml.SafeLoader) return yaml_content ########################...
StarcoderdataPython
109592
<filename>tests/test_testing.py from unittest.mock import Mock from ward import expect from ward.fixtures import fixture from ward.testing import Test, test def f(): expect(1).equals(1) mod = "my_module" t = Test(fn=f, module_name=mod) @fixture def anonymous_test(): def _(): expect(1).equals(1) ...
StarcoderdataPython
21536
from django.contrib.auth.models import User from rest_framework import viewsets from rest_framework import permissions from rest_framework.response import Response from blog.models import Post from blog.serializers import PostSerializer from blog.serializers import UserSerializer from blog.permissions import IsAuthor...
StarcoderdataPython
188091
<filename>examples/node_classification.py<gh_stars>1-10 import sys sys.path.append('../') from autogl.datasets import build_dataset_from_name from autogl.solver import AutoNodeClassifier from autogl.module import Acc import yaml import random import torch import numpy as np import logging logging.basicConfig(level=log...
StarcoderdataPython
5082
""" Test that escaping characters for HTML is disabled. """ import os, subprocess def test_escape_singlequote(tmpdir): # Define empty dictionaries doc = {} template = {} # Prepare file names doc['path'] = tmpdir.join("document.md") template['path'] = tmpdir.join("template.yaml") # Prepar...
StarcoderdataPython
5396
""" Migration script to add 'ldda_parent_id' column to the implicitly_converted_dataset_association table. """ from sqlalchemy import * from sqlalchemy.orm import * from migrate import * from migrate.changeset import * import logging log = logging.getLogger( __name__ ) metadata = MetaData() def upgrade(migrate_engi...
StarcoderdataPython
1612836
from distutils.core import setup setup( name='maluuba_napi', version='0.0.1', author='Maluuba', author_email='<EMAIL>', packages=['maluuba_napi'], url='http://developer.maluuba.com', license='LICENSE', description='A simple wrapper for consuming the Maluuba NLP API', long_descriptio...
StarcoderdataPython
95102
from app import db class Appointment(db.Model): __tablename__ = 'appointment' id = db.Column(db.Integer, primary_key=True) start = db.Column(db.DateTime, nullable=False) end = db.Column(db.DateTime, nullable=False) description = db.Column(db.String(1000, collation='utf8_general_ci'), ...
StarcoderdataPython
98693
<filename>pytglib/api/types/storage_statistics_by_file_type.py<gh_stars>1-10 from ..utils import Object class StorageStatisticsByFileType(Object): """ Contains the storage usage statistics for a specific file type Attributes: ID (:obj:`str`): ``StorageStatisticsByFileType`` Args: ...
StarcoderdataPython
93567
<filename>python-midonetclient/src/midonetclient/auth_lib.py # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Midokura PTE LTD. # 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 cop...
StarcoderdataPython
3374032
<reponame>transferwise/neural-lifetimes from typing import Dict, Union import numpy as np from sklearn.preprocessing import OrdinalEncoder import torch # TODO What does this function actually do? it doesn't normalize the data def normalize(x): """ Normalize the data. Only 1 encoding is handled at a time. ...
StarcoderdataPython
4815311
<gh_stars>1-10 from setuptools import setup, find_packages setup( name="dotlas", version="1.0", description="Dotlas Python Package", author="<NAME>.", author_email="<EMAIL>", url="https://github.com/dotlas/api-client-python", packages=find_packages(), python_requires=">=3.8", long_d...
StarcoderdataPython
3382838
import sys def messagetemplate(username, message, time, sides): talker = sides[0] chatmate = sides[1] if username == talker["username"]: user_is_talker = True elif username == chatmate["username"]: user_is_talker = False else: print (sys.stderr, f"unknown username in source file: {username}") print(e) ...
StarcoderdataPython
3251447
from dataclasses import dataclass from django.urls import reverse @dataclass class ToolbarItem: label: str is_active: bool url: str def toolbar(request): def create_item(label, view_name): url = reverse(view_name) return ToolbarItem(label=label, is_active=request.path.startswith(url...
StarcoderdataPython
33656
<reponame>jensengroup/fragreact<gh_stars>1-10 #!/usr/bin/env python import numpy as np import re from rdkit import Chem from rdkit.Chem import rdMolDescriptors from itertools import combinations import copy def print_smiles(smiles_list, human=False): smiles_dict = count_smiles(smiles_list) keys = smiles_dic...
StarcoderdataPython
3366895
# coding: utf8 from datetime import datetime import logging import re from config import config from models import Gossip from .utils import get_image logger = logging.getLogger(__name__) crawler = config.crawler normal_pattern = re.compile(r'<span style="color:#[0-9a-fA-F]*">(.*)</span>') total_p...
StarcoderdataPython
128462
<gh_stars>1-10 """Library for simple data processing tasks."""
StarcoderdataPython
1664431
"""Tests for module `transform_reorder.py`.""" import numpy as np from numpy.testing import assert_array_equal import pytest from hypermodern_screening.transform_reorder import ( ee_corr_reorder_sample, ee_uncorr_reorder_sample, reorder_cov, reorder_mu, reverse_ee_corr_reorder_sample, reverse_...
StarcoderdataPython
1722969
<filename>references/services/refextract/tests.py """Tests for :mod:`references.process.extract.refextract` module.""" import json import jsonschema import datetime import os import subprocess import unittest from unittest import mock from references.domain import Reference from references.services import refextract ...
StarcoderdataPython
169103
from functools import partial from typing import Any, List, Optional import torch from torch import nn from torch.nn import functional as F BATCH_NORM_MOMENTUM = 0.005 ENABLE_BIAS = True activation_fn = nn.ELU() class ASPPConv(nn.Sequential): def __init__(self, in_channels: int, out_channels: int, dilation: int)...
StarcoderdataPython
1625673
<gh_stars>0 import subprocess import shlex from . import status from .commands_extra import * from .mpi import _get_mpi_command def mAdd(images_table, template_header, out_image, img_dir=None, no_area=False, type=None, exact=False, debug_level=None, status_file=None, mpi=False, n_proc=8): ''' ...
StarcoderdataPython
4802790
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello, world. You're at the polls index.") def hello(request, name): return HttpResponse(("Hello", name)) def times2(request, number): return HttpResponse(("The prod...
StarcoderdataPython
1721732
<filename>api/old/websock.py<gh_stars>0 import json import datetime import websocket import MySQLdb db=MySQLdb.connect(passwd="<PASSWORD>", db="ar", user="ar") ws = websocket.WebSocket() ws.connect("ws://iot.wut.ee/p2p/chip/browser") while True: msg = json.loads(ws.recv()) if msg.get('mac') != None: c =...
StarcoderdataPython
3215783
""" Wishlist Steps Steps file for Wishlist.feature For information on Waiting until elements are present in the HTML see: https://selenium-python.readthedocs.io/waits.html """ from os import getenv import logging import json import requests from behave import * from compare import expect, ensure from selenium.web...
StarcoderdataPython
177394
""" https://adventofcode.com/2018/day/2 """ from collections import Counter from itertools import product from pathlib import Path def solve_a(codes): pairs = triplets = 0 for code in codes: occurrences = Counter(code).values() pairs += any(count == 2 for count in occurrences) triplet...
StarcoderdataPython
1649306
from setuptools import setup, Extension # Bypass import numpy before running install_requires # https://stackoverflow.com/questions/54117786/add-numpy-get-include-argument-to-setuptools-without-preinstalled-numpy class get_numpy_include: def __str__(self): import numpy return numpy.get_include() ...
StarcoderdataPython
191963
<gh_stars>1-10 from typing import Dict, List class TextParagraph: def __init__(self, number, text, parent = None): self.parent: LawParagraph = parent self.number: str = number self.text: str = text @property def id(self) -> str: safe_number = self.number if self.number is...
StarcoderdataPython
1679670
import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms import numpy as np def fakeBootStrapper(n): ''' This is just a placeholder for the user's method of bootstrapping the median and its confidence intervals. Returns an arbitrary median and confidence intervals packed into a ...
StarcoderdataPython
144986
from ..serializer import Serializable from .performance import PerformanceInfo from .message import Message class Response(Serializable): """ Response from chatbot Attributes ---------- messages : list of minette.Message Response messages headers : dict Response header per...
StarcoderdataPython
56700
<filename>tests/commands/open.py<gh_stars>0 #!/usr/bin/env python3 # # Short description of the program/script's operation/function. # import sys from command import Command class CmdOpen(Command): def __init__(self): Command.__init__(self, "open", short_alias="o", min_args...
StarcoderdataPython
4825622
<filename>djangotoolbox/fields.py<gh_stars>0 # All fields except for BlobField written by <NAME> <<EMAIL>> from django.db import models from django.core.exceptions import ValidationError from django.utils.importlib import import_module __all__ = ('RawField', 'ListField', 'DictField', 'SetField', 'BlobField...
StarcoderdataPython
3288057
<gh_stars>1-10 import os.path import pyinotify import sqlalchemy import logging import threading from logban.core import DBBase, DBSession, main_loop, main_loop_future, hash_string from abc import ABC, abstractmethod _logger = logging.getLogger(__name__) all_file_monitors = {} class AbstractFileMonitor(ABC): ...
StarcoderdataPython