content stringlengths 5 1.05M |
|---|
# coding: utf-8
"""
SpaCy deep_learning_keras.py solution to Kaggle Toxic Comment challenge
"""
import os
from utils import xprint_init, xprint, load_json, save_json
from framework import (SUMMARY_DIR, Evaluator, set_random_seed, show_auc, set_n_samples,
get_n_samples_str, auc_score_list, show_results)
from clf... |
#!/usr/bin/python3
import os
import subprocess
import docker
import utils
FNULL = open(os.devnull, 'w')
def setup(coin):
os.chdir("../docker-compose")
print("Starting " + f"{coin}_api node...")
sp = subprocess.Popen(["docker-compose", "-f", f"{coin}.yml", "-p", f"{coin}_api", "up", "--build", "-d"],
... |
#!/usr/bin/env python
"""Test classes for clients-related testing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import codecs
import collections
import os
import platform
import subprocess
import tempfile
import types
from grr_response_client import... |
/anaconda/lib/python3.6/tempfile.py |
# vim: fileencoding=utf8
import logging
import re
import amf, amf.utils
from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden
from django.db.models.query import QuerySet
from django.core import exceptions, urlresolvers
class AMFMiddleware(object):
CONTENT_TYPE = '... |
import os
from geckordp.settings import *
import geckordp.settings
# pylint: disable=invalid-name
# check if environment variables are set and override it
VAR_ID = "_Settings__X"
for name, value in GECKORDP.__dict__.items():
# check if correct variable
if (not name.startswith(VAR_ID)):
continue
#... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""PID fetchers for Invenio-OpenDefinition."""
from __future__ import absolute_impor... |
"""models.py - This file contains the class definitions for the Datastore
entities used by the Game."""
from protorpc import messages
from google.appengine.ext import ndb
class User(ndb.Model):
"""User profile"""
name = ndb.StringProperty(required=True)
email = ndb.StringProperty()
wins = ndb.Integer... |
from django.shortcuts import render , get_object_or_404
from .models import Job
# Create your views here.
def home (request):
jobs = Job.objects
return render(request,'jobs/home.html',{'jobs':jobs})
def detail (request, job_id):
job_detail = get_object_or_404(Job, pk = job_id)
return render(request,'... |
import numpy as np
import scipy.stats as stat
from utils import dichotomic_search
""" Implementation of last particle variant """
def ImportanceSplittingLp(gen,kernel,h,tau=0,N=100,s=0.1,decay=0.9,T = 20, accept_ratio = 0.9,
alpha_est = 0.95, alpha_test=0.99,verbose=1, gain_thresh=0.01, check_every=3, p_c = 10**(-2... |
from __future__ import division
import pymol
from pymol import cmd, stored
from pymol.cgo import *
import numpy as np
import time
from utils import get_glyco_bonds_within_chain_and_model, writer
def elapsed(starting, s):
e = time.time() - starting
print(s, e)
return e
def find_rings(resn_list, chain, mode... |
from intercom_test import http_best_matches as subject
from base64 import b64encode
from io import StringIO
import json
from should_dsl import should, should_not
JSON_STR = """[{
"id": 1,
"first_name": "Jeanette",
"last_name": "Penddreth",
"email": "jpenddreth0@census.gov",
"gender": "Female",
"ip_address"... |
import esgfpid.rabbit.rabbit
import logging
import time
import datetime
TESTVALUES_REAL = dict(
url_messaging_service='handle-esgf.dkrz.de',
messaging_exchange='rabbitsender_integration_tests',
exchange_no_queue='rabbitsender_integration_tests_no_queue',
exchange_name='rabbitsender_integration_tests'... |
"""
The challenge: find the first non repeating character in a string
"""
s = "abacabad"
def firstNotRepeatingCharacter(s):
for i in s:
if s.index(i) == s.rindex(i):
return i
return '_'
|
"""
********************************************************************************
* Name: setup.py
* Author: Nathan Swain
* Created On: 2014
* Copyright: (c) Brigham Young University 2014
* License: BSD 2-Clause
********************************************************************************
"""
import os
from setup... |
from .base import CRDT
from .base import Tuple
from .base import mutator
class LWWReg(CRDT):
@classmethod
def initial(cls):
return Tuple((0, None))
@classmethod
def join(cls, s1, s2):
if s1[0] == s2[0] and s2[1] > s1[1]:
return Tuple((s2[0], s2[1]))
return Tuple((s... |
import classyjson # classy-json
import ffmpeg # ffmpeg-python
import numpy # numpy
import time
import math
import os
with open('config.json', 'r') as c:
config = classyjson.load(c)
# reverse gradients
config.gradients[0] = ''.join(reversed([c for c in config.gradients[0]]))
config.gradients[1] = ''.join(revers... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from django.test import TestCase
from ..utils.data import bytes_for_humans
class BytesForHumans(TestCase):
def test_bytes(self):
self.assertEqual("132B", bytes_for_humans(132))
def t... |
from intcode import IntcodeVM
from collections import defaultdict
file = open('input.txt', 'r')
for line in file:
memry = line.split(',')
def addPos(one, two):
return one[0] + two[0], one[1] + two[1]
def positionQueried(direction):
global rob
offset = (0, 0)
if direction == 1:
offset = ... |
from blaze import dshape
from blaze.expr.nodes import Node
from blaze.expr.viz import dump
from blaze.table import NDArray, NDArray
from blaze.datashape.coretypes import float64, dynamic
from blaze.expr.graph import IntNode, FloatNode, App, StringNode
from unittest import skip
# Print out graphviz to the screen
DEB... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# imports.
from fil3s.classes.exceptions import Exceptions
from fil3s.classes.files import *
# pip imports.
from django.http import JsonResponse
import json as pypi_json
import traceback as _traceback_
# the response manager class.
class __Response__(object):
def __ini... |
import os
from fast_align.generate_alignments import generate_word_alignments_fast_align
from mgiza.generate_alignments import generate_word_alignments_mgiza
from SimAlign.generate_alignments import generate_word_alignments_simalign
from awesome.generate_alignments import generate_word_alignments_awesome
from typing im... |
#!/usr/bin/env python3
import pfp
from pfp.utils import binary
from pfp.fuzz import Changer
def test_changeset():
template = """
struct {
ushort a;
ushort b;
ushort c;
ushort d;
uint e;
} data;
"""
data = "aabbccddeeee"
dom ... |
from Crypto.Cipher import AES
from Crypto.Hash import SHA3_256
from Crypto.Random import get_random_bytes as rand
import pathlib
from pwinput import pwinput as getpass
from sys import argv as args
import argparse
from zipfile import ZipFile
from zipfile import Path as ZPath
from io import BytesIO
from tempfile import N... |
from primitives import GameObject
import constants as c
import pygame
import random
class Note(GameObject):
def __init__(self, game, note_key, scene, beat):
super().__init__(game)
self.scene = scene
self.beat = beat
self.note_key = note_key
self.y = self.get_y()
sel... |
from multiprocessing import Process
from proxypool.tester import Tester
from proxypool.db import RedisClient
from proxypool.crawl import Crawler
from proxypool.api import start_api
from time import sleep
from proxypool.settings import *
class Manager(object):
def handle_getter(self):
"""
爬取代理
... |
#!/bin/zsh
# source: youtube.com/watch?v=jBxRGcDmfWA
# source: youtube.com/watch?v=-zd1UI2JTuk
import pyautogui, time
from pynput import keyboard
import sys
text = "Pog"
def on_press(key):
if '{0}'.format(key) == "Key.esc":
sys.exit()
elif '{0}'.format(key) == "Key.enter":
# for word in f:
... |
import matplotlib.pyplot as plt
from collections import namedtuple
import numpy as np
import sys
import os
import seaborn as sns
inputFile = sys.argv[1]
plotsDir = inputFile + "-distribution.png"
weights = []
file = open(inputFile, "r")
for line in file:
weight = int(line)
weights.append(weight)
plt.hist(weights,... |
__all__ = ['split']
def split(splittable, splits=None, index=None):
"""Splits a list into :arg:`jobs` chunks
Args:
splittable (Sequence[T]): A list of any T to be split into
jobs chunks
splits (Union[int, str]): The number of parallel jobs. Default: 1
index (Union[int, str... |
"""Example code for MNIST. A fully-connected network and a convolutional neural network were implemented."""
import runtime_path # isort:skip
import argparse
import gzip
import os
import pickle
import sys
import time
import numpy as np
from core.evaluator import AccEvaluator
from core.layers import Dense
from core... |
from hikcamerabot.services.stream.dvr.service import DvrStreamService
__all__ = [
'DvrStreamService',
]
|
from pathlib import Path
import numpy as np
import nltk
import re
from parse_json import tokenize
from tqdm import tqdm
import constants
import json
def basic_tokenizer(sentence):
words = []
for space_separated_fragment in sentence.strip().split():
words.extend(re.split(" ", space_separated_fragment))
... |
# Copyright 2022 University of New South Wales, Ingham Institute
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applica... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-17 17:44
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... |
# -*- coding: utf-8 -*-
import logging
import datetime
from sqlalchemy import Table, Column, ForeignKey, types
from sqlalchemy.orm import relation
from ckan.model.meta import metadata, mapper
from ckan.model.domain_object import DomainObject
from ckan.model import group
saha_organization_table = None
__all__ = [
... |
from django.test import TestCase
from django.apps import apps
from iee_contact.apps import IEEContactConfig
class IEEContactConfigTestCase(TestCase):
"""
Test app config
"""
def test_apps(self):
self.assertEqual(IEEContactConfig.name, "iee_contact")
self.assertEqual(apps.get_app_conf... |
import datetime as dt
import numpy as np
import pandas as pd
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
engine = create_engine("sqlite:///hawaii.sqlite")
Base = automap_base()
Base.pr... |
## 3. Class Syntax ##
class Car():
def __init__(self):
self.color = "black"
self.make = "honda"
self.model = "accord"
black_honda_accord = Car()
print(black_honda_accord.color)
class Team():
def __init__(self):
self.name = "Tampa Bay Buccaneers"
bucs = Team()
print(bucs.name)... |
def task241(string):
res = ''
for i in range(len(string)):
res += str(ord(string[i]))
return res
def task241_main():
print(
"""
Задание 2 "Строки и списки"
4. Пусть дана строка:
Вариант 1. На основе данной строки сформируйте новую, содержащую только цифры. Выведите новую строку.
... |
"""
Calculate the fuel based on the given mass
"""
def calculate_fuel(mass):
return (mass // 3) - 2
f = open("input.txt", 'r')
total_fuel = 0
for number in f:
total_fuel += calculate_fuel(int(number))
print(total_fuel)
f.close()
|
#!/usr/bin/env python
import numpy
import rospy
import time
import collections
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Imu
from sensor_msgs.msg import NavSatFix
from std_srvs.srv import Trigger
from std_srvs.srv import TriggerResponse
from covariance_calculator ... |
"""CLI for DRSSMS package."""
from drssms import NeverAPI
import click
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@click.group()
def main():
"""Enter main script."""
# napi = NeverAPI()
# TODO: Move napi up here and use context
pass
@main.command()
@... |
import json
import logging
from datetime import date
from typing import Final
import requests
from bs4 import BeautifulSoup
from . import utils
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", level=logging.INFO
)
DAY_INTERVAL: Final = "d"
HOUR_INTERVAL: Final = "h"
FIFTEEN_MIN... |
numero1 = 10
numero2 = 5
numero3 = 9
promedio = (numero1 + numero2 + numero3)/3
print('El promedio de los 3 numeros es: ', promedio)
|
# Generated by Django 2.1.4 on 2018-12-24 16:46
from django.db import migrations, models
import django.db.models.deletion
import photoslib.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('photoslib', '0001_initial'),
]
operations = [
migrations.Create... |
#!/usr/bin/python3
# Project : pyzrtp
# Copyright (C) 2017 Orange
# All rights reserved.
# This software is distributed under the terms and conditions of the 'BSD 3-Clause'
# license which can be found in the file 'LICENSE' in this package distribution.
from Crypto.Cipher import AES
from collections import namedt... |
#!/usr/bin/env python3
"""
An example of testing the cache to prove that it's not making more requests than expected.
"""
import asyncio
from contextlib import asynccontextmanager
from logging import basicConfig, getLogger
from unittest.mock import patch
from aiohttp import ClientSession
from aiohttp_client_cache imp... |
import unittest
from hundo import parse_from_json as parser
class TestParsingFromJson(unittest.TestCase):
def test_smoke(self):
strings = (
'РЭУ, Факультет маркетинга, Менеджмент (38.03.02), ОП [Б], №: 3, №*: 1, №**: 2',
'ВШЭ, ФСН, Политология (41.03.04), ОП [БК], №: 3, №*: 1, №**:... |
import numpy as np
import libsvm.svmutil as libSVM
class LibSVM(object):
def __init__(self,paramsLst):
self.paramsLst = paramsLst
self.svmModel = None
#whether or not to flip the classes
#this is a weird error, but, it seems like the svm doesn't remember the order of the classes
#what this code curre... |
from alpaca_trade_api.entity import Quote
from alpaca_trade_api.rest import Positions
import config
import alpaca_trade_api as tradeapi
import risk
api = tradeapi.REST(config.API_KEY, config.SECRET_KEY, base_url=config.URL)
symbols = ["SPY" , "IWM", "DIA"]
for symbol in symbols:
quote = api.get_last_q... |
from sensor_msgs.msg import Imu
from std_msgs.msg import String
from robotis_controller_msgs.msg import SyncWriteItem
import rospy
class OpenCR(object):
def __init__(self, ns):
self._sub_imu = rospy.Subscriber(ns + "/open_cr/imu", Imu, self._cb_imu, queue_size=10)
self._sub_button = rospy.Subscrib... |
import abc
import math
import numpy as np
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import QObject, pyqtSignal, QPointF, QRectF
from PyQt5.QtGui import QColor, QPalette
from PyQt5.QtWidgets import QGraphicsRectItem, QMenu, QGraphicsSceneContextMenuEvent, QAction, QGraphicsItem, \
QGraphicsEllips... |
"""
A query on a dictionary.
:Author: Maded Batara III
:Author: Jose Enrico Salinas
:Version: v20181020
"""
from collections import Counter, defaultdict
from functools import reduce
from operator import or_ as union
import random
class DictionaryQuery:
"""A query from a dictionary.
The Dictionary... |
# --
# Copyright (c) 2008-2021 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
# --
"""Sessions managed in memory
These sessions managers keep:
- the last recently used ``DEFAUL... |
#!/usr/bin/env python
"""
Example:
$ ./main.py --choices 10 --list host1 host2 host3 host4 host5 --number 4
['host1', 'host2', 'host3', 'host4']
['host1', 'host2', 'host3', 'host5']
['host1', 'host2', 'host4', 'host5']
['host1', 'host3', 'host4', 'host5']
['host2', 'host3', 'host4', 'host5']
... |
import json
import logging
import os
import pickle
from collections import namedtuple
import torch
from consts import SPEAKER_START, SPEAKER_END, NULL_ID_FOR_COREF
from utils import flatten_list_of_lists
from torch.utils.data import Dataset
# CorefExample = namedtuple("CorefExample", ["token_ids", "clusters"])
Bart... |
# Copyright 2021 The Bellman Contributors
#
# 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... |
import pstats
import cProfile
import pyximport
pyximport.install()
import app
cProfile.runctx("app.analyze_movie('movie/testa.mp4')", globals(), locals(), "Profile.prof")
s = pstats.Stats("Profile.prof")
s.strip_dirs().sort_stats("time").print_stats() |
"""position.py
This scripts will extract atoms position from OUTCAR file from VASP calculation.
Examples of information that we need to extract from Ni100_Clean_rel:
POSITION TOTAL-FORCE (eV/Angst)
---------------------------------------------------------------------------------... |
import PySimpleGUI as sg
# Very basic form. Return values as a list
window = sg.FlexForm('OCR Unicode') # begin with a blank form
layout = [
[sg.Text('Please enter the folder path')],
[sg.Text('Folder Path', size=(15, 1))],
[sg.InputText()],
[sg.Checkbox('Split pdf_pages int... |
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib import cm
class BodyMap:
def __init__(self):
im_link = 'https://raw.githubusercontent.com/MuteJester/MediPlot/master/MediPlot/Body_Sil.png'
self.body_sil = plt.imread(im_link)
... |
#!/usr/bin/env python3
import sys
import json
import random
import termcolor
import requests
from graphqlclient import GraphQLClient
from collections import namedtuple
from urllib.error import URLError
__server_description_fields = [
'uri', 'alias', 'status',
'uuid', 'message', 'replicaset'
]
ServerDescript... |
# Copyright 2013 IBM Corp.
#
# 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, so... |
import os, sys, numpy as np, argparse, imp, datetime, time, pickle as pkl, random, json, collections
import matplotlib
import matplotlib.pyplot as plt
from tqdm import tqdm
import torch, torch.nn as nn
#Custom Libraries
import datasets as data
import netlib as netlib
import auxiliaries as aux
"""===================... |
import yaml
import os
import numpy as np
import gym
import matplotlib.pyplot as plt
from quanser_robots.cartpole.ctrl import SwingUpCtrl, MouseCtrl
from quanser_robots.common import GentlyTerminating, Logger
def load_config(config_path="config.yml"):
'''Load the configuration setting from a given path'''
if ... |
import time
class Timer(object):
def __init__(self, print_fnc=print):
self._last_ts = time.time()
self._print = print_fnc
def step(self, message, reset=True):
time_spent = time.time() - self._last_ts
self._print('[{:5}] {}'.format(time_spent, message))
if reset:
... |
import pytest
from llckbdm.min_rmse_kbdm import min_rmse_kbdm
def test_min_rmse_kbdm(data_brain_sim, dwell):
# because the number of points used to compute KBDM, only third element is capable of reproduce a good result
m_range = [30, 31, 180, 32, 33, 34]
l = 30
min_rmse_results = min_rmse_kbdm(
... |
import unittest
from zserio.bitbuffer import BitBuffer
from zserio.bitreader import BitStreamReader
from zserio.bitsizeof import INT64_MIN
from zserio.exception import PythonRuntimeException
class BitStreamReaderTest(unittest.TestCase):
def testFromBitBuffer(self):
bitBuffer = BitBuffer(bytes([0x0B, 0xAB... |
import time
import csv
import os
from threading import Timer
from NavigationCenter.RobotStatus import RobotStatus
from datetime import datetime
from threading import Timer
from collections import defaultdict
from heapq import *
from Queue import *
class NaviCenter:
def __init__(self,naviFilePath):
fileP... |
class CountingBits:
"""
https://leetcode-cn.com/problems/counting-bits/
"""
def countBits(self, num: int) -> List[int]:
|
"""Unit tests for the scene-optimizer class.
Authors: Ayush Baid
"""
import unittest
from pathlib import Path
import dask
import hydra
import numpy as np
from dask.distributed import LocalCluster, Client
from gtsam import EssentialMatrix, Rot3, Unit3
from hydra.utils import instantiate
import gtsfm.utils.geometry_co... |
'''
A quick edit to text_classifier.py.
bootstrap_classifier is used for the paragraph bootstrap project.
added the function: run_model_on_train_test_split
input:
X_train, X_test, y_train, y_test, output_filename, user_id, project_id,
label_id=None, method='bow', run_on_entire_dataset=False)
return:
result, clf
'''
im... |
# This code is referenced from https://github.com/VainF/pytorch-msssim/blob/master/pytorch_msssim/ssim.py
import torch
import torch.nn.functional as F
def _fspecial_gauss_1d(size, sigma):
r"""Create 1-D gauss kernel
Args:
size (int): the size of gauss kernel
sigma (float): sigma o... |
from __future__ import annotations
from typing import List, Union, Optional, TYPE_CHECKING
import pandas as pd
from ..parsers import CoreScript, WranglingScript
if TYPE_CHECKING:
from ..models import ModifierModel, FieldModel, SchemaActionModel, ColumnModel
class BaseSchemaAction:
"""Actions inherit from th... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... |
#coding=utf-8
import sys
sys.path.append("../configs")
sys.path.append("configs")
import settings
import happybase
import json
import logging
pool = happybase.ConnectionPool(size=settings.hbase_pool_size, \
host=settings.hbase_host, \
table_prefix=settings.hbase_table_prefix,\
protocol='compact... |
# -*- coding: utf-8 -*-
from abc import abstractmethod, ABC
from typing import Any
class IMqttMessageListener(ABC):
@abstractmethod
def on_message(self, topic: str, message: Any, packet: Any):
pass
|
"""
Run the application using Flask's simple webserver via
python runserver.py
command. Default port is 8000. To set the port indicate it via --port argument
python runserver.py --port 5000
"""
import argparse
from factory import create_app
if __name__ == "__main__":
parser = argparse.ArgumentParser()
pars... |
from keras.layers import LSTM, Embedding, TimeDistributed, Concatenate, Add
from keras.layers import Dropout, Bidirectional, Dense
from keras.models import Model, Input
from keras.metrics import CategoricalAccuracy
from keras.losses import CategoricalCrossentropy
from model.AttentionText.attention_text import CharTagAt... |
#-*- coding: utf-8 -*-
"""
@author:Bengali.AI
"""
from __future__ import print_function
from .normalizer import Normalizer |
# Generated by Django 3.1.1 on 2020-10-07 22:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('example', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ProfileAttachment',
... |
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key = lambda x: x[1]); units = 0
while truckSize > 0 and boxTypes:
curr = boxTypes.pop(-1)
while curr[0] > 0 and truckSize > 0:
units += curr[1]
... |
#lab5-1
#섭씨 -> 화씨, 화씨-> 섭씨
#함수를 이용해서 구하기
def celtofah(cel):
fah = (9.0 / 5.0) * cel + 32
return fah
def fahtocel(fah):
cel = (5.0 / 9.0) * (fah - 32)
return cel
cel = 40.0
fah = 120.0
print('Celsius'+10*' '+ 'Fahrenheit')
for i in range(0,10): #40도부터 30도까지
print(cel , 10 * ' ', celtofah(cel))
cel -= 1.0
print('... |
# -*- coding: utf-8 -*-
from openprocurement.tender.core.utils import optendersresource
from openprocurement.tender.openua.views.cancellation import TenderUaCancellationResource
from openprocurement.tender.openeu.utils import cancel_tender
@optendersresource(
name="aboveThresholdEU:Tender Cancellations",
coll... |
import logging
import os
import io
from unittest import mock
from django.test import TestCase, tag
from django.contrib.auth.models import User
from django.conf import settings
from feeds.models import Feed
from plugins.models import Plugin
from plugins.models import ComputeResource
from plugins.models import PluginP... |
import traceback
from datetime import timedelta
import pytz
import pendulum
import pandas as pd
from dagster import (
solid,
pipeline,
ModeDefinition,
Output,
OutputDefinition,
)
from repositories.capturas.resources import (
keepalive_key,
timezone_config,
discord_webhook,
)
from repos... |
import KratosMultiphysics
import KratosMultiphysics.ConstitutiveModelsApplication
import MainMaterial
#MainMaterial.Solution("shear_traction_parameters.json","isochoric_ogden_materials.json").Run()
#MainMaterial.Solution("shear_traction_parameters.json","ogden_materials.json").Run()
#MainMaterial.Solution("shear_tract... |
"""Tests for distutils.dist."""
import distutils.cmd
import distutils.dist
import os
import shutil
import sys
import tempfile
import unittest
from test.test_support import TESTFN
class test_dist(distutils.cmd.Command):
"""Sample distutils extension command."""
user_options = [
("sample-option=", "S... |
"""Generated message classes for config version v1alpha1.
"""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.protorpclite import messages as _messages
from apitools.base.py import encoding
from apitools.base.py import extra_types
packa... |
"""
n个数字的无重复排列
使用标志列表判重
使用函数
"""
def perm(i,n):
global count
for a[i] in range(1, n + 1):
if flags[a[i]] == 1:
continue
flags[a[i]] = 1
if i == n:
count += 1
print(a[1:n + 1])
else:
perm(i+1,n)
flags[a[i]] = 0
n=int(inp... |
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: LicenseRef-.amazon.com.-AmznSL-1.0
# Licensed under the Amazon Software License http://aws.amazon.com/asl/
import ffmpeg
import re
from collections import namedtuple
silence_start_re = re.compile(r' silence_start: (?... |
import cv2
image = cv2.imread('media/Leaves.jpg')
height, width, channels = image.shape
M = cv2.getRotationMatrix2D((width/2,height/2),90,1)
dst = cv2.warpAffine(image,M,(width,height))
cv2.imshow('Image', dst)
cv2.waitKey(0)
cv2.destroyAllWindows() |
import functools
from anillo.utils.common import merge_dicts
from urllib.parse import parse_qs
from cgi import parse_header
def wrap_form_params(func):
"""
A middleware that parses the url-encoded body and attach
the result to the request `form_params` attribute.
This middleware also merges the pars... |
from flask import Flask
from observatory.instance import SPACE_API
from observatory.lib.cli import BP_CLI
from observatory.rest.charts import BP_REST_CHARTS
from observatory.rest.mapper import BP_REST_MAPPER
from observatory.rest.owners import BP_REST_OWNERS
from observatory.rest.prompt import BP_REST_PROMPT
from obse... |
"""GameModel exceptions."""
class GameModelError(Exception):
def __init__(self, message: str):
self.message = message
class InvalidPlayer(GameModelError):
pass
class InvalidSpace(GameModelError):
pass
|
from yaetos.etl_utils import ETL_Base, Commandliner, Cred_Ops_Dispatcher, pdf_to_sdf
from yaetos.db_utils import pdf_to_sdf
from libs.python_db_connectors.query_oracle import query as query_oracle
from sqlalchemy import types
class Job(ETL_Base):
OUTPUT_TYPES = {
'session_id': types.VARCHAR(16),
... |
numero = int(input('Insira um número inteiro para obter a tabuada: '))
print('='*12)
contador = 1
for contador in range(1, 11):
print('{} x {} = {}'.format(numero, contador, numero * contador))
contador += 1
print('='*12)
|
import sqlite3
def _seconds_to_str(seconds) -> str:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return '%02d:%02d:%02d' % (h, m, s)
def check_if_stop_exists(db_filepath, stop_id) -> bool:
db_connection = sqlite3.connect(db_filepath)
cursor = db_connection.cursor()
cursor.execute('''selec... |
import os
import cv2
import numpy as np
import scipy
from PIL import Image, ImageFont, ImageDraw, ImageStat
from torchvision import transforms as transforms
def get_rows_cols_no_size(no, width, height):
answers = {}
for x in range(100):
for y in range(100):
if x * y == no:
... |
from flask import request, render_template, session
class SSDP_HTML():
endpoints = ["/ssdp", "/ssdp.html"]
endpoint_name = "page_ssdp_html"
endpoint_access_level = 1
endpoint_category = "tool_pages"
pretty_name = "SSDP"
def __init__(self, fhdhr):
self.fhdhr = fhdhr
def __call__(s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.