id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
5022403 | <reponame>AskNowQA/VANiLLa
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torchtext.data import BucketIterator
import random
import math
import time
import spacy
import numpy as np
from models.attn_model import *
from data.dataset import *
def attn_train(model, i... | StarcoderdataPython |
8058022 | #!/usr/bin/env python3.6
import argparse
import sys
import os
from datetime import datetime
import subprocess
import shutil
import time
from stat import *
import netCDF4
def timeString2DateTime(time_string):
year = time_string[0:4]
month = time_string[4:6]
day = time_string[6:8]
hour = time_string[8:1... | StarcoderdataPython |
254463 | from flask import Flask, request, make_response, render_template, redirect
import sqlite3
import secrets
import hashlib
import re
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
def createSessionAuthenticated(userName):
h = hashlib.sha512()
h.update(str.encode(userName))
sid = h.hexdigest()
db =... | StarcoderdataPython |
8146933 | <reponame>DASTUDIO/MyVHost
# coding=utf-8
import hashlib
def verify(signature,timestamp,nonce,echostr):
token = ""
list = [token,timestamp,nonce]
list.sort()
sha1 = hashlib.sha1()
# map(sha1.update,list)
res = ""
for item in list:
res=res+item
sha1.update(res.encode('utf-... | StarcoderdataPython |
6410000 | from flask import render_template, flash, redirect, url_for
from app import app
from app.forms import LoginForm, RecordForm, PostForm, MultiPostForm
from app.models import Post, User
from app.worker_local import UserData
from app.worker_s3 import DataFile
@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
... | StarcoderdataPython |
328066 | # encoding: utf-8
from sqlalchemy import *
from migrate import *
import uuid
def make_uuid():
return unicode(uuid.uuid4())
def upgrade(migrate_engine):
metadata = MetaData()
metadata.bind = migrate_engine
# you need to load these two for foreign keys to work
package_table = Table('package', me... | StarcoderdataPython |
5010822 | # flake8: noqa
from .conversion import localize_pydatetime, normalize_date
from .nattype import NaT, NaTType, iNaT, is_null_datetimelike
from .np_datetime import OutOfBoundsDatetime
from .period import IncompatibleFrequency, Period
from .timedeltas import Timedelta, delta_to_nanoseconds, ints_to_pytimedelta
fro... | StarcoderdataPython |
5102642 | #!/usr/bin/env python
"""Implement client side components.
Client components are managed, versioned modules which can be loaded at runtime.
"""
import importlib
import logging
import os
import StringIO
import sys
import zipfile
from grr.client import actions
from grr.lib import config_lib
from grr.lib import utils
fr... | StarcoderdataPython |
9751884 | <reponame>mattjw/sparkql
from pyspark.sql.types import StructType, StructField, StringType, ArrayType
from sparkql import merge_schemas
schema_a = StructType([
StructField("message", StringType()),
StructField("author", ArrayType(
StructType([
StructField("name", StringType())
])
... | StarcoderdataPython |
3372071 | from __future__ import absolute_import, division, print_function
import numpy as np
import h5py
import pandas as pd
import sys
sys.path.append('../')
import get_unique_craters as guc
class TestLongLatEstimation(object):
def setup(self):
ctrs = pd.HDFStore('./sample_crater_csv.hdf5', 'r')
ctrs_met... | StarcoderdataPython |
9675990 | import collections
class Solution:
"""
@param N:
@return: return true or false
"""
def reorderedPowerOf2(self, N):
# write your code here
curr = collections.Counter(str(N))
return any(curr == collections.Counter(str(1 << i)) for i in range(31))
| StarcoderdataPython |
6519258 |
# Ensure that no users have access keys that have never been used.
# Description: Checks that all users have only active access keys.
#
# Trigger Type: Change Triggered
# Scope of Changes: IAM:User
import json
import logging
import boto3
APPLICABLE_RESOURCES = ["AWS::IAM::User"]
def evaluate_compliance(configura... | StarcoderdataPython |
9655900 | # ------------------------------------------------------------------------
# MIT License
#
# Copyright (c) [2021] [<NAME>]
#
# This code is part of the library PyDL <https://github.com/nash911/PyDL>
# This code is licensed under MIT license (see LICENSE.txt for details)
# -----------------------------------------------... | StarcoderdataPython |
6596865 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 16 15:04:40 2020
@author: user
"""
from playwithml import predictor as p
P = p('datasets/iris.csv')
print(P.do_all(c=True))
| StarcoderdataPython |
8159583 | """
Date: 2022.02.03 9:11
Description: Omit
LastEditors: <NAME>
LastEditTime: 2022.02.03 9:11
"""
import os
from enum import IntEnum
from .common import writer
def pypirc(read_only=True):
official = "https://packaging.python.org/en/latest/specifications/pypirc/"
conf = os.path.join(os.path.expanduser("~"), ... | StarcoderdataPython |
3430490 | import logging
import socketio
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from src import routers
from src.utils.global_instances import sio
from src import socketio_events
logger = logging.getLogger("uvicorn.error")
app = FastAPI(debug=True)
app.add_middleware(
CORSMiddle... | StarcoderdataPython |
9760383 | <reponame>Junkbite/smoked-salmon
import re
from collections import defaultdict
from html import unescape
from salmon.common import RE_FEAT, parse_copyright, re_split
from salmon.sources import DeezerBase
from salmon.tagger.sources.base import MetadataMixin
RECORD_TYPES = {
"album": "Album",
"ep": "EP",
"s... | StarcoderdataPython |
1785685 | from django import forms
from .models import CreditApplication
class CreditApplicationForm(forms.ModelForm):
class Meta:
model = CreditApplication
fields = '__all__'
| StarcoderdataPython |
9630535 | <filename>config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
# BASIC APP CONFIG
WTF_CSRF_ENABLED = os.getenv('CSRF_ENABLED', 'yes') == 'yes'
SECRET_KEY = os.getenv('SECRET_KEY', 'secret')
BIND_ADDRESS = os.getenv('BIND_ADDRESS', '0.0.0.0')
PORT = os.getenv('PORT', 9393)
LOGIN_TITLE = os.getenv('L... | StarcoderdataPython |
4844197 | <filename>Calibration.py
class Calibration:
def __init__(self, radio_calib=None, intr_calib=None, geo_calib=None):
# This class simply combines the calibration objects from the different calibration procedures
self.radio_calib = radio_calib
self.intr_calib = intr_calib
self.geo_calib... | StarcoderdataPython |
3273114 | import asyncio
import functools
def wrap_sync_writer(writer):
class AsyncWriter:
def __init__(self, writer):
self.write = wrap_sync_func(writer.write)
return AsyncWriter(writer)
def wrap_sync_reader(reader):
class AsyncReader:
def __init__(self, reader):
self.rea... | StarcoderdataPython |
9717538 | __author__ = "<NAME> <http://intertwingly.net/> and <NAME> <http://diveintomark.org/>"
__version__ = "$Revision$"
__copyright__ = "Copyright (c) 2002 <NAME> and <NAME>"
from .base import validatorBase
from .validators import *
#
# Atom link element
#
class link(nonblank,xmlbase,iso639,nonhtml,nonNegativeInteger,rfc33... | StarcoderdataPython |
318504 | n = int(input())
left_dp = [1] * (n + 1)
right_dp = [1] * (n + 1)
arr = list(map(int, input().split()))
for i in range(1, n):
for j in range(i):
if arr[j] < arr[i]:
left_dp[i] = max(left_dp[i], left_dp[j] + 1)
for i in range(n - 2, -1, -1):
for j in range(n - 1, i, -1):
if arr[j]... | StarcoderdataPython |
1676345 | import argparse
import random
import numpy as np
import torch
from nner import *
from transformers import *
# take args
parser = argparse.ArgumentParser()
## Required parameters
parser.add_argument("--source_language", default='en', type=str,
help="The target language")
parser.add_argument("--targe... | StarcoderdataPython |
162415 | '''
Created on Feb 3, 2017
@author: Akash
link_preview is now a fashionable way of sharing links
in social media. The contents of what the preview is
made up are:-
1. og.title:-
Title of the preview.
In HTML: <meta property="og.title" content="XYZ">
... | StarcoderdataPython |
5175401 | <reponame>fragmuffin/howto-micropython
import machine
pin = machine.Pin('SW', machine.Pin.IN, machine.Pin.PULL_UP)
pin = machine.Pin('SW', machine.Pin.IN, machine.Pin.PULL_DOWN)
pin = machine.Pin('SW', machine.Pin.IN, machine.Pin.PULL_NONE)
# These 2 initialize the pin in the same way
pin = machine.Pin('SW') # defau... | StarcoderdataPython |
11233426 | from django.conf.urls.defaults import *
from django.views.generic.list_detail import object_list
from tagging.views import tagged_object_list
from badges.models import Badge
from badges.feeds import RecentlyClaimedAwardsFeed, RecentlyClaimedAwardsJSONFeed
from badges.feeds import AwardsClaimedForProfileFeed, Awards... | StarcoderdataPython |
172158 | '''
flask_miracle.functions
-----------------------
functions callable from within a Flask context
'''
from flask import current_app
def check_any(resource, permission, roles=None):
return current_app.miracle_acl_manager.check_any(resource, permission, roles=None)
def check_all(resource, permission, roles=None)... | StarcoderdataPython |
1918332 | <gh_stars>1000+
# SPDX-License-Identifier: MIT
# Copyright (C) 2018-present iced project and contributors
# ⚠️This file was generated by GENERATOR!🦹♂️
# pylint: disable=invalid-name
# pylint: disable=line-too-long
# pylint: disable=too-many-lines
"""
(MVEX) EH bit value
"""
import typing
if typing.TYPE_CHECKING:
... | StarcoderdataPython |
4900233 | <reponame>PraveenKumar-Rajendran/CarND-Behavioral-Cloning<gh_stars>0
version https://git-lfs.github.com/spec/v1
oid sha256:c9bd3410a4d0bb585f7dc4ff96eb71361c8acfacbab10e278230b6be4a8cb983
size 3457
| StarcoderdataPython |
6648819 | <filename>psims/mzmlb/components.py<gh_stars>10-100
from ..mzml.components import BinaryDataArray, Binary, NullMap
from ..xml import _element
EXTERNAL_DATASET_PARAM = "external HDF5 dataset"
# EXTERNAL_DATASET_PARAM = "external dataset"
class ExternalBinaryDataArray(BinaryDataArray):
def __init__(self, external... | StarcoderdataPython |
5172480 | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# DESCRIPTION: Given an excel file and text files passed as arguments to the script,
# metadata headers are added to each individual text files
# Windows run with Anaconda Prompt example:
# python add_headers.py --directory="Fall 2018/normalized/" --master_file=... | StarcoderdataPython |
3481422 | <reponame>1995chen/jingdong_financial
# -*- coding: utf-8 -*-
from typing import Optional
import inject
import template_logging
from template_pagination import Pagination
from sqlalchemy.orm import Query
from sqlalchemy import desc
from template_transaction import CommitContext
from app.models import GoldPrice
from... | StarcoderdataPython |
4843431 | <reponame>leonardcser/waldo-video-preprocessor
from utils.command_utils import check_docker_installed, run_cmd
from variables import IMAGE_NAME
from utils.logger import logger
def main() -> None:
"""Main function to remove the docker image"""
check_docker_installed()
user_input = input(
(
... | StarcoderdataPython |
6654519 | def main():
fh = open("file.txt")
for line in fh:
print(line)
fh.close()
with open("file2.txt") as fh2:
for line in fh2:
print(line)
with open("file3.txt", "rb") as fh3:
for l in fh3:
print(l)
if __name__ == '__main__':
main()
| StarcoderdataPython |
385065 | <reponame>azagajewski/ColiCoords
from colicoords.data_models import BinaryImage, BrightFieldImage, FluorescenceImage, STORMTable, Data
from colicoords.fileIO import load_thunderstorm, load
from colicoords.cell import Cell, CellList
from test.testcase import ArrayTestCase
from test.test_functions import load_testdat... | StarcoderdataPython |
3410666 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# Invenio-RDM-Records is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Test rights schema."""
import pytest
from marshmallow import ValidationError
from invenio_rdm_records.ser... | StarcoderdataPython |
264434 | # **************************** Desafio 094 ********************************* #
# Unindo dicionários e listas #
# Crie um programa que leia nome, sexo e idade de várias pessoas, guardando #
# os dados de cada pessoa em um dicionário e todos os dicionários em uma #
# li... | StarcoderdataPython |
9740208 | # 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, ... | StarcoderdataPython |
1856540 | __author__ = 'wangfeng'
import time
import os
import shutil
from functools import wraps
from oslo.config import cfg
from libcloud.compute.types import StorageVolumeState,NodeState
from libcloud.compute.base import NodeSize, NodeImage,NodeAuthSSHKey
from libcloud.storage.types import ObjectDoesNotExistError
import sshc... | StarcoderdataPython |
6455453 | <reponame>LoansBot/database
"""Restore the backup specified to the database. Requires user confirmation or
--confirm
"""
import argparse
import os
import sys
import settings
import subprocess
def main(args=None):
parser = argparse.ArgumentParser(description='Restore backup')
parser.add_argument('-... | StarcoderdataPython |
5195818 | from django.contrib import admin
from .models import Country, Author, Category, Book
@admin.register(Country)
class CountryAdmin(admin.ModelAdmin):
pass
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
pass
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
pass
@admin.reg... | StarcoderdataPython |
6477734 | import os
from distutils.core import setup
install_requires=[
"numpy",
"nltk",
"textblob",
"keras",
"pandas",
]
setup_requires=[
"numpy",
]
extras_require = {
"fasttext": ["fasttext"],
}
setup(
name="ontokom",
version="0.1",
description="",
url="",
author="<NAME>",
... | StarcoderdataPython |
334393 | import cv2
DEFAULT_HEIGHT = 720
DEFAULT_WIDTH = 1280
"""
Change image resolution
Defaults to 1280 * 720
"""
class Image():
def __init__(self, image,height=DEFAULT_HEIGHT,width=DEFAULT_WIDTH):
self.image = image
self.height = height
self.width = width
def read(self):
... | StarcoderdataPython |
296096 | <reponame>ANRGUSC/pyREM
import math
import scipy.integrate as integrate
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import root
RHO_A = 1.21 #density of air in kg/m^3
RHO_D = 1000 #density of droplet in kg/m^3
RHO = RHO_A
RHO_P = RHO_D
G = 9.81 #gravitational acceleration in m/s^2
VISCOSITY... | StarcoderdataPython |
1972893 | <filename>leetcode/easy/Binary_Tree_Level_Order_Traversal_II.py
# -*- coding: utf-8 -*-
"""
created by huash06 at 2015-04-13 11:28
Given a binary tree, return the bottom-up level order traversal of its nodes' values.
(ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#... | StarcoderdataPython |
6632792 | from fpdf import FPDF
class Cards(FPDF):
def __init__(self, orientation = 'P', unit = 'mm', format='A4'):
super().__init__(orientation, unit, format)
self.cards = []
self.curr_card = 0
# we do not want to auto page break
self.set_auto_page_break(False)
def add_card(self... | StarcoderdataPython |
6414641 | <reponame>zhanghao000/project_news
from flask import render_template, current_app, session, request, jsonify
from info import constants
from info.models import User, News, Category
from info.modules.news import index_blu
from info.utils.response_code import RET
@index_blu.route("/news_list")
def get_news_list():
... | StarcoderdataPython |
1956734 | <reponame>VirtualVFix/AndroidTestFramework
# All rights reserved by forest fairy.
# You cannot modify or share anything without sacrifice.
# If you don't agree, keep calm and don't look at code bellow!
"""
Additional functions integrated to `logging.Logger` class when new logger created in :mod:`src.libs.core.logger` ... | StarcoderdataPython |
304074 | <filename>transactions/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.contrib.auth.models import User
from projects.models import Project
from transactions.models import Transaction, Candidate
from transactions.forms import CandidateForm, SourcingF... | StarcoderdataPython |
376128 | import argparse
from download.download import VideoDownloader
from utils import (
reset_default_params,
set_cookies_path,
set_media_directory,
update_params,
)
def str_to_bool(v):
if isinstance(v, bool):
return v
elif v.lower() in ['true', 't', '1']:
return True
elif v.lo... | StarcoderdataPython |
4900947 | <gh_stars>0
from floodsystem.geo import rivers_by_station_number
from floodsystem.stationdata import build_station_list
from floodsystem.station import MonitoringStation
"""stations = build_station_list()
print(rivers_by_station_number(stations,10))"""
def run():
'build a list of stations'
stations =... | StarcoderdataPython |
5123650 | """
A wrapper around Requests to make Restful API calls
"""
from urllib.error import HTTPError
from urllib.error import URLError
import requests
class Base_API:
"Main base class for Requests based scripts"
def __init__(self, url=None):
pass
def json_or_text(self, response):
"Class to defi... | StarcoderdataPython |
12803768 | <reponame>shencebebetterme/pyTN
#!/usr/bin/python3
""" A module that generates and stores various results of different
coarse-graining algorithms for different lattice models. The point is
that when a tensor is requested, the module checks whether it already is
stored on the hard drive, and returns it if it is. If not... | StarcoderdataPython |
6407937 | from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from config import table, LONGITUDE, LATITUDE, logger, DATETIME_FORMAT, LIMIT_OUTPUT, APPID, DYNAMODB_TABLE
from models import OpenWeatherInsight
from openweather_api import OneCallAPI
def run(event, context):
api... | StarcoderdataPython |
1793809 | # Generated by Django 2.2.6 on 2019-12-18 20:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('a1test', '0006_questiontype_kinds'),
]
operations = [
migrations.AlterField(
model_name='exam',
name='time',
... | StarcoderdataPython |
3222831 | <filename>crowdsourcing/viewsets/task.py
from crowdsourcing.serializers.task import *
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import detail_route, list_route
from django.shortcuts import get_object_or_404
from crowdsourcing.permissions.proj... | StarcoderdataPython |
6563842 | <gh_stars>0
# coding=utf-8
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Tag(models.Model):
class Meta:
app_label = 'blog'
verbose_name = '标签'
verbose_name_plural = '标签'
name = models.CharField(max_length=40)
def ... | StarcoderdataPython |
1785249 | from trex.models.project import *
from trex.models.user import *
| StarcoderdataPython |
3517777 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 11:12:29 2019
@author: anna
Import the tilt and splay angle data.
make an histogram and fit the histogram with a gaussian.
use the range of the gaussian to fit the PMF
Compute the Kt and Kc as described in Phys. Chem. Chem. Phys. 2017... | StarcoderdataPython |
8138799 | <reponame>ryanjwise/free-speech
import os
def get_input():
user_input = input("What would you like to say?")
return user_input
def play_input(input):
os.system(f"espeak '{input}'")
def app_loop():
loop = True
while loop:
user_input = get_input()
play_input(user_input)
os.s... | StarcoderdataPython |
5193615 | <reponame>david58/gradertools
import os
from .compile_python import CompilerPython
from .compile_cpp import CompilerCpp
#from ..isolation.isolate import Isolate
class Compile:
def __init__(self, sourcepath, compiler, isolator=None):
if compiler == 'python':
Compiler = CompilerPython
el... | StarcoderdataPython |
6432882 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.insert(0, "../")
import threading
import time
import logging
import snakemq
import snakemq.link
import snakemq.packeter
import snakemq.messaging
import snakemq.queues
import snakemq.rpc
class B(object):
def wer(self):
print("wer")
def f(... | StarcoderdataPython |
6606027 | from func.firebase_init import db
from func.blackjack import *
from disnake.ext.commands import Param
from disnake.ext import commands
import disnake
class BJ(disnake.ui.View):
def __init__(self, og_inter: disnake.MessageInteraction, bet: int, user_money: int):
super().__init__()
self.result = N... | StarcoderdataPython |
1652060 | <reponame>lejion/django-sagepaypi<filename>sagepaypi/urls.py
from django.urls import path
from sagepaypi import views
app_name = 'sagepaypi'
urlpatterns = [
path(
'transactions/<tidb64>/<token>/3d-secure/complete/',
views.Complete3DSecureView.as_view(),
name='complete_3d_secure'
)
]
| StarcoderdataPython |
6579542 | # - Generated by tools/entrypoint_compiler.py: do not edit by hand
"""
TimeSeriesProcessingEntryPoints.SlidingWindowTransform
"""
import numbers
from ..utils.entrypoints import EntryPoint
from ..utils.utils import try_set, unlist
def timeseriesprocessingentrypoints_slidingwindowtransform(
source,
da... | StarcoderdataPython |
1624478 | <reponame>kanglicheng/learn-python-2020<filename>stephen/week1.py
"""
Chooses a random integer in [0, 100]. Asks user to enter a guess,
terminates only when user guesses correctly
"""
import random
def guessing_game():
number = random.randint(1, 5)
while True:
guess = int(
input("Please en... | StarcoderdataPython |
3598588 | import json, logging, os, psutil, requests, sys, traceback
from datetime import datetime
from ischedule import schedule, run_loop
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
from os import environ
def create_logger() :
log = logging.getLogger('')
... | StarcoderdataPython |
9610890 | <reponame>guanghuixu/multi-model-forgetting<gh_stars>10-100
from collections import defaultdict, deque
import os
import pickle
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
# from torch.tensor import ones
from models.cnn_layers import CNN_LAYER_CREATION_FUNCTIONS, initialize_l... | StarcoderdataPython |
4838053 | import sys
import click
import pprint
import json
import os
import datetime
import pyaurorax
from dateutil.parser import parse
from ..helpers import (print_request_logs_table,
print_request_status,
get_search_data)
from ..templates import EPHEMERIS_SEARCH_TEMPLATE
def __c... | StarcoderdataPython |
3570816 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
__author__ = 'zd'
import joblib
import data_utils
import model
import global_parameters as config
from flask import Flask, request, jsonify
app = Flask(__name__)
stop_words = data_utils.read_stopwords()
w2v_model = joblib.load(config.w2v_model_path)
@app.route('/get_summ... | StarcoderdataPython |
330991 | # 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 |
3376173 | <reponame>showerbugs/showerbasket
import time
import requests
from api import API
class Account(API):
def __init__(self):
super().__init__()
self.base = f'{self.base}/account'
def balance(self):
url = f'{self.base}/balance'
payload = {
'access_token': self.access... | StarcoderdataPython |
3594906 | <filename>sources/models/femnist/femnist_model_template.py
import tensorflow as tf
from typing import List, Union, Optional
from sources.global_data_properties import FEMNIST_IMAGE_SIZE, FEMNIST_CLASSES
from sources.metrics.default_metrics_tf import get_default_sparse_categorical_metrics_tf
from sources.models.keras_m... | StarcoderdataPython |
381534 | <filename>resources.py
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.11.2)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x04\xe5\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\... | StarcoderdataPython |
3503217 | <gh_stars>0
# coding=utf-8
# Advent of Code 2021 - Day 1
import utils
class Visit:
def __init__(self, allowed, count):
self.allowed = allowed
self.count = count
| StarcoderdataPython |
11274813 | """
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
https://leetcode.com/problems/letter-combinations-of-a-phone-num... | StarcoderdataPython |
1976719 | <gh_stars>0
class LLNode:
def __init__(self, n = None):
self.data = n
self.next = None
class SLL:
def __init__(self, n = None):
self.Head = None
if __name__ == '__main__':
ll = SLL()
ll.Head = LLNode()
ll.delete(1)
ll.insertleft(1)
ll.insertright(2)
ll.p... | StarcoderdataPython |
3427694 | '''
create_db.py
create db tables
'''
import sqlite3
def create_db(dbname):
conn = sqlite3.connect(dbname)
c = conn.cursor()
# create table document
c.execute('''CREATE TABLE document
(id INTEGER PRIMARY KEY,
document TEXT UNIQUE,
hash TEXT... | StarcoderdataPython |
3419119 | from django.shortcuts import render
from .models import brand,car_model
from django.views.generic import DetailView
def home(request):
for x in brand.objects.all():
cars_related = x.car_model_set.all()
x.cars_to_brand.set(cars_related)
x.save()
context = {
'cars':brand.objects.a... | StarcoderdataPython |
4875559 | """Test the TimeoutR2CClient"""
import unittest
from PiCN.Packets import Name, Content, Interest
from PiCN.Layers.NFNLayer.R2C import TimeoutR2CHandler
from PiCN.Layers.NFNLayer.Parser import DefaultNFNParser
from PiCN.Layers.NFNLayer.NFNComputationTable import NFNComputationList
class test_TimeoutR2CClient(unittest... | StarcoderdataPython |
6403106 | # -*- coding: utf-8 -*-
'''
Created on 2016-12-07
@author: hustcc
'''
from __future__ import absolute_import
from app import SQLAlchemyDB as db
class BaseMethod(object):
__table_args__ = {'mysql_engine': 'MyISAM', 'mysql_charset': 'utf8'}
# insert and update
def save(self):
db.session.add(self)
... | StarcoderdataPython |
8049651 | import os
import sys
import copyright
from distutils.core import setup
from setuptools import setup, find_packages
version = copyright.__version__
setup(
name='django-copyright',
version=version,
packages=find_packages(),
license='BSD',
description="Copyright django app",
long_description=ope... | StarcoderdataPython |
11204558 | <gh_stars>1000+
# Copyright 2021 Google LLC. 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 app... | StarcoderdataPython |
12857636 | import pandas as pd
import numpy as np
print("Data Loading....")
#data = pd.read_csv("adult.csv")
data = pd.read_csv("adult_2.csv")
# print(data)
# print(data.columns)
# print(data.shape)
# print(data.info())
# print(data.nunique())
data.describe()
data.isin(['?']).sum()
data = data.replace('?', np.Na... | StarcoderdataPython |
396948 | <reponame>jkbjh/sacreddata
import os
try:
import ujson as json
except ImportError:
import json
import dictor
import datetime
import io
import shutil
import pandas as pd
import warnings
class BuildCommandMixin(object):
def build_command(self):
vals = dict(self.run["experiment"])
vals.update... | StarcoderdataPython |
6624006 | <filename>wsm/backend/asyncwhois/cache.py
from .base import BaseCacheHandler, Action, Kind
import json
from ..services import (
get_whois,
create_whois,
get_whois_by_ip,
update_whois_by_ip,
get_cache_by_ip,
)
class IPWhoisCacheHandler(BaseCacheHandler):
async def create(self, action: Action):
... | StarcoderdataPython |
3227811 | from datetime import datetime, timedelta
import pandas as pd
import flask
from sqlalchemy import extract, asc, desc, func, text
from app import db, app
today = datetime.today()
first_of_this_month = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
last_of_prev_month = first_of_this_month - timedelta(day... | StarcoderdataPython |
1897419 | """Sphinx demo."""
from pathlib import Path
import sys
if sys.platform == 'win32':
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
__version__ = '0.0.2'
__version_full__ = __version__
def get_html_theme_path():
"""
Return path to Sphinx templates folder.
""... | StarcoderdataPython |
3384153 | <filename>src/aptsources_cleanup/util/zipfile.py
# -*- coding: utf-8
from . import strings
from . import collections
from .itertools import filterfalse
import sys
import os
import stat
import errno
import functools
from zipfile import *
import zipfile as _zipfile
__all__ = _zipfile.__all__
try:
from os import fspath... | StarcoderdataPython |
8174486 | #!/usr/bin/env python2.7
# pylint: disable=bad-indentation, no-member, invalid-name, line-too-long
import os
import shutil
import random
import argparse
import multiprocessing
import cv2
import lmdb
import caffe
import numpy as np
from jfda.config import cfg
from jfda.utils import load_wider, load_celeba
from jfda.uti... | StarcoderdataPython |
3431939 | <reponame>JohnOmernik/jupyter_mssql<filename>mssql_core/mssql_base.py<gh_stars>0
#!/usr/bin/python
# Base imports for all integrations, only remove these at your own risk!
import json
import sys
import os
import time
import pandas as pd
from collections import OrderedDict
import requests
from integration_core import I... | StarcoderdataPython |
6402496 | <reponame>Chenglin-Yang/PatchAttack<filename>PatchAttack/utils.py
import os
import time
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# torch
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as Transforms
import torchvision.m... | StarcoderdataPython |
3249217 | # Copyright (c) 2016 <NAME>, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, dist... | StarcoderdataPython |
6449383 | class Add:
def add(self, n1, n2, n3=0):
print("add of Add")
return n1 + n2 + n3
class Add2:
def add(self, n1, n2, n3=0):
print("add of Add2")
return n1 * n2
# 부모들 중 같은 시그너쳐의 메서드가 있다면 먼저 상속선언된 부모의 메서드가 우선시 되는 것 같다
class Calculator(Add2, Add):
def sub(self, n1, n2):
... | StarcoderdataPython |
6410027 | <filename>storm_control/sc_library/datareader.py
#!/usr/bin/env python
"""
Classes that handles reading STORM movie files. This is used by
the Steve program and it assumes the existance of an XML file
that describes everything that one needs to know about a movie.
Hazen 07/15
"""
#
# FIXME: Why not just use the versi... | StarcoderdataPython |
1675015 | <reponame>adeogliari/GeekUniversity_Python<filename>s05_estruturas_logicas_e_condicionais/s05_exercicios/s05_exercicio_20.py
"""
20) Dados três valores A, B, C, verificar se eles podem ser valores dos lados de um triângulo e, se forem,
se é um triângulo escaleno, equilátero ou isóscele, considerando os seguintes conce... | StarcoderdataPython |
8045541 | """Dyson climate platform."""
import logging
from typing import List, Optional
from libdyson import DysonPureHotCoolLink
from custom_components.dyson_local.utils import environmental_property
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_H... | StarcoderdataPython |
28585 | <filename>apps/my_app/handlers.py
import datetime
import fastapi
import pymongo
import pymongo.errors
import pymongo.results
from apps.common.enums import CodeAudiences
from apps.common.handlers import PasswordsHandler, TokensHandler
from fastapi_mongodb.exceptions import HandlerException, RepositoryExcept... | StarcoderdataPython |
5026515 | <gh_stars>1-10
#!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.