content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
##############################################################
# Fixing missmatches in parsing of doccano output
# The script also does not claim to be a reusable solution,
# instead it merely adapts the doccano output files to correspond
# to the entity split style of LitBank.
# Input: pandas dataframe, filename
# Ou... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @Date : 2017-07-18 13:26:17
# @Author : lileilei
'''
导入测试接口等封装
'''
import xlrd
def pasre_inter(filename):#导入接口
file=xlrd.open_workbook(filename)
me=file.sheets()[0]
nrows=me.nrows
ncol=me.ncols
project_name=[]
model_name=[]
interface_name=[]
interface_url=[]
interf... | nilq/baby-python | python |
# Create a function named same_name() that has two parameters named your_name and my_name.
# If our names are identical, return True. Otherwise, return False.
def same_name(your_name, my_name):
if your_name == my_name:
return True
else:
return False
| nilq/baby-python | python |
import numpy as np
import json
def _reject_outliers(data, m=5.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d / mdev if mdev else 0.
return data[s < m]
def reject(input_):
for line in input_:
d = json.loads(line)
print(_reject_outliers(np.array(d)).tolist())
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from django.template import loader
from django.utils import formats
from django.utils.text import Truncator
import django_tables2 as tables
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from ..html import AttributeDict, Icon
def merge_attrs... | nilq/baby-python | python |
"""
Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25.
This cipher rotates the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".... | nilq/baby-python | python |
import re
import pprint
from collections import Counter
ihaveadream = open('ihaveadream.txt', 'r')
read_dream = ihaveadream.read()
split = read_dream.split()
just_words = [re.sub('[^a-zA-Z]+','',i) for i in split]
just_long_words = []
for word in just_words:
word = word.lower()
if len(word) > 3:
j... | nilq/baby-python | python |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
import os
import sys
from glob import glob
import re
import json
import random
import shutil
import re
import codecs
dones = [x for x in open("done.txt",'r').read().split("\n... | nilq/baby-python | python |
from future.utils import with_metaclass
from openpyxl_templates.exceptions import OpenpyxlTemplateException
from openpyxl_templates.utils import OrderedType, Typed
class TemplatedWorkbookNotSet(OpenpyxlTemplateException):
def __init__(self, templated_sheet):
super(TemplatedWorkbookNotSet, self).__init__(... | nilq/baby-python | python |
import hashlib, hmac, time
def compute_signature(message, secret):
message = message.encode('utf-8')
timestamp = str(int(time.time()*100)).encode('ascii')
hashdata = message + timestamp
signature = hmac.new(secret.encode('ascii'),
hashdata,
hashlib.sha... | nilq/baby-python | python |
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
TEASERSWRAP_ALLOW_CHILDREN = getattr(
settings,
'TEASERS_TEASERSWRAP_ALLOW_CHILDREN',
True
)
TEASERSWRAP_PLUGINS = getattr(
settings,
'TEASERS_TEASERSWRAP_PLUGINS',
[
'TeaserPlugin',
]
)
TEAS... | nilq/baby-python | python |
from .models_1d import *
from .models_2d import *
from .models_3d import *
def M1D(config):
if config.model_module == 'V2SD':
model = V2StochasticDepth(n=config.channels,
proba_final_layer=config.proba_final_layer,
sdrop=config.sdrop,
... | nilq/baby-python | python |
"""Tests for the :mod:`campy.datastructures.sparsegrid` module."""
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# GOM-Script-Version: 6.2.0-6
# Anja Cramer / RGZM
# Timo Homburg / i3mainz
# Laura Raddatz / i3mainz
# Informationen von atos-Projektdateien (Messdaten: *.amp / *.session)
# 2020/2021
import gom
import xml, time, os, random
import math
import datetime
## Indicates if only properties for w... | nilq/baby-python | python |
# Generated by Django 2.2.2 on 2019-09-19 12:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('dcodex', '0001_initial'),
('dcodex_bible', '0001_initial'),
]
operations = [
mi... | nilq/baby-python | python |
for i in range(0, 10, 2):
print(f"i is now {i}") | nilq/baby-python | python |
# -- coding: utf-8 --
# Copyright 2019 FairwindsOps 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 l... | nilq/baby-python | python |
import re
import ast
import discord
from redbot.core import Config
from redbot.core import commands
from redbot.core import checks
defaults = {"Prefixes": {}}
class PrefixManager(commands.Cog):
"""Used to set franchise and role prefixes and give to members in those franchises or with those roles"""
def __i... | nilq/baby-python | python |
#!/usr/bin/env python
"""
.. py:currentmodule:: FileFormat.Results.test_PhirhozElement
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
Tests for the module `PhirhozElement`.
"""
# Script information for the file.
__author__ = "Hendrix Demers (hendrix.demers@mail.mcgill.ca)"
__version__ = ""... | nilq/baby-python | python |
from json import loads
from random import choice
from .base_menti_question import BaseMentiQuestion
QUOTES_PATH = 'quotes.json'
def get_quotes(filename=QUOTES_PATH):
with open(filename) as f:
return f.read()
return ''
class MentiText(BaseMentiQuestion):
max_text_len = 140
needed_attr = []
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from .wiserapi import WiserBaseAPI, _convert_case
class SetPoint:
def __init__(self):
self.time = None
self.temperature = None
class Schedule(WiserBaseAPI):
"""Represnts the /Schedule object in the Restful API"""
def __init__(self, *args, **kwargs):
# Def... | nilq/baby-python | python |
def lagrange(vec_x, vec_f, x=0):
tam,res = len(vec_x),0
L = [0]*tam
for i in range(tam):
L[i] = 1
for j in range(tam):
if j != i:
L[i] = L[i] * (x - vec_x[j])/(vec_x[i] - vec_x[j])
for k in range (tam):
res = res + vec_f[k]*L[k]
print(res)
x =... | nilq/baby-python | python |
import os
import pandas as pd
import numpy as np
import shutil
cwd = os.getcwd()
sysname = os.path.basename(cwd)
print(sysname)
if os.path.isdir(cwd+'/lmbl/'):
shutil.rmtree(cwd+'/lmbl/')
os.mkdir('lmbl')
coor = os.path.join(cwd+ '/coordinates/')
lmbl = os.path.join(cwd+ '/lmbl/')
os.chdir(lmbl)
for filename in os.... | nilq/baby-python | python |
# Copyright 2016 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 or at
# https://developers.google.com/open-source/licenses/bsd
"""Servlet for Content Security Policy violation reporting.
See http://www.html5rocks.com/en/tu... | nilq/baby-python | python |
import datetime
from pathlib import Path
from typing import Iterator, Any
import pytest
import google_takeout_parser.parse_json as prj
@pytest.fixture(scope="function")
def tmp_path_f(
request: Any, tmp_path_factory: pytest.TempPathFactory
) -> Iterator[Path]:
"""
Create a new tempdir every time this run... | nilq/baby-python | python |
from __future__ import annotations
from typing import TYPE_CHECKING
import discord
from discord.ext import typed_commands
from .exceptions import NotGuildOwner, OnlyDirectMessage
if TYPE_CHECKING:
from discord.ext.commands import core
def dm_only() -> core._CheckDecorator:
def predicate(ctx: core._CT, /) ... | nilq/baby-python | python |
# Copyright 2018 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.
"""Recipe for updating the go_deps asset."""
DEPS = [
'checkout',
'infra',
'recipe_engine/context',
'recipe_engine/properties',
'recipe_engine/p... | nilq/baby-python | python |
import spacy
import numpy as np
import os, shutil, json, sys
import json, argparse, logging
from tqdm import tqdm
import tensorflow as tf
from collections import defaultdict
from MultiHeadAttention import *
class GAN:
def __init__(self, input_shapes, embedding_size, question_padding):
#input shapes is in ... | nilq/baby-python | python |
"""A Yelp-powered Restaurant Recommendation Program"""
from abstractions import *
from data import ALL_RESTAURANTS, CATEGORIES, USER_FILES, load_user_file
from ucb import main, trace, interact
from utils import distance, mean, zip, enumerate, sample
from visualize import draw_map
##################################
# ... | nilq/baby-python | python |
import subprocess
import ansiconv
import sys
from django.conf import settings
from django.http import StreamingHttpResponse
from django.shortcuts import get_object_or_404
from django.views.generic import View
from fabric_bolt.projects.models import Deployment
from fabric_bolt.projects.signals import deployment_finish... | nilq/baby-python | python |
import json
import asyncio
import sys
from joplin_api import JoplinApi
from httpx import Response
import pprint
import difflib
import logging
with open('.token','r') as f:
token = f.readline()
joplin = JoplinApi(token)
async def search(query):
res = await joplin.search(query,field_restrictions='title')
lo... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 30/11/2021 22:19
# @Author : Mr. Y
# @Site :
# @File : similarity_indicators.py
# @Software: PyCharm
import numpy as np
np.seterr(divide='ignore',invalid='ignore')
import time
import os
from utils import Initialize
os.environ['KMP_DUPLICATE_LIB_OK'] = ... | nilq/baby-python | python |
"""
"""
try:
from stage_check import Output
except ImportError:
import Output
try:
from stage_check import OutputAssetState
except ImportError:
import OutputAssetState
def create_instance():
return OutputAssetStateText()
class OutputAssetStateText(OutputAssetState.Base, Output.Text):
"""
"... | nilq/baby-python | python |
import re
from django.urls import re_path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
re_path(r'^$',views.account,name='account'),
re_path(r'^account/',views.account,name='account'),
re_path(r'^home/',views.home,name='home'),
re_path(r... | nilq/baby-python | python |
# coding: utf-8
# flake8: noqa E266
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from flask_env import MetaFlaskEnv
from celery.schedules import crontab
class base_config(object, metaclass=MetaFlaskEnv):
"""Default configuration options."""
ENV_PREFIX = 'APP_'
SITE_NAME = 'T... | nilq/baby-python | python |
You are given an array nums of n positive integers.
You can perform two types of operations on any element of the array any number of times:
If the element is even, divide it by 2.
For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].
If the eleme... | nilq/baby-python | python |
import pandas as pd
import numpy as np
from unittest import TestCase, mock
from unittest.mock import MagicMock, PropertyMock
from gtfs_kit.feed import Feed
from representation.gtfs_metadata import GtfsMetadata
from representation.gtfs_representation import GtfsRepresentation
from usecase.process_stops_count_by_type_for... | nilq/baby-python | python |
from cryptography.utils import CryptographyDeprecationWarning
import warnings
warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning)
from qc_qubosolv.solver import Solver
| nilq/baby-python | python |
from sqlalchemy import create_engine
engine = create_engine('sqlite:///todo.db?check_same_thread=False')
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Date
from datetime import datetime
Base = declarative_base()
class task(Base):
__tablename__ = 'task'
... | nilq/baby-python | python |
n=int(input())
res=""
for i in range(1,n+1):
a,b=map(int, input().split())
if a>=0:
res+="Scenario #"+str(i)+":\n"+str((a+b)*(b-a+1)//2)
elif a<0 and b>=0:
res+="Scenario #"+str(i)+":\n"+str(b*(b+1)//2 + a*(abs(a)+1)//2)
else:
res+="Scenario #"+str(i)+":\n"+str((a+b)*(b-a+1)//2)
... | nilq/baby-python | python |
import torch
import torch.nn as nn
def FocalLoss(logits, labels, inverse_normed_freqs):
labels = labels.type(torch.float32)
probs = torch.sigmoid(logits)
pt = (1 - labels) * (1 - probs) + labels * probs
log_pt = torch.log(pt)
floss = - (1 - pt)**2 * log_pt
floss_weighted = floss * inverse_norm... | nilq/baby-python | python |
import sys
import inspect
import torch
#from torch_geometric.utils import scatter_
from torch_scatter import scatter
special_args = [
'edge_index', 'edge_index_i', 'edge_index_j', 'size', 'size_i', 'size_j'
]
__size_error_msg__ = ('All tensors which should get mapped to the same source '
'or... | nilq/baby-python | python |
from requests import post,get
from requests_oauthlib import OAuth1
from flask import request
from os import path
from json import dumps, loads
from time import sleep
dir_path = path.dirname(path.realpath(__file__))
def read_env(file=".env"):
read_file = open(dir_path + "/" + file, "r")
split_file = [r.strip().... | nilq/baby-python | python |
import gmaps2geojson
writer = gmaps2geojson.Writer()
writer.query("2131 7th Ave, Seattle, WA 98121", "900 Poplar Pl S, Seattle, WA 98144")
writer.query("900 Poplar Pl S, Seattle, WA 98144", "219 Broadway E, Seattle, WA 98102")
writer.save("example.geojson")
| nilq/baby-python | python |
"""Этот модуль запускает работу. Работа должна быть асинхронной, модуль запускает и управляет потоками внутри(?)"""
import asyncio
import time
import random
from ss_server_handler import new_order_handler
from PBM_main import TodaysOrders
from controllers_handler import qr_code_alarm, oven_alarm
from settings ... | nilq/baby-python | python |
import uuid
from datetime import datetime
from pydantic import BaseModel, EmailStr, Field
class UserBase(BaseModel):
id: uuid.UUID = Field(default_factory=uuid.uuid4)
username: str
email: EmailStr
class Config:
arbitrary_types_allowed = True
class UserCreate(UserBase):
register_date: d... | nilq/baby-python | python |
valores = []
for contador in range(0, 5):
valor = int(input('Digite um valor: '))
if contador == 0 or valor > valores[-1]:
valores.append(valor)
print('Adicionado ao final da lista...')
else:
posicao = 0
while posicao < len(valores):
if valor <= valores[posicao]:
... | nilq/baby-python | python |
import os,cStringIO
class Image_Fonts():
def Fonts_Defaults(self):
fontlist = [
'/usr/share/fonts/truetype/freefont/FreeSerif.ttf',
'/usr/share/fonts/truetype/freefont/FreeSans.ttf',
'/usr/share/fonts/truetype/freefont/FreeMono.ttf'
]
fontpath = '.'
... | nilq/baby-python | python |
import itertools
from django.http import HttpRequest, HttpResponse
from django.core.exceptions import PermissionDenied
from django.utils import timezone
from django.utils.text import slugify
from .jalali import Gregorian, datetime_to_str, mounth_number_to_name, en_to_fa_numbers
# create unique slug.
def unique_slug(t... | nilq/baby-python | python |
from hask.lang import build_instance
from hask.lang import sig
from hask.lang import H
from hask.lang import t
from hask.Control.Applicative import Applicative
from hask.Control.Monad import Monad
from .Foldable import Foldable
from .Functor import Functor
class Traversable(Foldable, Functor):
"""
Functors re... | nilq/baby-python | python |
from random import choice
from xkcdpass import xkcd_password
class XKCD:
delimiters_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
delimiters_full = ["!", "$", "%", "^", "&", "*", "-", "_", "+", "=",
":", "|", "~", "?", "/", ".", ";"] + delimiters_numbers
def __init__... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''
Created on : Thursday 18 Jun, 2020 : 00:47:36
Last Modified : Sunday 22 Aug, 2021 : 23:52:53
@author : Adapted by Rishabh Joshi from Original ASAP Pooling Code
Institute : Carnegie Mellon University
'''
import torch
import numpy as np
import torch.nn.functional as F
from torch.nn... | nilq/baby-python | python |
# License: MIT
# Author: Karl Stelzner
import os
import sys
import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import numpy as np
from numpy.random import random_integers
from PIL import Image
from torch.utils.data._utils.collate import default_collate
import json
def progres... | nilq/baby-python | python |
import random
import numpy as np
class Particle():
def __init__(self):
self.position = np.array([(-1) ** (bool(random.getrandbits(1))) * random.random()*50, (-1)**(bool(random.getrandbits(1))) * random.random()*50])
self.pbest_position = self.position
self.pbest_value = float('inf')
... | nilq/baby-python | python |
import sys
import os
import logging
import shutil
import inspect
from . import config
logger = logging.getLogger('carson')
_init = None
_debug = False
def initLogging(debug=False):
global _init, _debug
if _init is not None:
return
_init = True
_debug = debug
formatter = logging.Format... | nilq/baby-python | python |
import sys
from distutils.core import setup
from setuptools import find_packages
version = '0.1.1'
install_requires = [
'acme>=0.29.0',
'certbot>=1.1.0',
'azure-mgmt-resource',
'azure-mgmt-network',
'azure-mgmt-dns>=3.0.0',
'PyOpenSSL>=19.1.0',
'setuptools', # pkg_resources
'zope.int... | nilq/baby-python | python |
import json
import jwt
from fastapi import Depends, HTTPException, Path, Query
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.security.utils import get_authorization_scheme_param
from pydantic import BaseModel
from starlette.requests import Request
from starlette.status import HTTP_... | nilq/baby-python | python |
import time
from itertools import chain
from opentrons import instruments, labware, robot
from opentrons.instruments import pipette_config
def _sleep(seconds):
if not robot.is_simulating():
time.sleep(seconds)
def load_pipettes(protocol_data):
pipettes = protocol_data.get('pipettes', {})
pipette... | nilq/baby-python | python |
#!/usr/bin/python
import sys
def int2bin(num, width):
spec = '{fill}{align}{width}{type}'.format(
fill='0', align='>', width=width, type='b')
return format(num, spec)
def hex2bin(hex, width):
integer = int(hex, 16)
return int2bin(integer, width)
def sendBinary(send):
binary = '# ' + '\t branch targ... | nilq/baby-python | python |
"""tests rio_tiler.sentinel2"""
import os
from unittest.mock import patch
import pytest
import rasterio
from rio_tiler.errors import InvalidBandName
from rio_tiler_pds.errors import InvalidMODISProduct
from rio_tiler_pds.modis.aws import MODISASTRAEAReader
MODIS_AST_BUCKET = os.path.join(
os.path.dirname(__file... | nilq/baby-python | python |
import FWCore.ParameterSet.Config as cms
from RecoTracker.DebugTools.TrackAlgoCompareUtil_cfi import *
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @Time : 2020/1/23 10:10
# @Author : jwh5566
# @Email : jwh5566@aliyun.com
# @File : test1.py
# import sys
# print('参数个数: ', len(sys.argv))
# print('参数列表: ', str(sys.argv))
# a = 10
# if a > 0:
# print(a, "是一个正数")
# print("总是打印这句话")
#
# a = -10
# if a > 0:
# print(a, "是一个正数")
# a = 10... | nilq/baby-python | python |
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.selector import HtmlXPathSelector
from ..items import NewsItem
from datetime import datetime
import pandas as pd
import re
class SabahSpider(CrawlSpider):
name = "sabah"
allowed_domains = ["sabah.c... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayOpenAppXwbsssQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayOpenAppXwbsssQueryResponse, self).__init__()
self._a = None
@prop... | nilq/baby-python | python |
'''
--------------------
standard_parsers.py
--------------------
This module contains a set of commands initializing standard
:py:class:`argparse.ArgumentParser` objects with standard sets of pre-defined
options. The idea here is that I have a standard basic parser with set syntax
but can also have a 'cluster parse... | nilq/baby-python | python |
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
def conv(x, out_channel, kernel_size, stride=1, dilation=1):
x = slim.conv2d(x, out_channel, kernel_size, stride, rate=dilation,activation_fn=None)
return x
def global_avg_pool2D(x):
with tf.variable_scope(None, 'global_pool... | nilq/baby-python | python |
from functools import reduce
from typing import Optional
import numpy as np
def find_common_elements(*indices: np.array) -> np.array:
""" Returns array with unique elements common to *all* indices
or the first index if it's the only one. """
common_elements = reduce(np.intersect1d, indices[1:], indices[0... | nilq/baby-python | python |
from rest_framework import viewsets, mixins
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from core.models import Skill
from core.models import Location
from core.models import Job
# from core.models import Job
from job import serializers
from djang... | nilq/baby-python | python |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='clus']/h2[@class='nomargin title_sp']",
'price' : "//h2[@class='nomargin']/font",
'category' : "//div[@class='head_t... | nilq/baby-python | python |
from extractors import archive_extractor, ertflix_extractor, star_extractor, megatv_extractor
from downloaders import m3u8_downloader, alpha_downloader
import sys
if __name__ == "__main__":
url = sys.argv[1]
if "ertflix.gr" in url:
extractor = ertflix_extractor.ErtflixExtractor(url)
stream_dat... | nilq/baby-python | python |
#!/usr/bin/env python2
# PYTHON_ARGCOMPLETE_OK
import sys
import agoat._config
import agoat.run_disasms
import agoat.indexer
import agoat.diagnostic
import agoat.keywordsearcher
# set up command-line completion, if argcomplete module is installed
try:
import argcomplete
import argparse
parser = argparse... | nilq/baby-python | python |
import os
import math
import pygame
class Lava(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
"""
Create a platform sprite. Note that these platforms are designed to be very wide and not very tall.
It is required that the width is greater than or equal to the heigh... | nilq/baby-python | python |
def pal(a):
s=list(str(a))
i=1
w=[]
while i<=len(s):
w.append(s[-i])
i=i+1
if w==s:
print("it is palimdrom")
else:
print("it is not palimdrom")
string=input("enter the string :")
pal(string)
| nilq/baby-python | python |
from aoc import data
from collections import Counter, defaultdict
parser = int
def part1(inputData, days=80):
fish = Counter(inputData)
for _ in range(days):
newFish = fish.pop(0, 0)
fish = Counter({k-1: v for k, v in fish.items()}) + Counter({6: newFish, 8:newFish})
return sum(fish.values... | nilq/baby-python | python |
#!/usr/local/bin/python3
import sys
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
def getMNISTData():
print("Preparing data ...")
num_classes = 10
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data... | nilq/baby-python | python |
# Collection of supporting functions for wrapper functions
__author__ = 'AndrewAnnex'
from ctypes import c_char_p, c_bool, c_int, c_double, c_char, c_void_p, sizeof, \
POINTER, pointer, Array, create_string_buffer, create_unicode_buffer, cast, Structure, \
CFUNCTYPE, string_at
import numpy
from numpy import ct... | nilq/baby-python | python |
#!/bin/python
if __name__ == "__main__":
from picomc import main
main()
| nilq/baby-python | python |
import datetime
import logging
import json
import os
import socket
from config import Configuration
from io import StringIO
from loggly.handlers import HTTPSHandler as LogglyHandler
class JSONFormatter(logging.Formatter):
hostname = socket.gethostname()
fqdn = socket.getfqdn()
if len(fqdn) > len(hostname)... | nilq/baby-python | python |
from genericpath import exists
import os, sys
from os.path import join
import tempfile
import shutil
import json
try:
curr_path = os.path.dirname(os.path.abspath(__file__))
teedoc_project_path = os.path.abspath(os.path.join(curr_path, "..", "..", ".."))
if os.path.basename(teedoc_project_path) == "teedoc":
... | nilq/baby-python | python |
from .base_settings import *
import os
ALLOWED_HOSTS = ['*']
INSTALLED_APPS += [
'django_prometheus',
'django.contrib.humanize',
'django_user_agents',
'supporttools',
'rc_django',
]
TEMPLATES[0]['OPTIONS']['context_processors'].extend([
'supporttools.context_processors.supportools_globals'
])... | nilq/baby-python | python |
'''
This script loads an already trained CNN and prepares the Qm.f notation for each layer. Weights and activation are considered.
This distribution is used by net_descriptor to build a new prototxt file to finetune the quantized weights and activations
List of functions, for further details see below
- forward_pa... | nilq/baby-python | python |
from timemachines.skatertools.evaluation.evaluators import chunk_to_end
def test_chunk_from_end():
ys = [1,2,3,4,5,6,7,8]
chunks = chunk_to_end(ys,5)
assert len(chunks[0])==5
assert len(chunks)==1
assert chunks[0][0]==4 | nilq/baby-python | python |
from typing import NamedTuple, Optional
class ConnectionProperties(NamedTuple):
origin: str
port: Optional[int]
| nilq/baby-python | python |
"""cli.py - Command line interface related routines"""
import logging
import os
import pathlib
from itertools import chain
import click
import click_logging
from ocdsextensionregistry import ProfileBuilder
from ocdskit.util import detect_format
from spoonbill import FileAnalyzer, FileFlattener
from spoonbill.common i... | nilq/baby-python | python |
# -*- coding: utf-8 -*- #
# Copyright 2018 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 requir... | nilq/baby-python | python |
# CSC486 - Spring 2022
# Author: Dr. Patrick Shepherd
# NOTE: This file contains several functions, some of which already do something
# when run, even before you start writing code. For your convenience, in the
# main function, you may want to comment out the functions you are not currently
# using so they are not r... | nilq/baby-python | python |
import os
from PyQt5.QtCore import QThread, pyqtSignal
from lib.ffmpegRunner import Runner
from lib.logger import Log
class Controller(QThread):
output = pyqtSignal(str)
def __init__(self,):
QThread.__init__(self, parent=None)
self.__runner = None
self.__outputFile = None
def s... | nilq/baby-python | python |
# https://arcade.academy/examples/array_backed_grid_sprites_1.html#array-backed-grid-sprites-1
"""
Array Backed Grid Shown By Sprites
Show how to use a two-dimensional list/array to back the display of a
grid on-screen.
This version syncs the grid to the sprite list in one go using resync_grid_with_sprites.
If Pytho... | nilq/baby-python | python |
from datetime import date
def get_count_of_day(year,month,day):
"""
Function that returns the count of day (since the beginning of the year)
for a given year, month and day
Positional argument:
year -- type = integer
month -- type = integer
day -- type = integer
... | nilq/baby-python | python |
#!/usr/bin/env python3
from gi.repository import Meson
if __name__ == "__main__":
s = Meson.Sample.new("Hello, meson/py!")
s.print_message()
| nilq/baby-python | python |
import os
import sys
import unittest
import numpy as np
from QGrain.algorithms import *
NORMAL_PARAM_COUNT = 2
WEIBULL_PARAM_COUNT = 2
GENERAL_WEIBULL_PARAM_COUNT = 3
# the component number must be positive int value
class TestCheckComponentNumber(unittest.TestCase):
# valid cases
def test_1_to_100(self):
... | nilq/baby-python | python |
# Copyright (C) 2020 University of Oxford
#
# 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 t... | nilq/baby-python | python |
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
#
# SPDX-License-Identifier: MIT
# NOTE: Make sure you've created your secrets.py file before running this example
# https://learn.adafruit.com/adafruit-pyportal/internet-connect#whats-a-secrets-file-17-2
import board
from adafruit_pyporta... | nilq/baby-python | python |
"""
weasyprint.css.descriptors
--------------------------
Validate descriptors used for some at-rules.
"""
import tinycss2
from ...logger import LOGGER
from ..utils import (
InvalidValues, comma_separated_list, get_custom_ident, get_keyword,
get_single_keyword, get_url, remove_whitespace, single... | nilq/baby-python | python |
import numpy as np
import pandas as pd
import os
import h5py
from scipy import io
##########################################################
# author: tecwang
# email: tecwang@139.com
# Inspired by https://blog.csdn.net/zebralxr/article/details/78254192
# detail: Transfer mat file into csv file by python
#############... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Tue May 23 14:40:10 2017
@author: pudutta
"""
from __future__ import absolute_import, division, print_function
import codecs
import glob
import multiprocessing
import os
import pprint
import re
import nltk
import gensim.models.word2vec as w2v
import math
import ... | nilq/baby-python | python |
#!/user/bin python
# -*- coding:utf-8 -*-
'''
@Author: xiaodong
@Email: fuxd@jidongnet.com
@DateTime: 2015-11-08 19:06:43
@Description: 提取word文档信息 转换Excel
需求字段 : 姓名,职位,性别,年龄,教育程度,手机号码,邮箱,户籍,简历更新日期,工作经历,项目经历。
'''
from win32com.client import Dispatch, constants
import os,sys
import re
import chardet... | nilq/baby-python | python |
def my_zip(first,secoud):
first_it=iter(first)
secoud_it=iter(secoud)
while True:
try:
yield (next(first_it),next(secoud_it))
except StopIteration:
return
a=['s','gff x','c']
b=range(15)
m= my_zip(a,b)
for pair in my_zip(a,b):
print(pair)
a,b... | nilq/baby-python | python |
import sqlite3
def changeDb():
databaseFile = "app/database/alunos.db"
escolha = 0
while escolha != 4:
print("""
1 = Numero para contato
2 = Situação escolar
3 = Documentações pendentes
4 = Sair do menu
""")
escolha... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016, 2017 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Li... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.