id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1720697 | import asyncio, json
from aiohttp import web
class BoatAPI:
def __init__(self, boat, addr, port):
self.boat = boat
self.addr = addr
self.port = port
async def request_handler(self, request):
if request.rel_url.path == '/':
# For all methods to root
retur... | StarcoderdataPython |
3266977 | <reponame>renmengye/imageqa-public<gh_stars>10-100
import yaml
import router
from model import *
def load(modelSpecFilename):
"""
Need the following items in the model spec file:
costFn
decisionFn
stages
specs
:param modelSpecFilename:
:return:
"""
with open(modelS... | StarcoderdataPython |
173318 | """
Code provided by Hyperledger Indy (v1.15.0).
Use of this source code is governed by a Apache-2.0 license that can be found in the LICENSE file.
https://github.com/hyperledger/indy-sdk
"""
from indy.error import IndyError
from indy import anoncreds
from indy import blob_storage
from indy import crypto
from indy i... | StarcoderdataPython |
3280642 | <gh_stars>1000+
"""
Schur symmetric functions
"""
# ****************************************************************************
# Copyright (C) 2007 <NAME> <<EMAIL>>
# 2012 <NAME> <<EMAIL>>
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code is distribute... | StarcoderdataPython |
1642412 | # oxShibboleth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
# Copyright (c) 2020, Gluu
#
# Author: <NAME>
#
from org.gluu.model.custom.script.type.idp import IdpType
from org.gluu.util import StringHelper
from org.gluu.idp.externalauth import AuthenticatedNameTransla... | StarcoderdataPython |
148582 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2017 Alibaba Group Holding Ltd.
#
# 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/LICENS... | StarcoderdataPython |
1766117 | <filename>models_nonconvex_simple/ghg_1veh.py
# MINLP written by GAMS Convert at 08/13/20 17:37:45
#
# Equation counts
# Total E G L N X C B
# 38 18 9 11 0 0 0 0
#
# Variable counts
# x ... | StarcoderdataPython |
3341050 | <filename>rfcs/rfc-reports-generation/reports-api/main/decorators/timetracker.py<gh_stars>0
import time
def timetracker(method):
"""
Decorator for tracking the time around def invocation
:param method:
:return:
"""
def time_tracker(*args, **kw):
time_start = int(round(time.time() * 100... | StarcoderdataPython |
191393 | import numpy as np
def target_transform(y: np.array, increment: float=0.01) -> np.array:
"""
Transform non-negative array to R using np.log
:param y: np.array
:param increment: float
:return:
"""
return np.log(y + increment)
def target_inverse_transform(y_trn: np.array, increment: float=... | StarcoderdataPython |
3285321 | # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# License: The MIT License (MIT)
#
# Copyright (c) 2020 <NAME>. -> www.whexy.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), t... | StarcoderdataPython |
1721400 | <reponame>gold-standard-phantoms/asldro
""" BaseFilter classes and exception handling """
import copy
import logging
from typing import List, Mapping, Any
from abc import ABC, abstractmethod
from asldro.utils.general import map_dict
logger = logging.getLogger(__name__)
class BaseFilterException(Exception):
"""... | StarcoderdataPython |
188840 | <gh_stars>100-1000
from os import getenv, environ
from .converters import text_to_bool
from .entry import Entry, NotSet
class EnvEntry(Entry):
@classmethod
def default_conversions(cls):
conversions = super(EnvEntry, cls).default_conversions().copy()
conversions[bool] = text_to_bool
re... | StarcoderdataPython |
47863 | from django.urls import path
from . import views
urlpatterns = [
path('<int:sproperty_id>/',views.contact,name="contact"),
path('',views.contact_submit,name="contact-submit"),
] | StarcoderdataPython |
8775 | # -*- coding=utf-8 -*-
from zwechathihu.mypdf import GenPdf
from db.mysqlite import simpleToolSql
data=[{"url": "http://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484852&idx=1&sn=85b50b8b0470bb4897e517955f4e5002&chksm=9bd7fbbcaca072aa75e2a241064a403fde1e579d57ab846cd8537a54253ceb2c8b93cc3bf38e&scene=21#wechat_... | StarcoderdataPython |
153776 | import os
import re
from weakref import WeakKeyDictionary
from io import StringIO
import trafaret as _trafaret
from yaml import load, dump, ScalarNode
from yaml.scanner import ScannerError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader
from .error import Config... | StarcoderdataPython |
4809923 | <reponame>PranavSudersan/Buggee<filename>app/_mainImportfile.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 12:10:12 2020
@author: adwait
"""
import pims
import numpy as np
import cv2
import matplotlib.pyplot as plt
# import openpyxl
import pandas as pd
import os.path
import logging
from PyQt5.QtCo... | StarcoderdataPython |
11731 | <gh_stars>1-10
import os
import json
import logging
import yaml
from flask import Blueprint, jsonify, send_file, request, redirect
from service.errors import ApiError
from utils.repository import generate_repository_path, \
list_objects_in_repository
from utils.list_dir import list_dir
repository_controller = Bl... | StarcoderdataPython |
156742 | <gh_stars>1-10
from user import *
| StarcoderdataPython |
3354870 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | StarcoderdataPython |
3231997 |
from myhdl import Signal, intbv, always_comb, always_seq
from . import Streamers
class AXI4StreamChannel(Streamers):
def __init__(self, glbl, data_width=32):
""" Interface for AXI4 streaming protocol """
super(AXI4StreamChannel, self).__init__(glbl, data_width)
vmax = 2**data_width
... | StarcoderdataPython |
3364341 | <reponame>ria-ee/XTM
# coding=utf-8
import re
import time
import urllib
from selenium.webdriver.common.by import By
from helpers import xroad, auditchecker, ssh_server_actions
from view_models import clients_table_vm, popups, messages, ss_system_parameters, log_constants
from view_models.clients_table_vm import SERV... | StarcoderdataPython |
24021 | <filename>pub/models.py<gh_stars>1-10
# coding=utf-8
from pub.tables.resources import *
from pub.tables.map.domain import *
from pub.tables.cache.token import *
from pub.tables.map.files import *
from pub.tables.user import *
from pub.tables.cache.suspend import *
from pub.tables.notice import *
from pub.tables.templat... | StarcoderdataPython |
3306743 | # Russian Roulette game made in python. The rules are simple: Each player has to press enter to pull the trigger
# and the player that hits the chambers that contains the bullet, losses!
# After the game is over the user has the option to restart the game.
import random
import pyjokes
def russian_roulette():
fa... | StarcoderdataPython |
4819046 | <filename>SolaxGateway.py
import sys
sys.path.insert(0, './solax')
import solax
import asyncio
import json
import os
from solax import inverter
from http.server import HTTPServer, BaseHTTPRequestHandler
async def LoadSolaxData():
# r = await solax.real_time_api(os.environ['SOLAX_IP'],80,'admin')
... | StarcoderdataPython |
134743 | <filename>tests/test_download.py
"""
Tests for the download module of GLDAS.
"""
import os
from datetime import datetime
from smap_io.download import get_last_formatted_dir_in_dir
from smap_io.download import get_first_formatted_dir_in_dir
from smap_io.download import get_last_folder
from smap_io.download import get_f... | StarcoderdataPython |
138830 | <reponame>fiskenslakt/aoc-2020
from collections import deque
from operator import add, mul
from aocd import data as homework
def get_postfix(expression: str, advanced: bool = False) -> deque:
ops = []
queue = deque()
for token in expression.replace(' ', ''):
if token.isdigit():
queue... | StarcoderdataPython |
1679048 | <filename>RestAdmin/apps/system/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
# Create your models here.
class Menu(models.Model):
"""
菜单
"""
MENU_TYPE = (
(1, "一级类目"),
(2, "二级类目"),
(3, "三级类目"),
)
menu_type = models.Integer... | StarcoderdataPython |
3233800 | from toolz import curry
@curry
def subtract(x, y):
"""Subtracts its second argument from its first argument"""
return x - y
| StarcoderdataPython |
1759015 | <reponame>WojciechKusa/datasets
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets 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
#
# h... | StarcoderdataPython |
3389683 | <reponame>tys-hiroshi/bnodeapi
import bitsv
from whatsonchain import api
from utils.mnemonic.bip39_mnemonic_util import Bip39MnemonicUtil
from openapi_server.models.response_mnemonic_model import ResponseMnemonicModel
class BsvMnemonicUtil():
def __init__(self):
pass
@staticmethod
def get_mn... | StarcoderdataPython |
1604247 |
import os
import weakref
import queue
import copyreg
import types
import pickle
def is_pickle_format(filename):
# http://stackoverflow.com/questions/13939913/how-to-test-if-a-file-has-been-created-by-pickle
f = open(filename, "rb")
f.seek(-1, os.SEEK_END)
last_byte = f.read(1)
if last_byte == pic... | StarcoderdataPython |
1686072 | <reponame>fabiocaccamo/python-benedict
# -*- coding: utf-8 -*-
from datetime import datetime
from decimal import Decimal
from six import integer_types, string_types
import re
regex = re.compile('').__class__
uuid_re = re.compile(
'^([0-9a-f]{32}){1}$|^([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}){1}$',
flags=r... | StarcoderdataPython |
3285289 | # Licensed to the Apache Software Foundation (ASF) 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, Version 2.0
# (the "License"); you may not use ... | StarcoderdataPython |
3323649 | from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.flood import stations_level_over_threshold
def run():
stations = build_station_list()
update_water_levels(stations)
stationLevels = []
for station in stations_level_over_threshold(stations, 0.8):
stati... | StarcoderdataPython |
3334046 | """
Name : LockManager
Author : blu
Time : 2022/3/7 08:19
Desc : 日志管理器封装
"""
import logging
import os
import time
from logging.handlers import WatchedFileHandler
from aiostar.utils import singleton
class BufferingFileHandler(WatchedFileHandler):
def __init__(self, flush_interval=0.5, *args, **kwargs):
se... | StarcoderdataPython |
46032 | <filename>python/multi_view_learning/nn_leaveOneOut.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Tensor flow NN model for leave-one-out evaluation.
Created on Fri Apr 7 14:25:01 2017
@author: hxw186
"""
import tensorflow as tf
import numpy as np
import sys
sys.path.append("../")
from feature_evaluation... | StarcoderdataPython |
1735249 | <filename>scripts/hello_world_sarthak268.py
// LANGUAGE: Python
// AUTHOR: <NAME>
// GITHUB: https://github.com/sarthak268
print "Hello World"
| StarcoderdataPython |
9848 | <gh_stars>100-1000
import os
import sys
from pyspark.sql.types import *
PATH = "/home/ubuntu/work/ml-resources/spark-ml/data"
SPARK_HOME = "/home/ubuntu/work/spark-2.0.0-bin-hadoop2.7/"
os.environ['SPARK_HOME'] = SPARK_HOME
sys.path.append(SPARK_HOME + "/python")
from pyspark import SparkContext
from pyspark import S... | StarcoderdataPython |
3345303 | from coopihczoo.pointing.envs import SimplePointingTask
from coopihc.bundle.Bundle import Bundle
task = SimplePointingTask(gridsize=31, number_of_targets=8, mode="position")
bundle = Bundle(task=task)
game_state = bundle.reset()
print(game_state)
# >>> print(game_state)
# ---------------- ----------- --------------... | StarcoderdataPython |
79519 | import os
import logging
from .paths import get_path
_FORMAT = '%(asctime)s:%(levelname)s:%(lineno)s:%(module)s.%(funcName)s:%(message)s'
_formatter = logging.Formatter(_FORMAT, '%H:%M:%S')
_handler = logging.StreamHandler()
_handler.setFormatter(_formatter)
logging.basicConfig(filename=os.path.join(get_path(), 'sp... | StarcoderdataPython |
194109 | <reponame>DanSeraf/spyd
from twisted.application import service
from twisted.internet import reactor
class Service(service.Service):
def __init__(self, interface, port, protocol_factory):
self._interface = interface
self._port = port
self._protocol_factory = protocol_factory
... | StarcoderdataPython |
1752071 | <gh_stars>1000+
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator... | StarcoderdataPython |
3223655 | # Copyright 2018 The Bazel Authors. 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 required by applicable la... | StarcoderdataPython |
186534 | <reponame>waldur/waldur-mastermind
from waldur_core.logging.loggers import EventLogger, event_logger
class ProjectUpdateRequestLogger(EventLogger):
project = 'structure.Project'
offering = 'marketplace.Offering'
class Meta:
event_types = (
'project_update_request_created',
... | StarcoderdataPython |
3267579 | #coding:utf-8
#
# A class of IIR Band Pass Filter, process twice !
# (Target response is 2nd harmonic level less than -70dB)
#
import sys
import numpy as np
from matplotlib import pyplot as plt
from scipy import signal
from iir1 import *
from ema1 import *
# Check version
# Python 3.6.4 on win32 (W... | StarcoderdataPython |
1721011 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Script to read a list of course pages (based on course ID) and then
create the /sandbox subpage for any enrolled students if their sandbox
does not already exist.
"""
#
# (C) Pywikibot team, 2006-2014
# (C) <NAME>, 2014-2015
#
# Distributed under the terms of the MIT licen... | StarcoderdataPython |
4807376 | #!/usr/bin/python
# -*- coding: UTF-8 -*
"""
@author:li-boss
@file_name: common_response_process.py
@create date: 2019-10-27 14:38
@blog https://leezhonglin.github.io
@csdn https://blog.csdn.net/qq_33196814
@file_description:
"""
from flask import jsonify, Response
import json
import datetime
from utils.xml_json_pro... | StarcoderdataPython |
3390988 | """
active_learning
Active learning
"""
# Add imports here
from .BO import *
# Handle versioneer
from ._version import get_versions
versions = get_versions()
__version__ = versions["version"]
__git_revision__ = versions["full-revisionid"]
del get_versions, versions
| StarcoderdataPython |
145746 | <filename>wifiphisher-1.4/wifiphisher/common/firewall.py<gh_stars>0
#pylint: skip-file
import subprocess
from wifiphisher.common.constants import *
class Fw():
def __init__(self):
pass
def nat(self, internal_interface, external_interface):
subprocess.call(
('iptables -t nat -A POS... | StarcoderdataPython |
4832409 | import tensorflow as tf
import numpy as np
from functools import reduce
VGG_MEAN = [103.939, 116.779, 123.68]
class Vgg19:
"""
A trainable version VGG19.
"""
def __init__(self, vgg19_npy_path=None, trainable=True, dropout=0.5):
if vgg19_npy_path is not None:
self.data_dict = np.... | StarcoderdataPython |
1667690 | <gh_stars>1-10
from django.urls.conf import path, include
from qanda import views
from .views import QuestionAPI, latest
from rest_framework import routers
router = routers.DefaultRouter()
router.register("questions", QuestionAPI)
app_name = 'qanda'
urlpatterns = [
path('ask', views.AskQuestionView.as_vi... | StarcoderdataPython |
3316172 | <gh_stars>0
"""Visualize the resutls of the training using Seaborn."""
import json
import os
import re
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
results_folder_path = "./Phenophase_Classification/results"
results = sorted(os.listdir(results_folder_path))
jsons = []
for file_name in r... | StarcoderdataPython |
3387715 | <gh_stars>1-10
from Orange.data.table import Table
from Orange.data.pandas_compat import table_from_frame
from Orange.widgets.data.owtable import OWDataTable
from .view import View
@View.register_view
class TableView(View):
title = "Table"
supported_types = ("pandas_data_frame",)
def create_widget(self... | StarcoderdataPython |
164409 | # Το προγραμμα προσομειωνει την ριψη ενος κερματος, 10 φορες και θα εμφανιζει
# αν είναι κορώνα ή γράμμα.
import random
def ektelesi():
x = 0
while x != 10:
tyxaios_arithmos()
x = x + 1
print()
print()
def tyxaios_arithmos():
arithmos = random.randint(1, 2)
... | StarcoderdataPython |
3256598 | #!/usr/bin/env python
"""Performance tests for the eipaddress module."""
import sys
import time
import ipaddress as ip
import eipaddress as eip
from sizes import sizeof
# =============================================================================
class TextFx:
'''Terminal strings for text effects.'''
PL... | StarcoderdataPython |
139388 | <reponame>WildernessBear/447-COVID-lunch-proj<filename>Lunchtime/Lproj/Lapp/migrations/0002_db_setup.py
# Generated by Django 3.1.2 on 2020-12-08 08:29
from django.db import migrations
import random
# description should NOT be seen on website, it just describes if an item is a main dish, side, or drink
class Item:
... | StarcoderdataPython |
1689811 | # Copyright (c) Facebook, Inc. and its affiliates.
# Modified by BaseDetection, Inc. and its affiliates.
import logging
import time
import weakref
from typing import Dict
import numpy as np
import torch
from cvpods.utils import comm
from cvpods.utils.dump.events import EventStorage, get_event_storage
from cvpods.ut... | StarcoderdataPython |
169516 | import torch
from torchvision import datasets, transforms
from torch.autograd import Function
def load_data_fashion_mnist(batch_size, resize=None):
"""download Fashion-MNIST dataset, then load into memory"""
trans = [transforms.ToTensor()]
if resize:
trans.insert(0, transforms.Resize(resize))
t... | StarcoderdataPython |
3247564 | # coding: utf-8
from __future__ import unicode_literals
from django.dispatch import Signal
def handle_subscribe_created(sender, instance, request, **kwargs):
instance.send_notification()
subscribe_created = Signal(providing_args=['instance', 'request'])
subscribe_created.connect(handle_subscribe_created)
| StarcoderdataPython |
1764391 | import argparse
from utils import ModelConfiguration, DataLoaderConfiguration, EXTRA_TRANSFORM
import os
from roar_experiment import experiment
from sensitive_transparency import sensitive_transparency
import torch
def main(config):
torch.manual_seed(config.seed)
PATH = os.path.dirname(os.path.abspath(__file__... | StarcoderdataPython |
1657000 | <filename>robot/letter_reading/letter_mapping.py
import rospy
import RPi.GPIO as GPIO
from capture_image_from_embed_camera import capture_image_from_embed_camera
from map_letters import map_letters
from process_image_to_grayscale import process_image_to_grayscale
class Mapping:
def __init__(self):
... | StarcoderdataPython |
3261268 | __copyright__ = """
Copyright 2020 <NAME>
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 a... | StarcoderdataPython |
3223657 | #!/usr/bin/env python
# coding: utf-8
# Copyright 2013 <NAME>
#
# 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 applica... | StarcoderdataPython |
1771402 | <filename>origamid/utils/validation.py
try:
from pip.req import parse_requirements
except ImportError:
# For pip version >= 10
from pip._internal.req import parse_requirements
import logging
import os
import zipfile
from .file import get_model_bundles_base_dir, extract_zip_to_dir, \
clean_directory
fr... | StarcoderdataPython |
1613428 | <reponame>jkpubsrc/python-module-jk-json
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
import os
import sys
import codecs
import timeit
import json
import cProfile
from jk_logging import *
import jk_json
bDebugging = False
#bDebugging = True
with codecs.open("test-strict.json", "r", "utf-8") as f:... | StarcoderdataPython |
3363807 | <gh_stars>10-100
# Standard Library
from uuid import uuid4
# 3rd Party
from preggy import expect
from tests.fixtures.models import JobExecutionFixture, JobFixture
# Fastlane
from fastlane.models import Job, JobExecution, Task
from fastlane.utils import dumps, loads
# Must inject client to connect to redis and DB
de... | StarcoderdataPython |
1677579 | """
Copyright 2013 <NAME>
This file is part of CVXPY.
CVXPY is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CVXPY is distributed in the ho... | StarcoderdataPython |
3258249 | <gh_stars>0
def update_dict(items, d, output_format=1):
for k, v in d.items():
if k in items:
# if output_format == 1:
k2 = k + "_1"
count = 0
while k2 in items:
count += 1
k2 += "_1"
items.update({k2: v})
# else:
# k2
else:
items.update({k: v})
items = {"A":1,"B":2, "C":... | StarcoderdataPython |
4842676 | import logging
import os
import grpc
import pandas as pd
from typing import List
from generativesampler_pb2_grpc import GenerativeSamplerStub
from generativesampler_pb2 import GenerativeSpec, EmbeddingList, GenerativeModel, google_dot_protobuf_dot_empty__pb2
from cuchemcommon.data import GenerativeWfDao
from cuchemc... | StarcoderdataPython |
3237886 | from datetime import datetime
import numpy as np
from arcgis.features import GeoAccessor
from arcgis.gis import GIS
from go_utils.constants import (
abbreviation_dict,
end_date,
landcover_protocol,
mosquito_protocol,
region_dict,
start_date,
)
from go_utils.download import convert_dates_to_dat... | StarcoderdataPython |
4831141 | <gh_stars>0
import sqlalchemy
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
from math import *
from models import POIS, Category, POIS_distances, User, API_Key, API_Log, Concelho, Images, Route, SequencePois
import json
from app_core import db, app, celery
from my_function_osrm import *
import fiona... | StarcoderdataPython |
166315 | # coding: utf-8
# ----------------------------------------------------------------------------
# <copyright company="Aspose" file="MapiCalendarRecurrencePatternDto.py">
# Copyright (c) 2018-2020 Aspose Pty Ltd. All rights reserved.
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to... | StarcoderdataPython |
188098 | <reponame>mackaiver/slowREST
__author__ = 'kai'
import pygal
from pygal.style import LightSolarizedStyle
# import numpy as np
# from fact import time
def create_box_whisker(data_frame):
try:
#prepare and clean data. drop missings as well
data_frame.drop(["_id"], axis=1, inplace='true')
dat... | StarcoderdataPython |
54599 | from django.db import models
from django.db.models import Q
class PaperQuerySet(models.QuerySet):
def published(self):
"""Get all published items."""
return self.filter(Q(publish=True))
| StarcoderdataPython |
3200356 | hash_table = [0] * 8
def get_key(data):
return hash(data)
def get_addr(key):
return key % 8
def get_new_addr(addr):
return (addr+1) % 8
def save_data(data, value):
key = get_key(data)
addr = get_addr(key)
while hash_table[addr]:
if hash_table[addr][0] == key:
hash_table[a... | StarcoderdataPython |
158728 | <reponame>manuparra/oc2dm<gh_stars>1-10
import rpy2.robjects as ro
def cor (parameterCore):
cor = ro.r("""
dataset = read.csv(file="{0}", header = TRUE, sep=',')
resultfit = cor({1})
saveRDS(resultfit, "{2}")
""".format(parameterCore.dataset['ruta'], parameterCore.parameters, parameterCore.outputPMML)... | StarcoderdataPython |
3232498 | # Copyright 2019 Extreme Networks, 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 i... | StarcoderdataPython |
174218 | <reponame>showwin/kintai-paccho
import datetime
import json
from enum import IntEnum
from .repo import Employee
from .requester import KOTRequester
def register_user(user, kot_user_code) -> dict:
requester = KOTRequester()
resp_dict = requester.get('/employees/{}'.format(kot_user_code))
employee_key = re... | StarcoderdataPython |
83646 | <reponame>scavnicka/kuryr-kubernetes
# 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 requi... | StarcoderdataPython |
84619 | <filename>reeds/function_libs/visualization/re_plots.py
from typing import List
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from reeds.function_libs.visualization import plots_style as ps
from reeds.function_libs.visualization.utils import generate_trace_from_transition_dict, y_axis_fo... | StarcoderdataPython |
154802 | import numpy as np
raw = open("inputs/7.txt","r").readline()
input_array= [int(i) for i in np.asarray(raw.split(","))]
test_array = [16,1,2,0,4,2,7,1,2,14]
def alignCrabsPartOne(input):
result_array=[]
for i in range(min(input), max(input)+1):
result_array.append(sum([abs((horizontalPos-i)) for horizontalPos in i... | StarcoderdataPython |
3386828 | #!/usr/bin/env python
# encoding: utf-8
"""
gscholar.py
Created by <NAME> on November 16, 2013
"""
import requests
import alfred
from bs4 import BeautifulSoup # , SoupStrainer
import hashlib
import random
from common import waitForPeriodInQuery
# get query from user (won't parse until ends with ".")
title='Googl... | StarcoderdataPython |
1711093 | from pathlib import Path
from setuptools import setup
__here__ = Path(__file__).absolute().parent
README = (__here__ / "README.rst").read_text().strip()
VERSION = "1.0.0"
setup(
name="lazy-string",
version=VERSION,
description="Python library for defining strings with delayed evaluation",
long_descriptio... | StarcoderdataPython |
4841122 | import uuid
from notsouid import factories
class TestBaseFactory:
def test_call(self):
factory = factories.BaseFactory()
result = factory()
assert result == uuid.UUID('00000000-0000-0000-0000-000000000000')
def test_from_string(self):
factory = factories.BaseFactory.from_stri... | StarcoderdataPython |
3207596 | <gh_stars>10-100
'''
Given a list iterate it and display numbers which are divisible by 5 and if you find number greater than 150 stop the loop iterationGiven a list iterate it and display numbers which are divisible by 5 and
if you find number greater than 150 stop the loop iteration
'''
12, 15, 32, 42, 55, 75, 12... | StarcoderdataPython |
24122 | from matplotlib import pyplot as plt
import gpflow
import tensorflow as tf
import os
import numpy as np
import cProfile
def outputGraph(model, dirName, fileName):
model.compile()
if not(os.path.isdir(dirName)):
os.mkdir(dirName)
fullFileName = os.path.join(dirName, fileName)
if os.path.isfile(f... | StarcoderdataPython |
4802333 | import os
from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
from rpython.rlib.rposix import is_valid_fd
from rpython.rlib.rarithmetic import widen, ovfcheck_float_to_longlong
from rpython.rlib.objectmodel import keepalive_until_here
from rpython.rtyper.annlowlevel import llhelper
from pypy.interpreter.err... | StarcoderdataPython |
3295589 | '''
File: isg.py
Author: <NAME> (<EMAIL>)
Date: 25 Jan 2016
* Copyright (c) 2014/2015/2016, <NAME> and Data61/NICTA
* All rights reserved.
*
* Developed by: <NAME>
* Data61 / NICTA
* http://www.nickmattei.net
* http://www.preflib.org
*
* Redistributio... | StarcoderdataPython |
1668560 | #!/usr/bin/env python
from cherryadmin import *
def login_helper(login, password):
if login == password == "<PASSWORD>":
return {
"login" : "demo",
"role" : "admin",
"first_name" : "Nikola",
"last_name" : "Sanders",
}
return ... | StarcoderdataPython |
1649497 | from django.test import TestCase
#from django.contrib.auth import get_peak_model
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
"""Test creating a new user with an email is successful"""
email = '<EMAIL>'
passwor... | StarcoderdataPython |
1706336 | #!/usr/bin/python
import date
import datetime
import time
# ============================================================================ #
# Time-related helper functions
# ============================================================================ #
def sleep(duration):
"""
Pause execution for specified dura... | StarcoderdataPython |
3241056 | import os
from copy import deepcopy
from pathlib import Path
import numpy as np
import pytest
from ase.build import bulk, fcc100, molecule
from ase.io import read
from quacc.util.slabs import (
flip_atoms,
make_adsorbate_structures,
make_max_slabs_from_bulk,
make_slabs_from_bulk,
)
FILE_DIR = Path(__... | StarcoderdataPython |
3374144 | #!/usr/bin/env python3
"""
http://adventofcode.com/day/14
Part 1
------
This year is the Reindeer Olympics! Reindeer can fly at high
speeds, but must rest occasionally to recover their energy.
Santa would like to know which of his reindeer is fastest,
and so he has them race.
Reindeer can only either be flying (alway... | StarcoderdataPython |
1743558 | <reponame>RayYu03/pysoccer
from soccer.data import LEAGUE_PROPERTIES, LEAGUE_NAMES
from . import BaseWriter
import click
import json
import io
__all__ = ['Stdout', 'Fstdout', 'Fjson', 'Json']
class Stdout(BaseWriter):
def __init__(self, output_file):
enums = dict(
CL_POSITION="green",
... | StarcoderdataPython |
1791765 | <reponame>fabm3n/pretix
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 <NAME> and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License ... | StarcoderdataPython |
114897 | <gh_stars>0
from abc import ABCMeta, abstractmethod
from typing import Tuple, Callable, Any, Optional, List
import matplotlib.pyplot as plt
import numpy as np
from receptivefields.common import estimate_rf_from_gradients
from receptivefields.logging import get_logger
from receptivefields.plotting import plot_receptive... | StarcoderdataPython |
3375858 | import os
from collections import namedtuple
from pathlib import Path
import cv2
import numpy
import numpy as np
import zxing
from loguru import logger
from docbarcodes.zxingjpype.zxingreader import decodeImages
RegionBarcode = namedtuple('RegionBarcode', 'page num barcode file region')
DocBarcode = namedtuple('DocB... | StarcoderdataPython |
62648 | <reponame>Biguelini/Curso-Python-3
# 1
numero = input('Digite um número inteiro ')
if numero.isdigit():
if int(numero)%2==0:
print('É par')
else:
print('É ímpar')
else:
print('Digite um número inteiro')
# 2
from datetime import datetime
data_e_hora_atuais = datetime.now()
data_e_hora_atuai... | StarcoderdataPython |
3336537 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 15:58:07 2019
@author: ltetrel
"""
import unittest
import shutil
import os
from repo2data.repo2data import Repo2Data
class Test(unittest.TestCase):
def test_multiple(self):
if os.path.exists("./tests/out/repo2data_multiple1"):
... | StarcoderdataPython |
3348848 | <reponame>josulaguna/Python3<gh_stars>0
#<NAME>
#21/02/2018
valor1 = input ("Escribe el primer valor: ")
valor2 = input ("Escribe el segundo valor: ")
if (valor1 > valor2):
print "El primer valor es mas grande que el segundo"
elif (valor2 > valor1):
print "El segundo valor es mas grande que el primero"
else:
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.