id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
4815634 | from cdxj_indexer.main import CDXJIndexer, iter_file_or_dir
from cdxj_indexer.postquery import append_method_query_from_req_resp
from cdxj_indexer.bufferiter import buffering_record_iter
| StarcoderdataPython |
1653391 | from events import EventManager
from exchange.public import ExchangePublic
class FTX(ExchangePublic):
def __init__(self, conf=None):
exchange_id = 'ftx'
super().__init__(exchange_id, conf)
self.em.modify_mailbox_size(exchange_id, 7)
if __name__ == "__main__":
b = FTX()
b.listen()... | StarcoderdataPython |
199852 | import asyncio
import itertools
from collections import defaultdict
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import datetime, timedelta
from pathlib import Path
from typing import List, Union, Dict, Any, Sequence
import os
import logging
from aiomultiprocess import Pool
from... | StarcoderdataPython |
3231531 | <reponame>AWSCookbook/Containers<filename>605-Updating-Containers-With-BlueGreen/cdk-AWS-Cookbook-605/app.py
#!/usr/bin/env python3
import aws_cdk as cdk
from cdk_aws_cookbook_605.cdk_aws_cookbook_605_stack import CdkAwsCookbook605Stack
app = cdk.App()
CdkAwsCookbook605Stack(app, "cdk-aws-cookbook-605")
app.synth(... | StarcoderdataPython |
3240007 | load("@bazel_skylib//lib:versions.bzl", "versions")
def _store_bazel_version(repository_ctx):
bazel_version = versions.get()
if len(bazel_version) == 0:
print("You're using development build of Bazel, make sure it's at least version 0.17.1")
elif versions.is_at_most("0.17.0", bazel_version):
... | StarcoderdataPython |
70415 | <gh_stars>0
from src.localLib.paymentGateway import FwGateway as paymentGateway
from src.models.plans import Plans
def runPlansBilling():
"""
Process all payments requests for all clients of all plans
"""
pg = paymentGateway() # Instanciating the paymentGateway
plans = Plans()
activePlans = ... | StarcoderdataPython |
1737921 | # -*- encoding:utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.
import logging
import time
import numpy as np
import tensorflow as tf
from easy_rec.python.input.input import Input
from easy_rec.python.utils import odps_util
from easy_rec.python.utils.tf_utils import get_tf_type
try:
import common_io
exc... | StarcoderdataPython |
3292672 | # -*- coding: utf-8 -*-
"""
GUI frame template:
- auto-accelerated control shortcuts, "&OK" will turn Alt-O into shortcut
- Python console window, initially hidden,
with auto-saved command history kept in conf.ConsoleHistoryCommands
- wx widget inspector window, initially hidden
- option for log panel, handles... | StarcoderdataPython |
4800688 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
:author: 秋荏苒
:copyright: © 2019 by 秋荏苒 <<EMAIL>>.
:license: MIT, see LICENSE for more details.
"""
import os
import sys
from urllib.parse import urlparse, urljoin
from flask import request, redirect, url_for, current_app
from app.configs import basedir
def is_safe... | StarcoderdataPython |
94640 | <gh_stars>10-100
# function for merge sort
def merge_sort(arr):
if len(arr) > 1:
# mid element of array
mid = len(arr) // 2
# Dividing the array and calling merge sort on array
left = arr[:mid]
# into 2 halves
right = arr[mid:]
# merge sort for array first... | StarcoderdataPython |
1625740 | from cosymlib.file_io import get_geometry_from_file_cor
from cosymlib.file_io import errors
import os
import tempfile
import warnings
def read_old_input(file_name):
"""
Reads the old Shape's program input
:param file_name: file name
:return: list of Geometry objects and options
"""
options =... | StarcoderdataPython |
141769 | # -*- coding: utf-8 -*-
from django.conf.urls import url
from .views import SlackAuthView, DefaultAddSuccessView, DefaultSigninSuccessView
urlpatterns = [
url('add/', SlackAuthView.as_view(auth_type="add"), name='slack_add'),
url('signin/', SlackAuthView.as_view(auth_type="signin"), name='slack_signin'),
... | StarcoderdataPython |
10400 | import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import flopy
def run():
workspace = os.path.join("lake")
# make sure workspace directory exists
if not os.path.exists(workspace):
os.makedirs(workspace)
fext = "png"
narg = len(sys.argv)
iarg = 0
if narg > 1:... | StarcoderdataPython |
31159 | <filename>pythonlearn/input.py
# Write a program that asks the user what kind of rental car they
# would like. Print a message about that car, such as “Let me see if I can find you
# a Subaru.”
car = input("What type of rental rental car would you like? ")
print(f"Checking database to find a {car}")
# Write a program... | StarcoderdataPython |
1618371 | import os
import datetime
import requests
def fetch_remote_file(url, cache = '', expire = 0):
if cache and expire:
expire = (datetime.datetime.now() - datetime.timedelta(minutes=expire)).strftime('%s')
if not os.path.isfile(cache) or int(os.path.getmtime(cache)) < int(expire):
try:... | StarcoderdataPython |
3336781 | import math
import cv2
class DistanceToCamera(object):
def __init__(self):
# camera params
self.alpha = 8.0 * math.pi / 180 # degree measured manually
self.v0 = 119.865631204 # from camera matrix
self.ay = 332.262498472 # from camera matrix
def calc... | StarcoderdataPython |
3267522 | <reponame>CodeVsZombie/code-vs-zombie
from codeingame import Point, Line, PointId, Segment, Ash, Human, Zombie, Field
import math
import pytest
def test_calculate_distances():
a = Point(0, 0)
b = Point(1, 0)
c = Point(0, 1)
d = Point(1, 1)
assert a.distance(b) == 1
assert a.distance(c) == 1
assert a.distance(... | StarcoderdataPython |
1708350 | <reponame>gamozolabs/flounder
import requests, json, time, sys
# This script takes in a search query and a bing subscription key and
# generates a file containing all the links from the query. This file with
# links can then be used by download.py to download the files mentioned by
# the links
market_codes = [... | StarcoderdataPython |
4813964 | __all__ = ['coffee']
# Needed for South
from .coffee import *
| StarcoderdataPython |
149708 | from entities.entity import Entity
import random
#An entity that receives ticks
class TickingTrait(Entity):
delta_time = 0.0 #Time passed per frame, secs
time = 0.0 #time passed since simulation start, secs
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.at_most_fun... | StarcoderdataPython |
1733131 | <filename>TermGenerator.py
"""
Generates the terms to be used in the graph.
Supposed goals:
- Retrieve raw sentences and decide how to process them
- Cross-reference with entities to get all valid terms
-
"""
import logging
import os
import spacy
import time
from collections import Counter, OrderedDict
from utils im... | StarcoderdataPython |
144945 | <filename>crystalgodgenerator.py
#!/usr/bin/env python
""" Generate The Corpus Cloud with Page Elements, to be Styled """
import jinja2
import arrow
corpus = {
"5Cars": "http://5cars.world",
"Astral Seed": "http://trinitysoulstars.com",
"Ascension Symptoms": "http://ascension.fyi",
"Am... | StarcoderdataPython |
1777643 | # For Capstone Engine. AUTO-GENERATED FILE, DO NOT EDIT [x86_const.py]
# X86 registers
X86_REG_INVALID = 0
X86_REG_AH = 1
X86_REG_AL = 2
X86_REG_AX = 3
X86_REG_BH = 4
X86_REG_BL = 5
X86_REG_BP = 6
X86_REG_BPL = 7
X86_REG_BX = 8
X86_REG_CH = 9
X86_REG_CL = 10
X86_REG_CS = 11
X86_REG_CX = 12
X86_REG_DH = 13
X86_REG_DI ... | StarcoderdataPython |
5425 | import unittest
from routes import Mapper
class TestMapperStr(unittest.TestCase):
def test_str(self):
m = Mapper()
m.connect('/{controller}/{action}')
m.connect('entries', '/entries', controller='entry', action='index')
m.connect('entry', '/entries/{id}', controller='entry',... | StarcoderdataPython |
65801 | n = [ 1 ] + [ 50 ] * 10 + [ 1 ]
with open('8.in', 'r') as f:
totn, m, k, op = [ int(x) for x in f.readline().split() ]
for i in range(m):
f.readline()
for i, v in enumerate(n):
with open('p%d.in' % i, 'w') as o:
o.write('%d 0 %d 2\n' % (v, k))
for j in range(v):
... | StarcoderdataPython |
1775100 | <gh_stars>0
c = float(input())
f = (9/5)*c + 32
k = c + 273.15
print(f,k) | StarcoderdataPython |
3367691 | # -*- coding: utf-8 -*-
from distutils.core import setup
import settings
setup(name='nebula_web',
version=settings.Nebula_Web_Version,
description='nebula_web is nebula web server',
author='nebula',
author_email='<EMAIL>',
url='http://www.threathunter.cn',
packages=[],
)
| StarcoderdataPython |
52166 | <gh_stars>1-10
#!/usr/bin/python
# Raspberry Pi GPIO-controlled video looper
# Copyright (c) 2019 <NAME>
# License MIT
import RPi.GPIO as GPIO
import os
import sys
from subprocess import Popen, PIPE, call
import time
from threading import Lock
import signal
import argparse
class _GpioParser(argparse.Action):
""... | StarcoderdataPython |
1699199 | <reponame>aasensio/pyiacsun
from .prox_rank1_box import *
from .prox_rank1_hinge import *
from .prox_rank1_l0 import *
from .prox_rank1_l1 import *
from .prox_rank1_l1pos import *
from .prox_rank1_linf import *
from .prox_rank1_Rplus import *
| StarcoderdataPython |
3250388 | <filename>test_scripts/test2.py<gh_stars>1-10
# -*- coding:utf-8 -*-
import json
import array
import requests
url = "http://54.180.120.132:5000/"
#url = "http://1172.16.31.10:5000/"
def test():
byte_array = array.array('B')
audio_file = open("../data/sample_sound.wav", 'rb')
byte_array.frombytes(audio_f... | StarcoderdataPython |
3319864 | """ test the slip correction factor calculation
"""
import pytest
from particula import u
from particula.util.knudsen_number import knu
from particula.util.slip_correction import scf
def test_slip_correction():
""" test the slip correction factor calculation
the slip correction factor is approximately
... | StarcoderdataPython |
164325 | import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from datasets.dataset import Dataset
class AdultDataset(Dataset):
def __init__(self):
super().__init__(name="Adult Census", description="The Adult Census dataset")
self.cat_mappings = {
"education... | StarcoderdataPython |
3288741 | <gh_stars>0
import requests
import re
r = requests.get("https://dsu.edu/news")
news = re.findall(">([^<]+)</a></h2>", r.text)
for n in news:
n = n.encode("ascii", "ignore")
print n
| StarcoderdataPython |
197595 | import logging
from core.emulator.coreemu import CoreEmu
from core.emulator.emudata import IpPrefixes, NodeOptions
from core.emulator.enumerations import EventTypes
from core.nodes.base import CoreNode
from core.nodes.network import SwitchNode
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
... | StarcoderdataPython |
159977 | <gh_stars>1-10
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'GroupedMessage'
db.create_table('sentry_groupedmessage', (
('id... | StarcoderdataPython |
1709136 | <gh_stars>1-10
#! /usr/bin/python3
# Copyright © 2017 <NAME> <<EMAIL>>
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See the COPYING file for more details.
""" ...
Usage:
figLidar.py <F... | StarcoderdataPython |
1716328 | <filename>test.py
###############################################################################
#
# Copyright (c) 2018, <NAME>,
#
# 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. Redistribut... | StarcoderdataPython |
1682659 | <filename>dashboard/dashboard/debug_alert.py<gh_stars>0
# Copyright 2015 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.
"""Provides an interface for debugging the anomaly detection function."""
from __future__ import prin... | StarcoderdataPython |
1732765 | # -*- coding: utf-8 -*-
"""
Spyder Editor
京东手机TOP10数据分析.
问题列表:
%matplotlib widget在这里如何使用?或者说Spyder中如何便利的使用matplotlib
1. 长度
"""
# Part I. 基础图表
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset
import pandas as pd
import numpy as np
... | StarcoderdataPython |
137393 | <gh_stars>0
#!/usr/bin/env python
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.link import Link, TCLink,Intf
from subprocess import Popen, PIPE
from mininet.log import setLogLevel
if '__main__' == __name__:
setLogLevel('info')
net = Mininet(link=TCLink)
# key = "net.mptcp.mptcp_... | StarcoderdataPython |
3274629 | #--------------------------------------------#
# 该部分代码用于看网络结构
#--------------------------------------------#
import torch
from torchsummary import summary
from nets.deeplabv3_plus import DeepLab
if __name__ == "__main__":
# 需要使用device来指定网络在GPU还是CPU运行
device = torch.device('cuda' if torch.cuda.is_... | StarcoderdataPython |
57480 | import os
from argparse import RawTextHelpFormatter, ArgumentTypeError, ArgumentParser
from cfg_exporter.const import ExportType, ExtensionType, TEMPLATE_EXTENSION
def valid_source(source):
if os.path.exists(source):
return source
else:
raise ArgumentTypeError(_('the source path does not exis... | StarcoderdataPython |
1760893 | <reponame>elisarchodorov/ML-Recipes<filename>experiments_track/propancity/src/plots.py<gh_stars>0
import plotly.graph_objects as go
from plotly.subplots import make_subplots
["#27c1d1", "#217883", "#FF0000", "#6473ff"]
color_scheme = {"Visa": "#6473ff", "MasterCard":"#217883"}
def create_model_plots(df, feature_pl... | StarcoderdataPython |
1733581 | <gh_stars>0
#coding=utf-8
import xlsxwriter
from xlsxwriter.workbook import Workbook
from xlrd.sheet import Sheet
def demo1():
import xlsxwriter
# 创建excel文件
workbook = xlsxwriter.Workbook('demo.xlsx')
# 添加worksheet,也可以指定名字
worksheet = workbook.add_worksheet()
worksheet = workbook.add_work... | StarcoderdataPython |
1760304 | # Generated by Django 3.1.13 on 2021-12-10 13:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reservation_units', '0034_fix_reservation_start_interval_help_text'),
]
operations = [
migrations.AddField(
model_name='reserva... | StarcoderdataPython |
51435 | <reponame>lean-delivery/tf-readme-validator<filename>tests/optional-neg/test.py
#!/usr/bin/env python
import unittest
import sys
sys.path.append('../../bin')
target = __import__('tf_readme_validator')
main = target.main
readme = target.cfg['readme']
class Test1(unittest.TestCase):
def test(self):
resul... | StarcoderdataPython |
1682524 | <gh_stars>1-10
import _plotly_utils.basevalidators
class ValuessrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="valuessrc", parent_name="table.header", **kwargs):
super(ValuessrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=... | StarcoderdataPython |
25906 | """
Created on June 19th, 2017
@author: rouxpn
"""
from __future__ import division, print_function, unicode_literals, absolute_import
import warnings
warnings.simplefilter('default', DeprecationWarning)
import os
import re
from decimal import Decimal
class DecayParser():
"""
Parses the PHISICS xml decay file an... | StarcoderdataPython |
3341141 | ##############################################################################################################################################################
##############################################################################################################################################################
""... | StarcoderdataPython |
1675903 | <filename>backend/server.py
print("Starting server script")
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = ""
import flask
from flask_cors import CORS
import torch
import transformers
import traceback
app = flask.Flask(__name__)
app.config['TESTING'] = True
cors = CORS(... | StarcoderdataPython |
1699402 | #!/usr/bin/env python3
"""
The main entry point for the package.
Module Attributes:
_NAME_MOD_OVERRIDE (str): Name to use as override for `__name__` in select
cases since, in this module, `__name__` is often expected to be `__main__`.
logger (Logger): Logger for this module.
(C) Copyright 2021 <NAME>. All Ri... | StarcoderdataPython |
3263805 | '''
Support module around logging functionality for the performance scripts.
'''
from datetime import datetime
from logging import FileHandler, Formatter, StreamHandler
from logging import getLogger
from logging import INFO, WARNING
from os import getpid, makedirs, path
from time import time
import sys
import __main_... | StarcoderdataPython |
3338793 | <gh_stars>1-10
"""Gentoo Security bug scraper and vulnerable package checker."""
__version__ = '0.1.3'
| StarcoderdataPython |
4809576 | <filename>peleffy/tests/test_mapper.py
"""
This module contains the tests to check peleffy's molecular mapper.
"""
import pytest
class TestMapper(object):
"""
It wraps all tests that involve Mapper class.
"""
def test_mapper_initializer(self):
"""
It checks the initialization of the ... | StarcoderdataPython |
1724393 | <gh_stars>1-10
"""api_v1 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='ho... | StarcoderdataPython |
1744321 | <filename>qiskit/circuit/library/boolean_logic.py
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://... | StarcoderdataPython |
10876 | <reponame>mikedelong/aarhus
import json
import logging
import os
import pickle
import sys
import time
import pyzmail
# http://mypy.pythonblogs.com/12_mypy/archive/1253_workaround_for_python_bug_ascii_codec_cant_encode_character_uxa0_in_position_111_ordinal_not_in_range128.html
reload(sys)
sys.setdefaultencoding("utf8... | StarcoderdataPython |
1683660 | <reponame>CONABIO-audio/irekua-database
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from irekua_database.models import DeviceType
class MimeTypesInline(admin.TabularInline):
extra = 0
model = DeviceType.mime_types.through
autocomplete_fields = ('mimetype',)
... | StarcoderdataPython |
71638 | <gh_stars>0
# Copyright 2014 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.
from telemetry import user_story as user_story_module
class UserStorySet(object):
def __init__(self):
self.user_stories = []
def AddUs... | StarcoderdataPython |
1657980 | <reponame>cuiliang0302/myblog
# Generated by Django 3.1.3 on 2020-11-22 14:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('blog', '0014_auto_20201122_1420'),
]
operations = [
migrations.CreateModel(
... | StarcoderdataPython |
3372541 | from __future__ import unicode_literals
# Django
from django.conf import settings
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
# Local Apps
from grapevine.admin.base import BaseModelAdmin, SendableAdminMixin
from .models import Email, Emai... | StarcoderdataPython |
7767 | <filename>cracking_the_coding_interview_qs/10.4/find_x_in_listy_test.py
import unittest
from find_x_in_listy import find_x_in_listy, Listy
class Test_Case_Find_X_In_Listy(unittest.TestCase):
def test_case_find_x_in_listy(self):
listy = Listy(list(range(0, 1*10**8)))
self.assertEqual(find_x_in_listy... | StarcoderdataPython |
3209139 | <filename>gbdxtools/rda/fetch/conc/libcurl/select.py
import os
from collections import defaultdict
import threading
from tempfile import NamedTemporaryFile
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
try:
from functools import lru_cache # python 3
except ImportE... | StarcoderdataPython |
105219 | <gh_stars>0
from abc import ABC, abstractmethod
# NOTE - not making Pizza class as an ABC as we want subclasses to inherent current print messages that are linked
# to each method
class Pizza:
def __init__(self):
self.name = None
self.dough = None
self.sauce = None
self.veggies ... | StarcoderdataPython |
1725155 | <gh_stars>1-10
# Copyright (c) 2021. <NAME>
# Copyright (c) 2021. University of Edinburgh
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the a... | StarcoderdataPython |
15268 | <reponame>abijith-kp/Emolytics<gh_stars>0
from server import db, auth, emolytics
from server.models import Tweet
from classifier import create_classifier
from tweepy import Stream
from tweepy.streaming import StreamListener
from flask.ext.rq import job
import json
import random
from multiprocessing import Process
fr... | StarcoderdataPython |
3314190 | <gh_stars>0
#!/usr/bin/python3
import asterisk.agi as agi
def main():
agi_inst = agi.AGI()
agi_inst.verbose("Printing available channel values")
agi_inst.verbose(str(agi_inst.env))
callerId = agi_inst.env['agi_callerid']
agi_inst.verbose("call from %s" % callerId)
while True:
agi_inst.... | StarcoderdataPython |
190331 | <gh_stars>0
from .idol import *
from .music import *
from .tweet import *
from .calender import *
from .live import *
from .setlist import *
| StarcoderdataPython |
197114 | # @lc app=leetcode id=637 lang=python3
#
# [637] Average of Levels in Binary Tree
#
# https://leetcode.com/problems/average-of-levels-in-binary-tree/description/
#
# algorithms
# Easy (67.09%)
# Likes: 2409
# Dislikes: 215
# Total Accepted: 223.8K
# Total Submissions: 332.7K
# Testcase Example: '[3,9,20,null,nul... | StarcoderdataPython |
1708943 | from flask_restx import Namespace, Resource, fields
from .utils.decorator import save_request, token_required
from .utils.db_manager import put_doi
from .user_ns import user_response
api = Namespace('admin_doi',
description='Update the number of available DOIs per user')
number_payload = api.model(... | StarcoderdataPython |
3364062 | <reponame>RafayAK/CodingPrep
"""
This problem was asked by Amazon.
Given an array of numbers, find the maximum sum of any contiguous subarray of the array.
For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137,
since we would take elements 42, 14, -5, and 86.
Given the array [-5, -1, -... | StarcoderdataPython |
121221 | <filename>dataAnalysis/GetDataForAnalysis.py
import lidar
import time
import pickle
chunk_sizes = [3000,4000,6000]
storage = {}
port = raw_input("Enter port name which lidar is connected:") #windows
time.sleep(5)
for size in chunk_sizes:
Obj = lidar.YdLidarG4(port,size)
if(Obj.Connect()):
print(Obj.Get... | StarcoderdataPython |
4838653 | from typing import Optional
import requests
class PytweetException(Exception):
"""Exception: This is the base class of all exceptions.
.. versionadded:: 1.2.0
"""
def __init__(
self,
message: str = None,
):
self.message = message
super().__init__(self.message)
... | StarcoderdataPython |
3302403 | from train import train_model
from data_loader import load
from examples.NIPS.MNIST.mnist import MNIST_Net, neural_predicate
import torch
from network import Network
from model import Model
from optimizer import Optimizer
train_queries = load('train.txt')
test_queries = load('test.txt')[:100]
def test(model):
... | StarcoderdataPython |
1725475 | import shutil
import os
import json
import logging
import sys
from docker import APIClient
from fairing.builders.dockerfile import DockerFile
from fairing.builders.container_image_builder import ContainerImageBuilder
from fairing.utils import get_image_full
logger = logging.getLogger('fairing')
class DockerBuilder(... | StarcoderdataPython |
1649622 | <gh_stars>0
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
import information
load_dotenv(dotenv_path='.env')
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = commands.Bot(command_prefix='!')
@client.event
async def on_ready():
for guild in... | StarcoderdataPython |
3314151 | """
Hash = (s[1]*a**(n-1) + s[2]*a**(n-2)...s[n-1]*a+s[n]) mod m
"""
def polynomial_hash(base, module, string):
my_hash = 0
string_len = len(string)
for n, s in enumerate(string):
my_hash += ord(s)*(base**(string_len-n-1))
return my_hash % module
if __name__ == '__main__':
with open('i... | StarcoderdataPython |
159202 | import numpy as np
import cv2
from PIL import Image
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_default.xml')
image = cv2.imread('jeantest.JPG')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
for (x, y, w, h) in faces:
print(x,y,... | StarcoderdataPython |
1656772 | <reponame>Gwandalff/SelfAdaptableWASM
#
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# The Universal Permissive License (UPL), Version 1.0
#
# Subject to the condition set forth below, permission is hereby granted to any... | StarcoderdataPython |
1764986 | /*
wholesum = Sum((2**(m - 1) - 1)*(n + 1 - m*a)*(n + 1 - m*b), (m, 2, s)).doit()*2
vertical and horizontal : wholesum(1, 0, n, n, m)
cross : wholesum(1, 1, n, n, m)
other (gradient (a, b)) : 2*wholesum(a, b, n, floor(n/a), m)
*/
wholesum(a, b, n, s, p) = -2*Mod(2, p)^s*a*n*(s - 1) - 2*Mod(2, p)... | StarcoderdataPython |
4811114 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2018-06-15 17:58
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('data', '0050_auto_20180614_1917'),
('data', '0050_auto_20180612_1415'),
]
operation... | StarcoderdataPython |
47036 | <filename>backend_getData/get_poptweets_topic.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Downloads all tweets from a given user.
Uses twitter.Api.GetUserTimeline to retreive the last 3,200 tweets from a user.
Twitter doesn't allow retreiving more tweets than this through the API, so we get
as many as possi... | StarcoderdataPython |
1689470 | <gh_stars>1-10
import random
import string
import datetime
from math import log
def generate_timeseries(length, bounds=(0,1852255420), _type='timestamp',period=24*3600, swing=0, separator=','):
column = []
for n in range(*bounds,period):
if len(column) >= length:
break
column.appe... | StarcoderdataPython |
3258942 | <reponame>xanthous-tech/rasa-chinese-paddlenlp<filename>rasa_paddlenlp/nlu/paddlenlp_registry.py
from paddlenlp.transformers import (
BertModel,
BertTokenizer,
XLNetModel,
XLNetTokenizer,
RobertaModel,
RobertaTokenizer,
)
# these seems to be useful still, keeping
from rasa.nlu.utils.hugging_fac... | StarcoderdataPython |
154500 | from classes import biblioteca
def menu():
print("\n1-Inserir livros")
print("2- Exibir livros")
print("3-sair ")
op = int(input("\ndigite a opcao: "))
return op
def ler(biblioteca):
titulo = str(input("\ndigite o titulo do livro: "))
autor = str(input("digite o nome do autor: "))
data... | StarcoderdataPython |
3383798 | <gh_stars>0
"""Simple water flow example using ANUGA
Water flowing along a spiral wall and draining into a hole in the centre.
"""
#------------------------------------------------------------------------------
# Import necessary modules
#------------------------------------------------------------------------------
... | StarcoderdataPython |
1745235 | from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.utils.http import urlquote
from .models import MetaTags
def seo_metatags_admin_redirect(request):
url = request.GET.get('url', None)
if not url:
raise ValueError('No URL was provided in SEO redirect request.... | StarcoderdataPython |
3278315 | <reponame>cardosoyuri/RossmannStoreSalesPrediction
import pickle
import pandas as pd
from flask import Flask, request, Response
from rossmann.Rossmann import Rossmann
#loading model
model = pickle.load(open(r'C:\Users\prese\Desktop\Data Scince\Projetos\RossmannStoreSales\model\model_rossmann.pkl','rb'))
#... | StarcoderdataPython |
3305307 | <gh_stars>0
"""
qrcomm-py is a Python implementation of a QR-code communication protocol.
"""
import qrcode
from PIL import Image
import secrets
from hmac import compare_digest
from Crypto.Cipher import AES, Salsa20, ChaCha20, XChaCha20
import hashlib
hashes = {
"BLAKE2b": [hashlib.blake2b, 0]
}
ciphers = {
"AES":... | StarcoderdataPython |
3208732 | <reponame>Torolfr/hw05_final
from http import HTTPStatus
from django.contrib.auth import get_user_model
from django.test import Client, TestCase
from django.urls import reverse
from posts.models import Group, Post
User = get_user_model()
class PostsURLTests(TestCase):
@classmethod
def setUpClass(cls):
... | StarcoderdataPython |
1693091 | <reponame>ribuild/delphin_6_automation
__author__ = "<NAME>"
__license__ = 'MIT'
# -------------------------------------------------------------------------------------------------------------------- #
# IMPORTS
# Modules
import matplotlib.pyplot as plt
import numpy as np
import os
import datetime
import matplotlib.d... | StarcoderdataPython |
4837381 | from typing import Any, Dict, List, Optional
from ..._errors import ApifyApiError
from ..._utils import _catch_not_found_or_throw, _pluck_data_as_list, _snake_case_to_camel_case
from ..base import ResourceClient
class ScheduleClient(ResourceClient):
"""Sub-client for manipulating a single schedule."""
def _... | StarcoderdataPython |
3394221 | <filename>favoriteloop.py
#!/usr/bin/python3.7
favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python'}
for name in sorted(favorite_languages.keys()):
print(f"\n{name.try:
pass
except expression as identifier:
pass}") | StarcoderdataPython |
4822077 | import random
from pathlib import Path
from typing import Tuple
import glob
import numpy as np
import cv2
import torch
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import torchvision.transforms.functional as TF
from ganslate.utils.io import make_dataset_of_files
# Config imports
f... | StarcoderdataPython |
4808687 | import sqlite3 as sl
import pandas as pd
con = sl.connect('my-test.db')
con.execute("""
CREATE TABLE USER (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
);
""")
sql = 'INSERT INTO USER (id, name, age) values(?, ?, ?)'
data = [
(1, 'Alice', 21),
(2, 'Bob', 22)... | StarcoderdataPython |
47043 | <filename>src/lib/parsers/parseretinac.py
#!/usr/bin/python
# parseretinac.py
#
# By <NAME> <EMAIL> | <EMAIL>
# Copyright 2011 Intru-Shun.ca Inc.
# v0.09
# 16 October 2011
#
# The current version of these scripts are at: http://dshield.handers.org/adebeaupre/ossams-parser.tgz
#
# Parses retina community vers... | StarcoderdataPython |
3240351 | <filename>master/master.py<gh_stars>1-10
import sys
import socket
import threading
import logging
import json
import time
import random
import os
# Docker requires loopback address to be 0.0.0.0 instead of localhost.
# 'localhost' is chosen if run manually without docker.
JOB_REQUESTS_HOST = os.getenv("LOOPBACK_ADDRE... | StarcoderdataPython |
179755 | #
# Copyright (c) 2021 the Hugging Face team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | StarcoderdataPython |
1750680 | import json
from logging.config import dictConfig
from typing import List, Dict
from allennlp.models import load_archive
from allennlp.predictors import Predictor
from fever.api.web_server import fever_web_api
from fever.evidence.retrieval_methods.retrieval_method import RetrievalMethod
import os
import logging
from f... | StarcoderdataPython |
1655316 | <gh_stars>1000+
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-02-05 18:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0057_v350_remove_become_method_type'),
]
operations = [
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.