content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import glob
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setuptools.setup(
name="mldiag",
version="0.0.1",
author="Aymen SHABOU",
author_email="aymen.shabou@gmail.com",
descript... | python |
#!/usr/bin/env python
import roslib
import rospy
import tf
from geometry_msgs.msg import TransformStamped
from posedetection_msgs.msg import ObjectDetection
def handle_pose(msg):
br = tf.TransformBroadcaster()
if len(msg.objects)==0:
return
p = msg.objects[0].pose
br.sendTransform((p.position.... | python |
#!/usr/bin/env python3
#
# Author: Jeremy Compostella <jeremy.compostella@gmail.com>
#
# 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 above copyright
# notic... | python |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
... | python |
"""
Merged String Checker
http://www.codewars.com/kata/54c9fcad28ec4c6e680011aa/train/python
"""
def is_merge(s, part1, part2):
result = list(s)
def findall(part):
pointer = 0
for c in part:
found = False
for i in range(pointer, len(result)):
if result... | python |
import os
import docker.errors
import pandas as pd
import pytest
from ebonite.build.docker import create_docker_client, is_docker_running
from ebonite.core.objects.core import Model
from sklearn.linear_model import LinearRegression
from tests.client.test_func import func
def has_docker():
if os.environ.get('SKI... | python |
from ..value_set import ValueSet
class BmiRatio(ValueSet):
"""
**Clinical Focus:** This value set contains concepts that represent a body mass index (BMI) ratio.
**Data Element Scope:** This value set may use the Quality Data Model (QDM) category or attribute related to Procedure.
**Inclusion Criter... | python |
import os
import json
import tempfile
from model import VepException, VepResult
from bgcore import tsv
from bgcore.request import Request
def _ctype(value):
return value.split(",")
class VepService(object):
HOST = "beta.rest.ensembl.org"
VEP_STRAND = { "+" : "1", "-" : "-1", "1" : "1", "-1" : "-1" }
def __ini... | python |
from ._PlaceBox import *
from ._RemoveBox import *
| python |
"""Implements logic to render and validate web forms for login and user registration."""
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
"""Form for new users to log-in to... | python |
spanish_columns = {
"oer": "oer",
"games": "partidos",
"points_made": "puntos_a_favor",
"total_possessions": "posesiones_totales",
"minutes": "minutos",
"assists": "asistencias",
"steals": "robos",
"turnovers": "perdidas",
"2_point_percentage": "porcentaje_2_puntos",
"2_point_mad... | python |
import decimal
import numbers
import itertools
__all__ = [
'TRUNCATE',
'ROUND',
'DECIMAL_PLACES',
'SIGNIFICANT_DIGITS',
'NO_PADDING',
'PAD_WITH_ZERO',
'decimal_to_precision',
]
# rounding mode
TRUNCATE = 0
ROUND = 1
# digits counting mode
DECIMAL_PLACES = 2
SIGNIFICANT_DIGITS = 3
# padd... | python |
import os
from setuptools import setup
README = """
See the README on `GitHub
<https://github.com/uw-it-aca/uw-restclients-coda>`_.
"""
version_path = 'uw_coda/VERSION'
VERSION = open(os.path.join(os.path.dirname(__file__), version_path)).read()
VERSION = VERSION.replace("\n", "")
# allow setup.py to be run from any... | python |
#!/usr/bin/env pytest
# -*- coding: utf-8 -*-
################################################################################
# Project: OGR NextGIS Web Driver
# Purpose: Tests OGR NGW Driver capabilities
# Author: Dmitry Baryshnikov, polimax@mail.ru
# Language: Python
#############################################... | python |
# Copyright (c) 2016 Rackspace Hosting Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | python |
# coding: utf-8
# pylint: disable=W0201,C0111
from __future__ import division, unicode_literals, print_function
# standard library
import sys
import os.path
import time
import datetime
import traceback
from copy import deepcopy
from collections import OrderedDict
from itertools import cycle
from math import ceil
impor... | python |
#
# Copyright (c) 2010 Testrepository Contributors
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two lic... | python |
import re
import h5py
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from os.path import join,exists
from os import listdir
from paper import paper
def html_reader(input_dir):
"""
read the html file at input_dir, ... | python |
from .experiment import Experiment # noqa: F401
from .trial import Trial # noqa: F401
| python |
import os
import argparse
import imageio
parser = argparse.ArgumentParser()
parser.add_argument('--name', required=True, type=str)
args = parser.parse_args()
for file in sorted(os.listdir(os.path.join('outputs', args.name, 'particles'))):
i = int(file.replace('.bin', ''))
print('frame %d' % i, flush=True)
... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-20 14:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0014_add_indices'),
]
operations = [
migrations.AddIndex(
... | python |
###########################################################
# compare.py -Script that compares any two painting's hex
# hex values for similarity or rank in the
# frequency list and quantifies it with a
# percentage
# Author: Shaedil Dider
###########################################... | python |
from selenium import webdriver
from utils.logging import init_logger
from utils.s3_manager.manage import S3Manager
class SeleniumCrawler:
def __init__(self, base_url, bucket_name, key, head=False):
self.logger = init_logger()
self.bucket_name = bucket_name
self.s3_manager = S3Manager(buc... | python |
from ._accuracy_per_cell_type import accuracy_per_cell_type
from ._cd_ratio import cd_ratio
from ._cumulative_node import cumulative_node
from ._cumulative_node_group import cumulative_node_group
from ._dists_distr import dists_distr
from ._mean_node_per_cell_type import mean_node_per_cell_type
from ._metric_heatmap im... | python |
import socket
class Triton200:
"""
Create an instance of the Triton200 class.
Supported modes: IP
:param str ip_address: The IP address of the Triton 200.
:param int port_number: The associated port number of the Triton 200 (default: 33576)
:param int timeout: How long to wait for... | python |
import random
import itertools
import json
import networkx as nx
import sys, getopt
import dcop_instance as dcop
def generate(G : nx.Graph, dsize = 2, p2=1.0, cost_range=(0, 10), def_cost = 0, int_cost=True, outfile='') :
assert (0.0 < p2 <= 1.0)
agts = {}
vars = {}
doms = {'0': list(range(0, dsize))}
... | python |
#!/usr/bin/python3
"""Explode an LLVM IR dump.
Given a debug dump generated from the -print-debug-all option, split out the
dumps into multiple files, one for each phase/procedure. Example usage:
clang -c -O3 -mllvm -print-before-all mumble.c 1> err.txt 2>&1
rm -rf /tmp/dumps ; mkdir /tmp/dumps
explode-llvm-ir-... | python |
# https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/Corpora_and_Vector_Spaces.ipynb
from gensim import corpora
# This is a tiny corpus of nine documents, each consisting of only a single sentence
documents = ["Human machine interface for lab abc computer applications",
"A survey of u... | python |
# Copyright (c) 2013 by Gilbert Ramirez <gram@alumni.rice.edu>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# Th... | python |
# Author: Deepak Pathak (c) 2016
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# from __future__ import unicode_literals
import numpy as np
from PIL import Image
import time
import argparse
import os
import pyflow
parser = argparse.ArgumentParser(
des... | python |
from rect import Rect
from math import floor
class HashMap(object):
"""
Hashmap is a broad-phase collision detection strategy, which is quick
enough to build each frame.
"""
def __init__(self, cell_size):
self.cell_size = cell_size
self.grid = {}
@classmethod
def from_objec... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
drawmap.py
@Purpose: draw a current map from a hdf mohid or netcdfoutput
@version: 1.0
@python version: 3.9
@author: Pedro Montero
@license: INTECMAR
@requires: matplotlib, numpy, toolkits.basemap
@date 2021/10/13
@history:
"""
import os
from common.readers.read... | python |
a,b=map(int,input().split())
print(-~(a+b)//2) | python |
# script to create relationship classes in a GeMS database
#
# Somebody who uses relationship classes more than I should look at this.
# Particularly, are the Forward and Backward labels named as usefully as possible?
# Are there other issues?
#
# Note that Validate Database script can be used to maintain refere... | python |
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Paint')
self.setWindowIcon(QIcon('Images/Paint.png'))
self.setMaximumSize(860, 720)
self... | python |
# Run detection in real-time setting on a COCO-format dataset
import argparse, json, pickle
from os.path import join, isfile
from time import perf_counter
from tqdm import tqdm
import numpy as np
import torch
from pycocotools.coco import COCO
from mmcv.runner import load_checkpoint
import sys; sys.pa... | python |
import os
import glob
from imageai.Detection.Custom import DetectionModelTrainer
execution_path = os.getcwd()
models_path = os.path.join(execution_path, "doge-identification/models/")
data_path = os.path.join(execution_path, "doge-identification/")
# This will force tensorflow to run on the cpu
os.environ["CUDA_VISIBL... | python |
# This file is part of the CERN Indico plugins.
# Copyright (C) 2014 - 2020 CERN
#
# The CERN Indico plugins are free software; you can redistribute
# them and/or modify them under the terms of the MIT License; see
# the LICENSE file for more details.
from __future__ import unicode_literals
from wtforms.fields import... | python |
"""Error handlers."""
from werkzeug.http import HTTP_STATUS_CODES
from flask import jsonify
from muckr_api.extensions import database
class APIError(Exception):
def __init__(self, status_code, message=None, details=None):
super().__init__()
error = HTTP_STATUS_CODES.get(status_code, "Unknown err... | python |
from django.conf.urls import url
from .views import Dashboard
urlpatterns = [
url(r'^$', Dashboard.as_view()),
]
| python |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... | python |
from typing import List
import msgpack
from pydantic import BaseModel
import ormsgpack
class Member(BaseModel):
id: int
active: bool
class Object(BaseModel):
id: int
name: str
members: List[Member]
objects_as_pydantic = [
Object(
id=i, name=str(i) * 3, members=[Member(id=j, activ... | python |
#!/usr/bin/env python
from breakmywork.application import main
main()
| python |
import inferpy as inf
def test_parameter_in_pmodel():
# test that random variables in pmodel works even if no name has been provided
@inf.probmodel
def model():
inf.Parameter(0)
v = list(model().params.values())[0]
assert v.name.startswith('parameter')
# assert also is_datamodel is fa... | python |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Phase2C11I13_cff import Phase2C11I13
from Configuration.Eras.Modifier_phase2_3DPixels_cff import phase2_3DPixels
from Configuration.Eras.Modifier_phase2_GE0_cff import phase2_GE0
Phase2C11I13T25M9 = cms.ModifierChain(Phase2C11I13, phase2_3DPixels, p... | python |
import numpy as np
class RandomParameters:
"""
Example params are in JSON format:
{
"booster": ["gbtree", "gblinear"],
"objective": ["binary:logistic"],
"eval_metric": ["auc", "logloss"],
"eta": [0.0025, 0.005, 0.0075, 0.01, 0.025, 0.05, 0.075, 0.1]
}
"""
@sta... | python |
import sys,os,pygame
| python |
# Generated by Django 3.0.6 on 2020-05-25 00:02
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL)... | python |
from tests.save_restore_cursor import SaveRestoreCursorTests
import esccmd
from escutil import knownBug
class DECSETTiteInhibitTests(SaveRestoreCursorTests):
def __init__(self):
SaveRestoreCursorTests.__init__(self)
def saveCursor(self):
esccmd.DECSET(esccmd.SaveRestoreCursor)
def restoreCursor(self):
... | python |
from domain.rules import game_loops
connect_game = game_loops.Game_Loops()
''' here we call the game loop function'''
connect_game.connect_four_game()
| python |
from flask import Flask, request, render_template, url_for, send_file
import qrcode
from PIL import Image
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/result', methods=["POST", "GET"])
def result():
if request.method == "POST":
input = request.f... | python |
# python peripherals
import os
import numpy
import random
import queue
from multiprocessing import Process, Queue, cpu_count
# torch
import torch
from torch.utils.data import Dataset
# deep_signature
from deep_signature.data_generation import curve_generation
from deep_signature.data_generation import dataset_generat... | python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
# standard library
# django
from django.contrib import admin
from django.core.urlresolvers import NoReverseMatch
from django.core.urlre... | python |
import pandas as pd
from modules.locale_generator.data import LocaleOutData
from helper.utils.utils import read_sheet_map_file
class LocaleProcessor:
def __init__(self, language_name, english_column_name):
self.language_name = language_name
self.english_column_name = english_column_name
... | python |
from unittest import mock
from bgmi.downloader.deluge import DelugeRPC
from bgmi.website.model import Episode
_token = "token:2334"
@mock.patch("bgmi.config.DELUGE_RPC_PASSWORD", _token)
@mock.patch("bgmi.downloader.deluge.DelugeRPC._call")
def test_init(call):
DelugeRPC(
download_obj=Episode(name="n", ... | python |
'''
a = input("First number")
b = input("Second number")
a = int(a)
b = int(b)
print(a+b)
print(a-b)
print(a*b)
print(a/b)
result = a/b
print(type(result))
print(result)
print(a**2)
'''
# Логические операции
a = True
b = False
# Отрицание
print(not a)
# Логическое И
print(a and b)
# Логическое ИЛИ
print(a or b)
a ... | python |
from mypackage import shazam
shazam() | python |
# query_parser_test.py
# Author: Thomas MINIER - MIT License 2017-2018
import pytest
from query_engine.sage_engine import SageEngine
from query_engine.optimizer.query_parser import parse_query
from database.hdt_file_connector import HDTFileConnector
from tests.utils import DummyDataset
import math
hdtDoc = HDTFileCon... | python |
import sys
import time
from http.client import HTTPSConnection
from typing import List
def main(argv: List[str]):
time.sleep(3)
for i in range(3):
for j in argv:
connection = HTTPSConnection(j)
connection.request('GET', '/')
connection.getresponse().read()
... | python |
# -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# 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 o... | python |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from common.Utilities import execute_command, get_file_extension_list, error_exit
from ast import ASTGenerator, AST
import Mapper
import Finder
import Logger
import Extractor
import Emitter
def merge_var_info(var_expr_map, var_value_map):
Logger.trace(_... | python |
# CONTADOR DE CÉDULAS
value = int(input('Digite o valor a ser sacado: '))
total = value # Pegando o valor a ser sacado
ced = 50 # Começando na cedula de 50
totced = 0 # Total de cedula por valor
while True:
if total >= ced: # Enquanto puder retirar o valor da cedula do valor total
total -= ced # R... | python |
"""
Generate static HTML files for eduid-IdP in all supported languages.
"""
import os
import sys
import six
import pkg_resources
from six.moves import configparser
from jinja2 import Environment, PackageLoader
from babel.support import Translations
__version__ = '0.1'
__copyright__ = 'SUNET'
__organization__ = 'SUN... | python |
import pywikibot
from openpyxl import load_workbook
site = pywikibot.Site()
'''
page = pywikibot.Page(site, u"Project:Sandbox")
text = page.text
#page.text = u"DarijaBot kheddam daba"
page.save(page.text+u"\n\nawwal edit dial DarijaBot")
'''
sandbox = pywikibot.Page(site, 'User:' + site.user() + '/Project:Sandbox'... | python |
import numpy as np
from .agent import Agent
class RandomAgent(Agent):
def __init__(self, actions):
super(RandomAgent, self).__init__(actions)
def act(self, obs):
return np.random.randint(0, self.num_actions)
| python |
from rA9.neurons.LIF import LIF
def LIF_recall(tau, Vth, dt, x, v_current):
model = LIF(tau_m=tau, Vth=Vth, dt=dt)
spike_list, v_current = model.forward(x, v_current=v_current)
return spike_list, v_current
def LIF_backward(tau, Vth, x, spike_list, e_grad, time):
model = LIF(tau_m=tau, Vth=Vth)
... | python |
from meido.libs.yuntongxun.sms import CCP
from celery_tasks.main import app
@app.task(name='send_sms_code')
def send_sms_code(mobile, sms_code):
ccp = CCP()
ccp.send_template_sms(mobile, [sms_code, '5'], 1)
@app.task()
def test_print():
print(2222)
| python |
#!/usr/bin/env python3
def naive_search(l,x):
for i in range(len(l)):
if l[i]==x:
return i
n = int(input())
l = list(range(n))
cnt = 0
for x in range(n):
i = naive_search(l,x)
cnt += 1
print("#query=%d"%cnt)
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains artellapipe-tools-welcome view implementation
"""
from __future__ import print_function, division, absolute_import
import os
import random
from functools import partial
from Qt.QtCore import Qt, QSize, QTimer, QByteArray, QBuffer
from Qt.QtWidge... | python |
from flask_cors import cross_origin
from app.blueprints.base_blueprint import (
Blueprint,
BaseBlueprint,
request,
Security,
Auth,
)
from app.controllers.user_employment_controller import UserEmploymentController
url_prefix = "{}/user_employment_history".format(BaseBlueprint.base_url_prefix)
user_... | python |
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Thread, Message
# Create your tests here.
class ThreadTestCase(TestCase):
def setUp(self):
self.user1 = User.objects.create_user("user1", None, "test1234")
self.user2 = User.objects.create_user("user2", None, "te... | python |
#!/usr/bin/env python
import argparse
import sys
import Tools
from Bio import SeqIO
from Bio import SeqRecord
from Bio import Seq
ap = argparse.ArgumentParser(description="Take an inversion bed file, and print the sequences in inverted format with some flanking part of the genome.")
ap.add_argument("bed", help="Input... | python |
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView
from django.http import JsonResponse
from api.models import Country, City
class CountryView(LoginRequiredMixin, UserPassesTestMixin, ListView):
model = Country
response_class = JsonRespons... | python |
from .triplet_generators import generator_from_neighbour_matrix, \
TripletGenerator, UnsupervisedTripletGenerator, SupervisedTripletGenerator
from .generators import KerasSequence
| python |
import setuptools
with open("./README.md", "r") as f:
description = f.read()
setuptools.setup(
name="blive",
version="0.0.5",
author="cam",
author_email="yulinfeng000@gmail.com",
long_description=description,
long_description_content_type="text/markdown",
url="https://github.com/yulinf... | python |
from .md5_database import MD5DB
from .paper_database import paperDB | python |
import socket
def resolv(hostname):
try:
return socket.gethostbyname(hostname)
except socket.gaierror as e:
raise Exception('Cloud not resolv "%s": %s' % (hostname, e))
class FilterModule(object):
filter_map = {
'resolv': resolv,
}
def filters(self):
return {'res... | python |
import unittest
import mutable_test
class TestRemoveShared(unittest.TestCase):
'''Tests for function duplicates.remove_shared.'''
def test_general_case(self):
'''
Test remove_shared where there are items that appear in both lists,
and items that appear in only one or the other list... | python |
import numpy as np
from .preprocessing import *
from .sequence_alignment import *
class SemAlign(object):
def __init__(self, embeddings_path, kernel_size=1, delimiter=',', verbose=True):
self.lookup = load_embeddings(embeddings_path, delimiter)
self.kernel_size = kernel_size
self.verbose =... | python |
from enum import Enum, auto
class Color(Enum):
BLACK = 0
WHITE = 1
RED = 2
BLUE = 3
# class TestEnum(Enum):
# ONE = 0
# ONE = 1
class TestNewEnum(Enum):
ZERO = auto()
ONE = auto()
TWO = auto()
if __name__ == "__main__":
print(Color.BLACK)
print(Color.BLACK.name)
pri... | python |
# Update the paths according to your environemnt
OPT = "/data/guide/Trident/llvm-2.9-build/bin/opt"
LLVMGCC = "/data/Trident/llvm-gcc4.2-2.9-x86_64-linux/bin/llvm-gcc"
LLVMLINK = "/data/guide/Trident/llvm-2.9-build/bin/llvm-link"
LLVMPASS_FOLDER = "/data/guide/Trident/llvm-2.9-build/lib/"
LLI = "/data/guide/Triden... | python |
def pour(jug1, jug2):
capacityA = 5
capacityB = 7
Measure = 4
print("%d \t %d" % (jug1, jug2))
if jug2 is Measure: # jug2 has "measure" amount of water stop
return
elif jug2 is capacityB:
pour(0, jug1)
elif jug1 != 0 and jug2 is 0:
pour(0, jug1)
... | python |
def isExistingClassification(t):
pass
def getSrcNodeName(dst):
"""
Get the name of the node connected to the argument dst plug.
"""
pass
def getCollectionsRecursive(parent):
pass
def disconnect(src, dst):
pass
def findVolumeShader(shadingEngine, search='False'):
"""
Returns ... | python |
import scanpy as sc
import numpy as np
import pandas as pd
from scdcdm.util import cell_composition_data as ccd
#%%
adata_ref = sc.datasets.pbmc3k_processed() # this is an earlier version of the dataset from the pbmc3k tutorial
print(adata_ref.X.shape)
#%%
cell_counts = adata_ref.obs["louvain"].value_counts()
print... | python |
"""
:type: tuple
:Size: 1.295MB
:Package Requirements: * **sklearn**
Vec-colnames and neighber matrix used in Substitute DECS. See :py:class:`.DCESSubstitute` for detail.
"""
import os
import pickle
from OpenAttack.utils import make_zip_downloader
NAME = "AttackAssist.DCES"
URL = "https://cdn.data.thunlp.org/TAAD... | python |
#coding:utf-8
"""
@file: db_config
@author: lyn
@contact: tonylu716@gmail.com
@python: 3.3
@editor: PyCharm
@create: 2016-11-20 12:18
@description:
sqlalchemy 配置数据库
"""
from JsonConfig import DB_Config
for path in ['.','..']:
try:
db = DB_Config(
json_file_path=
... | python |
import os
import datetime
import dropbox
from app import db
from app.models import SystemLog
from app.enums import LogStatus, LogType
from flask import current_app
def download(dbx, folder, subfolder, name):
"""Download a file.
Return the bytes of the file, or None if it doesn't exist.
"""
path = '/%s/... | python |
NumOfRows = int(input("Enter number of rows: "))
coeffcient = 1
for i in range(1, NumOfRows+1):
for space in range(1, NumOfRows-i+1):
print(" ",end="")
for j in range(0, i):
if j==0 or i==0:
coeffcient = 1
else:
coeffcient = coeffcient * (i - j)//j
print(... | python |
import abc
class ORMDB(abc.ABC):
@abc.abstractmethod
def parse_sql(self, sql_str):
pass
| python |
# -*- coding: utf-8 -*-
"""This python program converts various parts of glowscript from the most
convenient format for modification into the most convenient format for
deployment.
* Take shaders from shaders/*.shader and combine them into lib/glow/shaders.gen.js
* Extract glowscript libraries list from ``untrusted/r... | python |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import argparse
import io
import numpy as np
import os
from PIL import Image
import requests
import time
import yacs
import torch
from poptorch import inferenceModel, Options
from models.detector import Detector
from models.yolov4_p5 import Yolov4P5
from utils.... | python |
from datetime import datetime
import bs4
from bs4 import BeautifulSoup
from django.contrib.auth.models import User
from bookmarks.models import Bookmark, parse_tag_string
from bookmarks.services.tags import get_or_create_tags
def import_netscape_html(html: str, user: User):
soup = BeautifulSoup(html, 'html.pars... | python |
###exercicio 49
n = int(input('digite um numero: '))
for c in range (1, 11):
print (' {} * {} = {}'.format(n, c, n*c))
print ('Fim!!!') | python |
import cv2
import numpy as np
from PyQt5.QtCore import Qt, QObject, pyqtSignal
from PyQt5.QtGui import QImage, QPixmap, QDropEvent
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy
class QMapCommunicate(QObject):
drop_event = pyqtSignal(QDropEvent)
class PsQMapWidget(QWidget):
def __init... | python |
# coding: utf-8
import torch
import torch.nn.functional as F
from helpers.utils import int_type, add_noise_to_imgs
class NumDiffAutoGradFn(torch.autograd.Function):
"""
A custom backward pass for our [s, x, y] vector when using hard attention
grid = torch.Size([16, 32, 32, 2])
grad_output_shape = ... | python |
import os
import shutil
# Create a new dummy store to run tests on
from tests._stores_for_tests import _TestFixStore
# recs = [
# {'fix_id': 'Fix1', 'operands': {'arg1': '1'}, 'ncml': '<NcML1>'},
# {'fix_id': 'Fix2', 'operands': {'arg2': '2'}, 'ncml': '<NcML2>'}
# ]
recs = [
{
"fix_id": "Fix1",
... | python |
import os
import lldb
class ConcurrentLazyFormatter:
def __init__(self, valobj, dict):
self.valobj = lldb.value(valobj)
def get_child_index(self, name):
return 0 # There is only ever one child
def num_children(self):
if self.has_value:
return 1
return 0
def get_child_at_index(self, index):
if inde... | python |
import os
import re
from .models import Photo
def generate_photo(file_path):
photo_path, width, height = image_utils.fit_and_save(file_path)
thumb_path = image_utils.generate_thumbnail(photo_path)
photo_path, thumb_path = (relp(rp(p), PARENT_DIR) for p in (photo_path, thumb_path))
photo = Photo(image_... | python |
# project/users/forms.py
from flask_wtf import Form
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Length, EqualTo, Email
class RegisterForm(Form):
email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)])
password = PasswordField(... | python |
from .libfm import (
RegressionCallback,
ClassificationCallback,
OrderedProbitCallback,
LibFMLikeCallbackBase,
)
| python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.