Example #1
0
def graph_stints(player_stints, team_abbr, save_path):
    # graph this as rotation chart
    fig, ax = plt.subplots(figsize=(11, 12))

    y_ticks = []
    y_labels = []

    for index, player in enumerate(player_stints, start=1):
        y_ax = (200 + 10 - (10 * index), 9)
        y_ticks.append(200 + 10 - (10 * index) + 5)
        y_labels.append(player['player_name'])

        bar_colors = []
        for stint, plus_minus in zip(player['stints'], player['plus_minus']):
            data = [stint[0], stint[1]]

            for qtr_time in [12, 24, 36, 48]:
                if data[0] <= qtr_time:
                    start = 12 * (qtr_time / 12) - data[0]
                    break

            for qtr_time in [12, 24, 36, 48]:
                if data[1] + data[0] <= qtr_time:
                    end = 12 * (qtr_time / 12) - (data[1] + data[0])
                    break
            if data[1] <= 48:
                start_sec = math.ceil((start - math.floor(start)) * 60)
                end_sec = math.ceil((end - math.floor(end)) * 60)

                start_text = f"{math.floor(start)}:{start_sec:02d}"
                end_text = f"{math.floor(end)}:{end_sec:02d}"

                ax.annotate(start_text,
                            xy=(stint[0], y_ax[0] + 7), xycoords='data',
                            xytext=(stint[0], y_ax[0] + 7), textcoords='data')
                ax.annotate(end_text,
                            xy=(stint[0] + stint[1], y_ax[0] + 1.5), xycoords='data',
                            xytext=(stint[0] + stint[1], y_ax[0] + 1.5), textcoords='data')

                if plus_minus > 0:
                    plus_minus = f"+{plus_minus}"
                    bar_colors.append('green')
                elif plus_minus == 0:
                    bar_colors.append('gray')
                else:
                    bar_colors.append('red')

                ax.annotate(plus_minus,
                            xy=((2 * stint[0] + stint[1]) / 2, y_ax[0] + 4.25), xycoords='data',
                            xytext=((2 * stint[0] + stint[1]) / 2, y_ax[0] + 4.25), textcoords='data')

        ax.broken_barh(player['stints'], y_ax, color=bar_colors)

    ax.set_yticks(y_ticks)
    ax.set_yticklabels(y_labels)
    ax.axhline(y=160, color='black')

    x_ticks = [12, 24, 36, 48]
    x_labels = ['End 1', 'Half', 'End 3', 'End 4']
    ax.set_xticks(x_ticks)
    ax.set_xticklabels(x_labels)

    for tick in x_ticks:
        ax.axvline(x=tick, color='black')

    plt.title(f"{team_abbr} Rotation", loc='left')
    save_path = f"{save_path}/{team_abbr}rotation.png"
    AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY')
    AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_KEY')
    AWS_BUCKET_NAME = os.environ.get('AWS_BUCKET_NAME')
    # save in a buffer object and upload to S3
    buffer = BytesIO()
    fig.savefig(buffer, format='png')
    buffer.seek(0)
    image_png = buffer.getvalue()
    buffer.close()
    plt.close("all")

    s3 = boto3.resource('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
    s3.Bucket(AWS_BUCKET_NAME).put_object(Key=save_path, Body=image_png)

    return save_path
Example #2
0
                "block_num": row[2],
                "par_num": row[3],
                "line_num": row[4],
                "word_num": row[5],
                "left": row[6],
                "top": row[7],
                "width": row[8],
                "height": row[9]
            }

            if ocr_key in ocr_json:
                ocr_json[ocr_key].append(ocr_value)
            else:
                ocr_json[ocr_key] = [ocr_value]

        image_buffer = BytesIO()
        image_reader.save(image_buffer, format="JPEG")
        image_str = base64.b64encode(image_buffer.getvalue())

        mongo_row = {
            'image_name': output_image,
            'image_file': image_str,
            'ocr_text': ocr_text.encode('utf-8', 'strict'),
            'ocr_data': ocr_json
        }

        # print(mongo_row)
        mongo_row_id = collection.insert_one(mongo_row).inserted_id

        # print(row_id)
Example #3
0
 def encode(self, include_path=True):
     port = BytesIO()
     self.write(port, include_path)
     return port.getvalue()
Example #4
0
def parameter(dims=None,
              name=None,
              learning_rate_multiplier=1.0,
              init='uniform',
              init_value_scale=1,
              value=0,
              init_from_file_path='',
              init_from_literal=None,
              random_seed=-1):
    '''
    creates a parameter tensor node.
    '''

    # FIXME We need to better manage the context. How can we get hold
    # of the overall context without having to always pass it
    # explicitly?

    # if the parameter is initialized from a literal value
    if (init == 'fromLiteral'):
        """
        To be as generic as possible, we 
         - flatten the data 
         - initialize a ParameterTensor operator with it
         - ensure that the graph does not backprob to it.  
         - Finally we to reshape it.
        """

        value = init_from_literal

        if not (np.isscalar(value) or is_tensor(value)):
            raise ValueError('value type is not supported: %s' % type(value))

        if isinstance(value, list) or np.isscalar(value):
            value = np.asarray(value)

        if sparse.issparse(value):
            raise ValueError('only dense data is supported')

        param_shape = value.shape if value.shape else (1, )
        literal_shape = (param_shape[0], np.multiply.reduce(param_shape[1:]))

        literal_array = np.reshape(value, literal_shape)

        from io import BytesIO
        s = BytesIO()
        np.savetxt(s, literal_array, '%.4f')

        return cntk1_ops.ParameterTensor(
            dims=param_shape,
            learningRateMultiplier=learning_rate_multiplier,
            init='fromLiteral',
            initFromLiteral=s.getvalue().decode())

    return cntk1_ops.ParameterTensor(dims,
                                     learning_rate_multiplier,
                                     init,
                                     init_value_scale,
                                     value,
                                     init_from_file_path,
                                     randomSeed=random_seed,
                                     var_name=name)
 def test_verify_input(self):
     raw_tx = bytes.fromhex('0100000001813f79011acb80925dfe69b3def355fe914bd1d96a3f5f71bf8303c6a989c7d1000000006b483045022100ed81ff192e75a3fd2304004dcadb746fa5e24c5031ccfcf21320b0277457c98f02207a986d955c6e0cb35d446a89d3f56100f4d7f67801c31967743a9c8e10615bed01210349fc4e631e3624a545de3f89f5d8684c7b8138bd94bdd531d2e213bf016b278afeffffff02a135ef01000000001976a914bc3b654dca7e56b04dca18f2566cdaf02e8d9ada88ac99c39800000000001976a9141c4bc762dd5423e332166702cb75f40df79fea1288ac19430600')
     stream = BytesIO(raw_tx)
     tx = Tx.parse(stream)
     self.assertTrue(tx.verify_input(0))
Example #6
0
def txFromHex(hexstring):
    tx = CTransaction()
    f = BytesIO(hex_str_to_bytes(hexstring))
    tx.deserialize(f)
    return tx
Example #7
0
 def test_compress(self):
     raw = b"test"
     compressed = publisher.gzip_compress(raw)
     decompressed = gzip.GzipFile(fileobj=BytesIO(compressed)).read()
     self.assertEqual(raw, decompressed)
Example #8
0
            "//button[contains(text(),'View entire discussion')]").click()
    except:
        print('Already accepted cookies')

    scrollToBottom()

    time.sleep(1)
    print('Taking Screenshots')
    post.comments.replace_more(limit=0)
    post.comment_sort = config['reddit']['filterBy']
    charCount = 0

    j = 0
    element = driver.find_element_by_id('t3_' + id)
    screenshot = element.screenshot_as_png
    image = Image.open(BytesIO(screenshot))
    image.save('images/' + str(j) + '.png')
    audioTimes.append(createVoice(post.title, 'voices/' + str(j) + '.wav'))
    j += 1

    audioTimeTotal = 0

    for comment in post.comments:
        if isinstance(comment, MoreComments):
            break

        if comment.stickied:
            continue

        if config['reddit']['maxCharacterComment'] < len(comment.body):
            continue
Example #9
0
    async def facebook(self, ctx, *, resp=None):
        """Comando totalmente demente de facebook
        Use ash facebook <mensagem desejada>"""
        if resp is None:
            return await ctx.send(
                '<:alert:739251822920728708>│``DIGITE ALGO PARA EU POSTAR``')

        rede = [[20, (89, 74)], [(218, 166), (91, 128)],
                [['', (90, 93), 9], ['', (112, 74), 7],
                 ['Agora', (112, 81), 7]], 42, 2]

        msg = await ctx.send(
            '<a:loading:520418506567843860>│``Processando...``')

        cont = 0
        list_ = resp.split()
        resp = ''
        for c in list_:
            if len(c) + cont >= rede[3]:
                cont = 0
                resp = '{}{}{}'.format(resp, '''
''', c)
                if len(c) > rede[3]:
                    resp = ' {}-{} {}'.format(c[:rede[3]], '''
''', c[rede[3]:])
                    cont = len(c) - rede[3]
            else:
                resp = '{} {}'.format(resp, c)
                cont += len(c)
        if resp.count('''
''') > rede[4]:
            await ctx.send(
                '<:alert:739251822920728708>│``Sua mensagem foi muito grande!``'
            )
        else:
            avatar = await get_avatar(ctx.author.avatar_url_as(format="png"),
                                      rede[0][0], rede[0][0])

            imgurl = random.choice([
                'https://i.imgur.com/2Owhe1y.jpg',
                'https://i.imgur.com/pFuPCUE.jpg',
                'https://i.imgur.com/0lnhQR9.jpg',
                'https://i.imgur.com/mbigFXD.jpg',
                'https://i.imgur.com/SL0AZr3.jpg',
                'https://i.imgur.com/vj6hIvx.jpg',
                'https://i.imgur.com/wMjySPZ.png',
                'https://i.imgur.com/GCrHCm4.jpg',
                'https://i.imgur.com/caVly1I.jpg',
                'https://i.imgur.com/DI3MnVF.jpg',
                'https://i.imgur.com/I1oFR7s.jpg',
                'https://i.imgur.com/i1TjXts.jpg',
                'https://i.imgur.com/IVzCAgX.jpg',
                'https://i.imgur.com/AgX0ebq.jpg',
                'https://i.imgur.com/ZxUEnnm.jpg',
                'https://i.imgur.com/a34fK0P.jpg',
                'https://i.imgur.com/JdufgXh.jpg',
                'https://i.imgur.com/4bUx6IE.jpg',
                'https://i.imgur.com/VXxGrIT.jpg',
                'https://i.imgur.com/Kn1yIcC.jpg',
                'https://i.imgur.com/YllNI2J.jpg',
                'https://i.imgur.com/HI6Qmig.jpg',
                'https://i.imgur.com/Nmnx7E8.jpg',
                'https://i.imgur.com/A9ZvUzz.jpg',
                'https://i.imgur.com/mSPiRMA.jpg',
                'https://i.imgur.com/EQV5IS3.jpg',
                'https://i.imgur.com/sY76YYa.jpg',
                'https://i.imgur.com/jGtn5Q2.jpg',
                'https://i.imgur.com/ncgHAFi.jpg',
                'https://i.imgur.com/U4UW8Tn.jpg',
                'https://i.imgur.com/YpK2xua.jpg',
                'https://i.imgur.com/r5ttJuB.jpg',
                'https://i.imgur.com/8wbwwV9.jpg',
                'https://i.imgur.com/zRc0LtN.jpg',
                'https://i.imgur.com/Q5USYEZ.png',
                'https://i.imgur.com/XVhh7oO.jpg',
                'https://i.imgur.com/vm109nQ.jpg',
                'https://i.imgur.com/yMH2IN0.png',
                'https://i.imgur.com/6UT2wFZ.jpg',
                'https://i.imgur.com/yjSl9fs.jpg',
                'https://i.imgur.com/OkSXZst.jpg',
                'https://i.imgur.com/Wuad8Zw.jpg',
                'https://i.imgur.com/crBWwqo.jpg',
                'https://i.imgur.com/QGBSogM.jpg',
                'https://i.imgur.com/IKSvnoK.jpg',
                'https://i.imgur.com/MNHiUjf.jpg',
                'https://i.imgur.com/TpOtHY6.png',
                'https://i.imgur.com/mBsvITd.jpg',
                'https://i.imgur.com/69PudmI.jpg',
                'https://i.imgur.com/Le1XrNv.jpg',
                'https://i.imgur.com/I2eCtiW.jpg'
            ])

            imgurl = requests.get(imgurl)
            img = Image.open(BytesIO(imgurl.content)).convert('RGBA')
            img = img.resize(rede[1][0])
            big_img = (img.size[0] * 3, img.size[1] * 3)
            mascara = Image.new('L', big_img, 0)
            trim = ImageDraw.Draw(mascara)
            trim.rectangle((0, 0) + big_img, fill=255)  # opacidade
            mascara = mascara.resize(img.size, Image.ANTIALIAS)
            img.putalpha(mascara)
            exit_img = ImageOps.fit(img, mascara.size, centering=(0.5, 0.5))
            exit_img.putalpha(mascara)
            img = exit_img

            um = rede[2][0][0]
            dois = rede[2][1][0]
            tres = rede[2][2][0]
            if rede[2][0][0] == '':
                rede[2][0][0] = resp
            if rede[2][1][0] == '':
                rede[2][1][0] = ctx.author
            if rede[2][2][0] == '':
                rede[2][2][0] = '@{}'.format(ctx.author)

            image = Image.open('images/social/facebook.png').convert('RGBA')
            escrita = ImageDraw.Draw(image)
            for c in (rede[2]):
                font = ImageFont.truetype('fonts/arial.ttf', c[2])
                texto = str(c[0])
                escrita.text(xy=c[1], text=texto, fill=(10, 10, 10), font=font)
            image.paste(avatar, rede[0][1], avatar)
            image.paste(img, rede[1][1], img)
            image.save('facesbook.png')
            await ctx.send(file=discord.File('facesbook.png'))
            await msg.delete()
            rede[2][0][0] = um
            rede[2][1][0] = dois
            rede[2][2][0] = tres
Example #10
0
 def __init__(self, file):
     self._fd = file.fileno()
     self.buffer = BytesIO()
     self.writable = "x" in file.mode or "r" not in file.mode
     self.write = self.buffer.write if self.writable else None
Example #11
0
    def doit(num_ins, num_outs, M, keys, fee=10000,
                outvals=None, segwit_in=False, outstyles=['p2pkh'], change_outputs=[],
                incl_xpubs=False):
        psbt = BasicPSBT()
        txn = Tx(2,[],[])

        if incl_xpubs:
            # add global header with XPUB's
            # - assumes BIP45
            for xfp, m, sk in keys:
                kk = pack('<II', xfp, 45|0x80000000)
                psbt.xpubs.append( (sk.serialize(as_private=False), kk) )

        psbt.inputs = [BasicPSBTInput(idx=i) for i in range(num_ins)]
        psbt.outputs = [BasicPSBTOutput(idx=i) for i in range(num_outs)]

        for i in range(num_ins):
            # make a fake txn to supply each of the inputs
            # - each input is 1BTC

            # addr where the fake money will be stored.
            addr, scriptPubKey, script, details = make_ms_address(M, keys, idx=i)

            # lots of supporting details needed for p2sh inputs
            if segwit_in:
                psbt.inputs[i].witness_script = script
            else:
                psbt.inputs[i].redeem_script = script

            for pubkey, xfp_path in details:
                psbt.inputs[i].bip32_paths[pubkey] = b''.join(pack('<I', j) for j in xfp_path)

            # UTXO that provides the funding for to-be-signed txn
            supply = Tx(2,[TxIn(pack('4Q', 0xdead, 0xbeef, 0, 0), 73)],[])

            supply.txs_out.append(TxOut(1E8, scriptPubKey))

            with BytesIO() as fd:
                if not segwit_in:
                    supply.stream(fd)
                    psbt.inputs[i].utxo = fd.getvalue()
                else:
                    supply.txs_out[-1].stream(fd)
                    psbt.inputs[i].witness_utxo = fd.getvalue()

            spendable = TxIn(supply.hash(), 0)
            txn.txs_in.append(spendable)


        for i in range(num_outs):
            # random P2PKH
            if not outstyles:
                style = ADDR_STYLES[i % len(ADDR_STYLES)]
            else:
                style = outstyles[i % len(outstyles)]

            if i in change_outputs:
                addr, scriptPubKey, scr, details = \
                    make_ms_address(M, keys, idx=i, addr_fmt=unmap_addr_fmt[style])

                for pubkey, xfp_path in details:
                    psbt.outputs[i].bip32_paths[pubkey] = b''.join(pack('<I', j) for j in xfp_path)

                if 'w' in style:
                    psbt.outputs[i].witness_script = scr
                    if style.endswith('p2sh'):
                        psbt.outputs[i].redeem_script = b'\0\x20' + sha256(scr).digest()
                elif style.endswith('sh'):
                    psbt.outputs[i].redeem_script = scr
            else:
                scr = fake_dest_addr(style)

            assert scr

            if not outvals:
                h = TxOut(round(((1E8*num_ins)-fee) / num_outs, 4), scriptPubKey)
            else:
                h = TxOut(outvals[i], scriptPubKey)

            txn.txs_out.append(h)

        with BytesIO() as b:
            txn.stream(b)
            psbt.txn = b.getvalue()

        rv = BytesIO()
        psbt.serialize(rv)
        assert rv.tell() <= MAX_TXN_LEN, 'too fat'

        return rv.getvalue()
def test_dump():
    X_sparse, y_dense = load_svmlight_file(datafile)
    X_dense = X_sparse.toarray()
    y_sparse = sp.csr_matrix(y_dense)

    # slicing a csr_matrix can unsort its .indices, so test that we sort
    # those correctly
    X_sliced = X_sparse[np.arange(X_sparse.shape[0])]
    y_sliced = y_sparse[np.arange(y_sparse.shape[0])]

    for X in (X_sparse, X_dense, X_sliced):
        for y in (y_sparse, y_dense, y_sliced):
            for zero_based in (True, False):
                for dtype in [np.float32, np.float64, np.int32, np.int64]:
                    f = BytesIO()
                    # we need to pass a comment to get the version info in;
                    # LibSVM doesn't grok comments so they're not put in by
                    # default anymore.

                    if (sp.issparse(y) and y.shape[0] == 1):
                        # make sure y's shape is: (n_samples, n_labels)
                        # when it is sparse
                        y = y.T

                    # Note: with dtype=np.int32 we are performing unsafe casts,
                    # where X.astype(dtype) overflows. The result is
                    # then platform dependent and X_dense.astype(dtype) may be
                    # different from X_sparse.astype(dtype).asarray().
                    X_input = X.astype(dtype)

                    dump_svmlight_file(X_input, y, f, comment="test",
                                       zero_based=zero_based)
                    f.seek(0)

                    comment = f.readline()
                    comment = str(comment, "utf-8")

                    assert_in("scikit-learn %s" % sklearn.__version__, comment)

                    comment = f.readline()
                    comment = str(comment, "utf-8")

                    assert_in(["one", "zero"][zero_based] + "-based", comment)

                    X2, y2 = load_svmlight_file(f, dtype=dtype,
                                                zero_based=zero_based)
                    assert_equal(X2.dtype, dtype)
                    assert_array_equal(X2.sorted_indices().indices, X2.indices)

                    X2_dense = X2.toarray()
                    if sp.issparse(X_input):
                        X_input_dense = X_input.toarray()
                    else:
                        X_input_dense = X_input

                    if dtype == np.float32:
                        # allow a rounding error at the last decimal place
                        assert_array_almost_equal(
                            X_input_dense, X2_dense, 4)
                        assert_array_almost_equal(
                            y_dense.astype(dtype), y2, 4)
                    else:
                        # allow a rounding error at the last decimal place
                        assert_array_almost_equal(
                            X_input_dense, X2_dense, 15)
                        assert_array_almost_equal(
                            y_dense.astype(dtype), y2, 15)
def test_load_zero_based():
    f = BytesIO(b"-1 4:1.\n1 0:1\n")
    assert_raises(ValueError, load_svmlight_file, f, zero_based=False)
Example #14
0
    def launch_next(self):
        path = ""
        title = ""
        var.next_downloaded = False
        logging.debug(var.current_music)
        if var.current_music["type"] == "url" or var.current_music["type"] == "playlist":
            url = media.get_url(var.current_music["url"])

            if not url:
                return

            media.clear_tmp_folder(var.config.get('bot', 'tmp_folder'), var.config.getint('bot', 'tmp_folder_max_size'))

            if var.current_music["type"] == "playlist":
                path, title = self.download_music(url, var.current_music["current_index"])
                var.current_music["playlist_title"] = title
            else:
                path, title = self.download_music(url)
            var.current_music["path"] = path

            if os.path.isfile(path):
                audio = EasyID3(path)
                if audio["title"]:
                    title = audio["title"][0]

                path_thumbnail = var.config.get('bot', 'tmp_folder') + hashlib.md5(path.encode()).hexdigest() + '.jpg'
                thumbnail_html = ""
                if os.path.isfile(path_thumbnail):
                    im = Image.open(path_thumbnail)
                    im.thumbnail((100, 100), Image.ANTIALIAS)
                    buffer = BytesIO()
                    im.save(buffer, format="JPEG")
                    thumbnail_base64 = base64.b64encode(buffer.getvalue())
                    thumbnail_html = '<img - src="data:image/PNG;base64,' + thumbnail_base64.decode() + '"/>'

                logging.debug(thumbnail_html)
                if var.config.getboolean('bot', 'announce_current_music'):
                    self.send_msg_channel(var.config.get('strings', 'now_playing') % (title, thumbnail_html))
            else:
                if var.current_music["type"] == "playlist":
                    var.current_music['current_index'] = var.current_music['number_track_to_play']
                if self.get_next():
                    self.launch_next()
                    self.async_download_next()

        elif var.current_music["type"] == "file":
            path = var.config.get('bot', 'music_folder') + var.current_music["path"]
            title = var.current_music["path"]

        elif var.current_music["type"] == "radio":
            url = media.get_url(var.current_music["path"])
            if not url:
                return
            var.current_music["path"] = url
            path = url
            title = media.get_radio_server_description(url)

        var.current_music["title"] = title

        if var.config.getboolean('debug', 'ffmpeg'):
            ffmpeg_debug = "debug"
        else:
            ffmpeg_debug = "warning"

        command = ["ffmpeg", '-v', ffmpeg_debug, '-nostdin', '-i', path, '-ac', '1', '-f', 's16le', '-ar', '48000', '-']
        self.thread = sp.Popen(command, stdout=sp.PIPE, bufsize=480)
Example #15
0
def roundtrip(im, **options):
    out = BytesIO()
    im.save(out, "PNG", **options)
    out.seek(0)
    return Image.open(out)
Example #16
0
def send_image(filename):
    #return send_from_directory("images", filename)
    file_data = FileContents.query.filter_by(name=filename).first()
    print "data: ", BytesIO(file_data.data)
    return send_file(BytesIO(file_data.data), attachment_filename=filename, as_attachment=True)   
Example #17
0
    def test_repr_png(self):
        im = hopper()

        repr_png = Image.open(BytesIO(im._repr_png_()))
        self.assertEqual(repr_png.format, 'PNG')
        self.assert_image_equal(im, repr_png)
Example #18
0
def download():
    file_data = FileContents.query.filter_by(id=1).first()
    return send_file(BytesIO(file_data.data), attachment_filename='profile2.jpg', as_attachment=True)
Example #19
0
def __import_data__(chat_id, data):
    failures = []
    for notename, notedata in data.get("extra", {}).items():
        match = FILE_MATCHER.match(notedata)
        matchsticker = STICKER_MATCHER.match(notedata)
        matchbtn = BUTTON_MATCHER.match(notedata)
        matchfile = MYFILE_MATCHER.match(notedata)
        matchphoto = MYPHOTO_MATCHER.match(notedata)
        matchaudio = MYAUDIO_MATCHER.match(notedata)
        matchvoice = MYVOICE_MATCHER.match(notedata)
        matchvideo = MYVIDEO_MATCHER.match(notedata)
        matchvn = MYVIDEONOTE_MATCHER.match(notedata)

        if match:
            failures.append(notename)
            notedata = notedata[match.end():].strip()
            if notedata:
                sql.add_note_to_db(chat_id, notename[1:], notedata,
                                   sql.Types.TEXT)
        elif matchsticker:
            content = notedata[matchsticker.end():].strip()
            if content:
                sql.add_note_to_db(chat_id,
                                   notename[1:],
                                   notedata,
                                   sql.Types.STICKER,
                                   file=content)
        elif matchbtn:
            parse = notedata[matchbtn.end():].strip()
            notedata = parse.split("<###button###>")[0]
            buttons = parse.split("<###button###>")[1]
            buttons = ast.literal_eval(buttons)
            if buttons:
                sql.add_note_to_db(
                    chat_id,
                    notename[1:],
                    notedata,
                    sql.Types.BUTTON_TEXT,
                    buttons=buttons,
                )
        elif matchfile:
            file = notedata[matchfile.end():].strip()
            file = file.split("<###TYPESPLIT###>")
            notedata = file[1]
            content = file[0]
            if content:
                sql.add_note_to_db(chat_id,
                                   notename[1:],
                                   notedata,
                                   sql.Types.DOCUMENT,
                                   file=content)
        elif matchphoto:
            photo = notedata[matchphoto.end():].strip()
            photo = photo.split("<###TYPESPLIT###>")
            notedata = photo[1]
            content = photo[0]
            if content:
                sql.add_note_to_db(chat_id,
                                   notename[1:],
                                   notedata,
                                   sql.Types.PHOTO,
                                   file=content)
        elif matchaudio:
            audio = notedata[matchaudio.end():].strip()
            audio = audio.split("<###TYPESPLIT###>")
            notedata = audio[1]
            content = audio[0]
            if content:
                sql.add_note_to_db(chat_id,
                                   notename[1:],
                                   notedata,
                                   sql.Types.AUDIO,
                                   file=content)
        elif matchvoice:
            voice = notedata[matchvoice.end():].strip()
            voice = voice.split("<###TYPESPLIT###>")
            notedata = voice[1]
            content = voice[0]
            if content:
                sql.add_note_to_db(chat_id,
                                   notename[1:],
                                   notedata,
                                   sql.Types.VOICE,
                                   file=content)
        elif matchvideo:
            video = notedata[matchvideo.end():].strip()
            video = video.split("<###TYPESPLIT###>")
            notedata = video[1]
            content = video[0]
            if content:
                sql.add_note_to_db(chat_id,
                                   notename[1:],
                                   notedata,
                                   sql.Types.VIDEO,
                                   file=content)
        elif matchvn:
            video_note = notedata[matchvn.end():].strip()
            video_note = video_note.split("<###TYPESPLIT###>")
            notedata = video_note[1]
            content = video_note[0]
            if content:
                sql.add_note_to_db(chat_id,
                                   notename[1:],
                                   notedata,
                                   sql.Types.VIDEO_NOTE,
                                   file=content)
        else:
            sql.add_note_to_db(chat_id, notename[1:], notedata, sql.Types.TEXT)

    if failures:
        with BytesIO(str.encode("\n".join(failures))) as output:
            output.name = "failed_imports.txt"
            dispatcher.bot.send_document(
                chat_id,
                document=output,
                filename="failed_imports.txt",
                caption="These files/photos failed to import due to originating "
                "from another bot. This is a telegram API restriction, and can't "
                "be avoided. Sorry for the inconvenience!",
            )
Example #20
0
 def echo(self, _body):
     return BytesIO(_body.read())
Example #21
0
    def run_test(self):
        self.log.info(
            'prepare some coins for multiple *rawtransaction commands')
        self.nodes[2].generate(1)
        self.sync_all()
        self.nodes[0].generate(101)
        self.sync_all()
        self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.5)
        self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0)
        self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 5.0)
        self.sync_all()
        self.nodes[0].generate(5)
        self.sync_all()

        self.log.info(
            'Test getrawtransaction on genesis block coinbase returns an error'
        )
        block = self.nodes[0].getblock(self.nodes[0].getblockhash(0))
        assert_raises_rpc_error(
            -5,
            "The genesis block coinbase is not considered an ordinary transaction",
            self.nodes[0].getrawtransaction, block['merkleroot'])

        self.log.info(
            'Check parameter types and required parameters of createrawtransaction'
        )
        # Test `createrawtransaction` required parameters
        assert_raises_rpc_error(-1, "createrawtransaction",
                                self.nodes[0].createrawtransaction)
        assert_raises_rpc_error(-1, "createrawtransaction",
                                self.nodes[0].createrawtransaction, [])

        # Test `createrawtransaction` invalid extra parameters
        assert_raises_rpc_error(-1, "createrawtransaction",
                                self.nodes[0].createrawtransaction, [], {}, 0,
                                False, 'foo')

        # Test `createrawtransaction` invalid `inputs`
        txid = '1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000'
        assert_raises_rpc_error(-3, "Expected type array",
                                self.nodes[0].createrawtransaction, 'foo', {})
        assert_raises_rpc_error(-1, "JSON value is not an object as expected",
                                self.nodes[0].createrawtransaction, ['foo'],
                                {})
        assert_raises_rpc_error(-1, "JSON value is not a string as expected",
                                self.nodes[0].createrawtransaction, [{}], {})
        assert_raises_rpc_error(
            -8, "txid must be of length 64 (not 3, for 'foo')",
            self.nodes[0].createrawtransaction, [{
                'txid': 'foo'
            }], {})
        assert_raises_rpc_error(
            -8,
            "txid must be hexadecimal string (not 'ZZZ7bb8b1697ea987f3b223ba7819250cae33efacb068d23dc24859824a77844')",
            self.nodes[0].createrawtransaction, [{
                'txid':
                'ZZZ7bb8b1697ea987f3b223ba7819250cae33efacb068d23dc24859824a77844'
            }], {})
        assert_raises_rpc_error(-8, "Invalid parameter, missing vout key",
                                self.nodes[0].createrawtransaction,
                                [{
                                    'txid': txid
                                }], {})
        assert_raises_rpc_error(-8, "Invalid parameter, missing vout key",
                                self.nodes[0].createrawtransaction,
                                [{
                                    'txid': txid,
                                    'vout': 'foo'
                                }], {})
        assert_raises_rpc_error(-8, "Invalid parameter, vout must be positive",
                                self.nodes[0].createrawtransaction, [{
                                    'txid': txid,
                                    'vout': -1
                                }], {})
        assert_raises_rpc_error(
            -8, "Invalid parameter, sequence number is out of range",
            self.nodes[0].createrawtransaction, [{
                'txid': txid,
                'vout': 0,
                'sequence': -1
            }], {})

        # Test `createrawtransaction` invalid `outputs`
        address = self.nodes[0].getnewaddress()
        address2 = self.nodes[0].getnewaddress()
        assert_raises_rpc_error(-1, "JSON value is not an array as expected",
                                self.nodes[0].createrawtransaction, [], 'foo')
        self.nodes[0].createrawtransaction(
            inputs=[],
            outputs={})  # Should not throw for backwards compatibility
        self.nodes[0].createrawtransaction(inputs=[], outputs=[])
        assert_raises_rpc_error(-8, "Data must be hexadecimal string",
                                self.nodes[0].createrawtransaction, [],
                                {'data': 'foo'})
        assert_raises_rpc_error(-5, "Invalid Bitcoin address",
                                self.nodes[0].createrawtransaction, [],
                                {'foo': 0})
        assert_raises_rpc_error(-3, "Invalid amount",
                                self.nodes[0].createrawtransaction, [],
                                {address: 'foo'})
        assert_raises_rpc_error(-3, "Amount out of range",
                                self.nodes[0].createrawtransaction, [],
                                {address: -1})
        assert_raises_rpc_error(
            -8, "Invalid parameter, duplicated address: %s" % address,
            self.nodes[0].createrawtransaction, [],
            multidict([(address, 1), (address, 1)]))
        assert_raises_rpc_error(
            -8, "Invalid parameter, duplicated address: %s" % address,
            self.nodes[0].createrawtransaction, [], [{
                address: 1
            }, {
                address: 1
            }])
        assert_raises_rpc_error(-8, "Invalid parameter, duplicate key: data",
                                self.nodes[0].createrawtransaction, [],
                                [{
                                    "data": 'aa'
                                }, {
                                    "data": "bb"
                                }])
        assert_raises_rpc_error(-8, "Invalid parameter, duplicate key: data",
                                self.nodes[0].createrawtransaction, [],
                                multidict([("data", 'aa'), ("data", "bb")]))
        assert_raises_rpc_error(
            -8,
            "Invalid parameter, key-value pair must contain exactly one key",
            self.nodes[0].createrawtransaction, [], [{
                'a': 1,
                'b': 2
            }])
        assert_raises_rpc_error(
            -8, "Invalid parameter, key-value pair not an object as expected",
            self.nodes[0].createrawtransaction, [],
            [['key-value pair1'], ['2']])

        # Test `createrawtransaction` invalid `locktime`
        assert_raises_rpc_error(-3, "Expected type number",
                                self.nodes[0].createrawtransaction, [], {},
                                'foo')
        assert_raises_rpc_error(-8, "Invalid parameter, locktime out of range",
                                self.nodes[0].createrawtransaction, [], {}, -1)
        assert_raises_rpc_error(-8, "Invalid parameter, locktime out of range",
                                self.nodes[0].createrawtransaction, [], {},
                                4294967296)

        # Test `createrawtransaction` invalid `replaceable`
        assert_raises_rpc_error(-3, "Expected type bool",
                                self.nodes[0].createrawtransaction, [], {}, 0,
                                'foo')

        self.log.info(
            'Check that createrawtransaction accepts an array and object as outputs'
        )
        tx = CTransaction()
        # One output
        tx.deserialize(
            BytesIO(
                hex_str_to_bytes(self.nodes[2].createrawtransaction(
                    inputs=[{
                        'txid': txid,
                        'vout': 9
                    }], outputs={address: 99}))))
        assert_equal(len(tx.vout), 1)
        assert_equal(
            tx.serialize().hex(),
            self.nodes[2].createrawtransaction(inputs=[{
                'txid': txid,
                'vout': 9
            }],
                                               outputs=[{
                                                   address: 99
                                               }]),
        )
        # Two outputs
        tx.deserialize(
            BytesIO(
                hex_str_to_bytes(self.nodes[2].createrawtransaction(
                    inputs=[{
                        'txid': txid,
                        'vout': 9
                    }],
                    outputs=OrderedDict([(address, 99), (address2, 99)])))))
        assert_equal(len(tx.vout), 2)
        assert_equal(
            tx.serialize().hex(),
            self.nodes[2].createrawtransaction(inputs=[{
                'txid': txid,
                'vout': 9
            }],
                                               outputs=[{
                                                   address: 99
                                               }, {
                                                   address2: 99
                                               }]),
        )
        # Multiple mixed outputs
        tx.deserialize(
            BytesIO(
                hex_str_to_bytes(self.nodes[2].createrawtransaction(
                    inputs=[{
                        'txid': txid,
                        'vout': 9
                    }],
                    outputs=multidict([(address, 99), (address2, 99),
                                       ('data', '99')])))))
        assert_equal(len(tx.vout), 3)
        assert_equal(
            tx.serialize().hex(),
            self.nodes[2].createrawtransaction(inputs=[{
                'txid': txid,
                'vout': 9
            }],
                                               outputs=[{
                                                   address: 99
                                               }, {
                                                   address2: 99
                                               }, {
                                                   'data': '99'
                                               }]),
        )

        for type in ["bech32", "p2sh-segwit", "legacy"]:
            addr = self.nodes[0].getnewaddress("", type)
            addrinfo = self.nodes[0].getaddressinfo(addr)
            pubkey = addrinfo["scriptPubKey"]

            self.log.info('sendrawtransaction with missing prevtx info (%s)' %
                          (type))

            # Test `signrawtransactionwithwallet` invalid `prevtxs`
            inputs = [{'txid': txid, 'vout': 3, 'sequence': 1000}]
            outputs = {self.nodes[0].getnewaddress(): 1}
            rawtx = self.nodes[0].createrawtransaction(inputs, outputs)

            prevtx = dict(txid=txid, scriptPubKey=pubkey, vout=3, amount=1)
            succ = self.nodes[0].signrawtransactionwithwallet(rawtx, [prevtx])
            assert succ["complete"]
            if type == "legacy":
                del prevtx["amount"]
                succ = self.nodes[0].signrawtransactionwithwallet(
                    rawtx, [prevtx])
                assert succ["complete"]

            if type != "legacy":
                assert_raises_rpc_error(
                    -3, "Missing amount",
                    self.nodes[0].signrawtransactionwithwallet, rawtx,
                    [{
                        "txid": txid,
                        "scriptPubKey": pubkey,
                        "vout": 3,
                    }])

            assert_raises_rpc_error(-3, "Missing vout",
                                    self.nodes[0].signrawtransactionwithwallet,
                                    rawtx, [{
                                        "txid": txid,
                                        "scriptPubKey": pubkey,
                                        "amount": 1,
                                    }])
            assert_raises_rpc_error(-3, "Missing txid",
                                    self.nodes[0].signrawtransactionwithwallet,
                                    rawtx, [{
                                        "scriptPubKey": pubkey,
                                        "vout": 3,
                                        "amount": 1,
                                    }])
            assert_raises_rpc_error(-3, "Missing scriptPubKey",
                                    self.nodes[0].signrawtransactionwithwallet,
                                    rawtx, [{
                                        "txid": txid,
                                        "vout": 3,
                                        "amount": 1
                                    }])

        #########################################
        # sendrawtransaction with missing input #
        #########################################

        self.log.info('sendrawtransaction with missing input')
        inputs = [{
            'txid':
            "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000",
            'vout': 1
        }]  #won't exists
        outputs = {self.nodes[0].getnewaddress(): 4.998}
        rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
        rawtx = self.nodes[2].signrawtransactionwithwallet(rawtx)

        # This will raise an exception since there are missing inputs
        assert_raises_rpc_error(-25, "Missing inputs",
                                self.nodes[2].sendrawtransaction, rawtx['hex'])

        #####################################
        # getrawtransaction with block hash #
        #####################################

        # make a tx by sending then generate 2 blocks; block1 has the tx in it
        tx = self.nodes[2].sendtoaddress(self.nodes[1].getnewaddress(), 1)
        block1, block2 = self.nodes[2].generate(2)
        self.sync_all()
        # We should be able to get the raw transaction by providing the correct block
        gottx = self.nodes[0].getrawtransaction(tx, True, block1)
        assert_equal(gottx['txid'], tx)
        assert_equal(gottx['in_active_chain'], True)
        # We should not have the 'in_active_chain' flag when we don't provide a block
        gottx = self.nodes[0].getrawtransaction(tx, True)
        assert_equal(gottx['txid'], tx)
        assert 'in_active_chain' not in gottx
        # We should not get the tx if we provide an unrelated block
        assert_raises_rpc_error(-5, "No such transaction found",
                                self.nodes[0].getrawtransaction, tx, True,
                                block2)
        # An invalid block hash should raise the correct errors
        assert_raises_rpc_error(-1, "JSON value is not a string as expected",
                                self.nodes[0].getrawtransaction, tx, True,
                                True)
        assert_raises_rpc_error(
            -8, "parameter 3 must be of length 64 (not 6, for 'foobar')",
            self.nodes[0].getrawtransaction, tx, True, "foobar")
        assert_raises_rpc_error(
            -8, "parameter 3 must be of length 64 (not 8, for 'abcd1234')",
            self.nodes[0].getrawtransaction, tx, True, "abcd1234")
        assert_raises_rpc_error(
            -8,
            "parameter 3 must be hexadecimal string (not 'ZZZ0000000000000000000000000000000000000000000000000000000000000')",
            self.nodes[0].getrawtransaction, tx, True,
            "ZZZ0000000000000000000000000000000000000000000000000000000000000")
        assert_raises_rpc_error(
            -5, "Block hash not found", self.nodes[0].getrawtransaction, tx,
            True,
            "0000000000000000000000000000000000000000000000000000000000000000")
        # Undo the blocks and check in_active_chain
        self.nodes[0].invalidateblock(block1)
        gottx = self.nodes[0].getrawtransaction(txid=tx,
                                                verbose=True,
                                                blockhash=block1)
        assert_equal(gottx['in_active_chain'], False)
        self.nodes[0].reconsiderblock(block1)
        assert_equal(self.nodes[0].getbestblockhash(), block2)

        #########################
        # RAW TX MULTISIG TESTS #
        #########################
        # 2of2 test
        addr1 = self.nodes[2].getnewaddress()
        addr2 = self.nodes[2].getnewaddress()

        addr1Obj = self.nodes[2].getaddressinfo(addr1)
        addr2Obj = self.nodes[2].getaddressinfo(addr2)

        # Tests for createmultisig and addmultisigaddress
        assert_raises_rpc_error(-5, "Invalid public key",
                                self.nodes[0].createmultisig, 1, ["01020304"])
        self.nodes[0].createmultisig(
            2, [addr1Obj['pubkey'], addr2Obj['pubkey']
                ])  # createmultisig can only take public keys
        assert_raises_rpc_error(
            -5, "Invalid public key", self.nodes[0].createmultisig, 2,
            [addr1Obj['pubkey'], addr1]
        )  # addmultisigaddress can take both pubkeys and addresses so long as they are in the wallet, which is tested here.

        mSigObj = self.nodes[2].addmultisigaddress(
            2, [addr1Obj['pubkey'], addr1])['address']

        #use balance deltas instead of absolute values
        bal = self.nodes[2].getbalance()

        # send 1.2 BTC to msig adr
        txId = self.nodes[0].sendtoaddress(mSigObj, 1.2)
        self.sync_all()
        self.nodes[0].generate(1)
        self.sync_all()
        assert_equal(
            self.nodes[2].getbalance(), bal + Decimal('1.20000000')
        )  #node2 has both keys of the 2of2 ms addr., tx should affect the balance

        # 2of3 test from different nodes
        bal = self.nodes[2].getbalance()
        addr1 = self.nodes[1].getnewaddress()
        addr2 = self.nodes[2].getnewaddress()
        addr3 = self.nodes[2].getnewaddress()

        addr1Obj = self.nodes[1].getaddressinfo(addr1)
        addr2Obj = self.nodes[2].getaddressinfo(addr2)
        addr3Obj = self.nodes[2].getaddressinfo(addr3)

        mSigObj = self.nodes[2].addmultisigaddress(
            2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']
                ])['address']

        txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
        decTx = self.nodes[0].gettransaction(txId)
        rawTx = self.nodes[0].decoderawtransaction(decTx['hex'])
        self.sync_all()
        self.nodes[0].generate(1)
        self.sync_all()

        #THIS IS AN INCOMPLETE FEATURE
        #NODE2 HAS TWO OF THREE KEY AND THE FUNDS SHOULD BE SPENDABLE AND COUNT AT BALANCE CALCULATION
        assert_equal(
            self.nodes[2].getbalance(), bal
        )  #for now, assume the funds of a 2of3 multisig tx are not marked as spendable

        txDetails = self.nodes[0].gettransaction(txId, True)
        rawTx = self.nodes[0].decoderawtransaction(txDetails['hex'])
        vout = next(o for o in rawTx['vout']
                    if o['value'] == Decimal('2.20000000'))

        bal = self.nodes[0].getbalance()
        inputs = [{
            "txid": txId,
            "vout": vout['n'],
            "scriptPubKey": vout['scriptPubKey']['hex'],
            "amount": vout['value']
        }]
        outputs = {self.nodes[0].getnewaddress(): 2.19}
        rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
        rawTxPartialSigned = self.nodes[1].signrawtransactionwithwallet(
            rawTx, inputs)
        assert_equal(rawTxPartialSigned['complete'],
                     False)  #node1 only has one key, can't comp. sign the tx

        rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx, inputs)
        assert_equal(
            rawTxSigned['complete'],
            True)  #node2 can sign the tx compl., own two of three keys
        self.nodes[2].sendrawtransaction(rawTxSigned['hex'])
        rawTx = self.nodes[0].decoderawtransaction(rawTxSigned['hex'])
        self.sync_all()
        self.nodes[0].generate(1)
        self.sync_all()
        assert_equal(self.nodes[0].getbalance(), bal + Decimal('50.00000000') +
                     Decimal('2.19000000'))  #block reward + tx

        # 2of2 test for combining transactions
        bal = self.nodes[2].getbalance()
        addr1 = self.nodes[1].getnewaddress()
        addr2 = self.nodes[2].getnewaddress()

        addr1Obj = self.nodes[1].getaddressinfo(addr1)
        addr2Obj = self.nodes[2].getaddressinfo(addr2)

        self.nodes[1].addmultisigaddress(
            2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address']
        mSigObj = self.nodes[2].addmultisigaddress(
            2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address']
        mSigObjValid = self.nodes[2].getaddressinfo(mSigObj)

        txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
        decTx = self.nodes[0].gettransaction(txId)
        rawTx2 = self.nodes[0].decoderawtransaction(decTx['hex'])
        self.sync_all()
        self.nodes[0].generate(1)
        self.sync_all()

        assert_equal(
            self.nodes[2].getbalance(), bal
        )  # the funds of a 2of2 multisig tx should not be marked as spendable

        txDetails = self.nodes[0].gettransaction(txId, True)
        rawTx2 = self.nodes[0].decoderawtransaction(txDetails['hex'])
        vout = next(o for o in rawTx2['vout']
                    if o['value'] == Decimal('2.20000000'))

        bal = self.nodes[0].getbalance()
        inputs = [{
            "txid": txId,
            "vout": vout['n'],
            "scriptPubKey": vout['scriptPubKey']['hex'],
            "redeemScript": mSigObjValid['hex'],
            "amount": vout['value']
        }]
        outputs = {self.nodes[0].getnewaddress(): 2.19}
        rawTx2 = self.nodes[2].createrawtransaction(inputs, outputs)
        rawTxPartialSigned1 = self.nodes[1].signrawtransactionwithwallet(
            rawTx2, inputs)
        self.log.debug(rawTxPartialSigned1)
        assert_equal(rawTxPartialSigned1['complete'],
                     False)  #node1 only has one key, can't comp. sign the tx

        rawTxPartialSigned2 = self.nodes[2].signrawtransactionwithwallet(
            rawTx2, inputs)
        self.log.debug(rawTxPartialSigned2)
        assert_equal(rawTxPartialSigned2['complete'],
                     False)  #node2 only has one key, can't comp. sign the tx
        rawTxComb = self.nodes[2].combinerawtransaction(
            [rawTxPartialSigned1['hex'], rawTxPartialSigned2['hex']])
        self.log.debug(rawTxComb)
        self.nodes[2].sendrawtransaction(rawTxComb)
        rawTx2 = self.nodes[0].decoderawtransaction(rawTxComb)
        self.sync_all()
        self.nodes[0].generate(1)
        self.sync_all()
        assert_equal(self.nodes[0].getbalance(), bal + Decimal('50.00000000') +
                     Decimal('2.19000000'))  #block reward + tx

        # decoderawtransaction tests
        # witness transaction
        encrawtx = "010000000001010000000000000072c1a6a246ae63f74f931e8365e15a089c68d61900000000000000000000ffffffff0100e1f50500000000000102616100000000"
        decrawtx = self.nodes[0].decoderawtransaction(
            encrawtx, True)  # decode as witness transaction
        assert_equal(decrawtx['vout'][0]['value'], Decimal('1.00000000'))
        assert_raises_rpc_error(
            -22, 'TX decode failed', self.nodes[0].decoderawtransaction,
            encrawtx, False)  # force decode as non-witness transaction
        # non-witness transaction
        encrawtx = "01000000010000000000000072c1a6a246ae63f74f931e8365e15a089c68d61900000000000000000000ffffffff0100e1f505000000000000000000"
        decrawtx = self.nodes[0].decoderawtransaction(
            encrawtx, False)  # decode as non-witness transaction
        assert_equal(decrawtx['vout'][0]['value'], Decimal('1.00000000'))

        # getrawtransaction tests
        # 1. valid parameters - only supply txid
        txId = rawTx["txid"]
        assert_equal(self.nodes[0].getrawtransaction(txId), rawTxSigned['hex'])

        # 2. valid parameters - supply txid and 0 for non-verbose
        assert_equal(self.nodes[0].getrawtransaction(txId, 0),
                     rawTxSigned['hex'])

        # 3. valid parameters - supply txid and False for non-verbose
        assert_equal(self.nodes[0].getrawtransaction(txId, False),
                     rawTxSigned['hex'])

        # 4. valid parameters - supply txid and 1 for verbose.
        # We only check the "hex" field of the output so we don't need to update this test every time the output format changes.
        assert_equal(self.nodes[0].getrawtransaction(txId, 1)["hex"],
                     rawTxSigned['hex'])

        # 5. valid parameters - supply txid and True for non-verbose
        assert_equal(self.nodes[0].getrawtransaction(txId, True)["hex"],
                     rawTxSigned['hex'])

        # 6. invalid parameters - supply txid and string "Flase"
        assert_raises_rpc_error(-1, "not a boolean",
                                self.nodes[0].getrawtransaction, txId, "Flase")

        # 7. invalid parameters - supply txid and empty array
        assert_raises_rpc_error(-1, "not a boolean",
                                self.nodes[0].getrawtransaction, txId, [])

        # 8. invalid parameters - supply txid and empty dict
        assert_raises_rpc_error(-1, "not a boolean",
                                self.nodes[0].getrawtransaction, txId, {})

        inputs = [{
            'txid':
            "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000",
            'vout': 1,
            'sequence': 1000
        }]
        outputs = {self.nodes[0].getnewaddress(): 1}
        rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
        decrawtx = self.nodes[0].decoderawtransaction(rawtx)
        assert_equal(decrawtx['vin'][0]['sequence'], 1000)

        # 9. invalid parameters - sequence number out of range
        inputs = [{
            'txid':
            "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000",
            'vout': 1,
            'sequence': -1
        }]
        outputs = {self.nodes[0].getnewaddress(): 1}
        assert_raises_rpc_error(
            -8, 'Invalid parameter, sequence number is out of range',
            self.nodes[0].createrawtransaction, inputs, outputs)

        # 10. invalid parameters - sequence number out of range
        inputs = [{
            'txid':
            "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000",
            'vout': 1,
            'sequence': 4294967296
        }]
        outputs = {self.nodes[0].getnewaddress(): 1}
        assert_raises_rpc_error(
            -8, 'Invalid parameter, sequence number is out of range',
            self.nodes[0].createrawtransaction, inputs, outputs)

        inputs = [{
            'txid':
            "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000",
            'vout': 1,
            'sequence': 4294967294
        }]
        outputs = {self.nodes[0].getnewaddress(): 1}
        rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
        decrawtx = self.nodes[0].decoderawtransaction(rawtx)
        assert_equal(decrawtx['vin'][0]['sequence'], 4294967294)

        ####################################
        # TRANSACTION VERSION NUMBER TESTS #
        ####################################

        # Test the minimum transaction version number that fits in a signed 32-bit integer.
        tx = CTransaction()
        tx.nVersion = -0x80000000
        rawtx = ToHex(tx)
        decrawtx = self.nodes[0].decoderawtransaction(rawtx)
        assert_equal(decrawtx['version'], -0x80000000)

        # Test the maximum transaction version number that fits in a signed 32-bit integer.
        tx = CTransaction()
        tx.nVersion = 0x7fffffff
        rawtx = ToHex(tx)
        decrawtx = self.nodes[0].decoderawtransaction(rawtx)
        assert_equal(decrawtx['version'], 0x7fffffff)

        self.log.info('sendrawtransaction/testmempoolaccept with maxfeerate')

        # Test a transaction with a small fee.
        txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0)
        rawTx = self.nodes[0].getrawtransaction(txId, True)
        vout = next(o for o in rawTx['vout']
                    if o['value'] == Decimal('1.00000000'))

        self.sync_all()
        inputs = [{"txid": txId, "vout": vout['n']}]
        # Fee 10,000 satoshis, (1 - (10000 sat * 0.00000001 BTC/sat)) = 0.9999
        outputs = {self.nodes[0].getnewaddress(): Decimal("0.99990000")}
        rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
        rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx)
        assert_equal(rawTxSigned['complete'], True)
        # Fee 10,000 satoshis, ~100 b transaction, fee rate should land around 100 sat/byte = 0.00100000 BTC/kB
        # Thus, testmempoolaccept should reject
        testres = self.nodes[2].testmempoolaccept([rawTxSigned['hex']],
                                                  0.00001000)[0]
        assert_equal(testres['allowed'], False)
        assert_equal(testres['reject-reason'], 'absurdly-high-fee')
        # and sendrawtransaction should throw
        assert_raises_rpc_error(-26, "absurdly-high-fee",
                                self.nodes[2].sendrawtransaction,
                                rawTxSigned['hex'], 0.00001000)
        # and the following calls should both succeed
        testres = self.nodes[2].testmempoolaccept(
            rawtxs=[rawTxSigned['hex']])[0]
        assert_equal(testres['allowed'], True)
        self.nodes[2].sendrawtransaction(hexstring=rawTxSigned['hex'])

        # Test a transaction with a large fee.
        txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0)
        rawTx = self.nodes[0].getrawtransaction(txId, True)
        vout = next(o for o in rawTx['vout']
                    if o['value'] == Decimal('1.00000000'))

        self.sync_all()
        inputs = [{"txid": txId, "vout": vout['n']}]
        # Fee 2,000,000 satoshis, (1 - (2000000 sat * 0.00000001 BTC/sat)) = 0.98
        outputs = {self.nodes[0].getnewaddress(): Decimal("0.98000000")}
        rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
        rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx)
        assert_equal(rawTxSigned['complete'], True)
        # Fee 2,000,000 satoshis, ~100 b transaction, fee rate should land around 20,000 sat/byte = 0.20000000 BTC/kB
        # Thus, testmempoolaccept should reject
        testres = self.nodes[2].testmempoolaccept([rawTxSigned['hex']])[0]
        assert_equal(testres['allowed'], False)
        assert_equal(testres['reject-reason'], 'absurdly-high-fee')
        # and sendrawtransaction should throw
        assert_raises_rpc_error(-26, "absurdly-high-fee",
                                self.nodes[2].sendrawtransaction,
                                rawTxSigned['hex'])
        # and the following calls should both succeed
        testres = self.nodes[2].testmempoolaccept(rawtxs=[rawTxSigned['hex']],
                                                  maxfeerate='0.20000000')[0]
        assert_equal(testres['allowed'], True)
        self.nodes[2].sendrawtransaction(hexstring=rawTxSigned['hex'],
                                         maxfeerate='0.20000000')
Example #22
0
def img2str(img):
    rawBytes = BytesIO()
    img.save(rawBytes, "PNG")
    rawBytes.seek(0)
    return base64.b64encode(rawBytes.read()).decode('utf-8')
Example #23
0
    def to_wcs(self, use_full_header=False, target_image=None):
        """
        Convert AVM projection information into a Astropy WCS object.

        Parameters
        ----------
        use_full_header : bool, optional
            Whether to use the full embedded Header if available. If set to
            `False`, the WCS is determined from the regular AVM keywords.
        target_image : str, optional
            In some cases, the dimensions of the image containing the AVM/WCS
            information is different from the dimensions of the image for which
            the AVM was defined. The `target_image` option can be used to pass
            the path of an image from which the size will be used to re-scale
            the WCS.
        """

        if not astropy_installed:
            raise Exception("Astropy is required to use to_wcs()")

        if repr(self.Spatial) == '':
            raise NoSpatialInformation(
                "AVM meta-data does not contain any spatial information")

        if use_full_header and self.Spatial.FITSheader is not None:
            print("Using full FITS header from Spatial.FITSheader")
            header = fits.Header(txtfile=BytesIO(self.Spatial.FITSheader))
            return WCS(header)

        # Initializing WCS object
        wcs = WCS(naxis=2)

        # Find the coordinate type
        if self.Spatial.CoordinateFrame is not None:
            ctype = self.Spatial.CoordinateFrame
        else:
            warnings.warn("Spatial.CoordinateFrame not found, assuming ICRS")
            ctype = 'ICRS'

        if ctype in ['ICRS', 'FK5', 'FK4']:
            xcoord = "RA--"
            ycoord = "DEC-"
            wcs.wcs.radesys = ctype.encode('ascii')
        elif ctype in ['ECL']:
            xcoord = "ELON"
            ycoord = "ELAT"
        elif ctype in ['GAL']:
            xcoord = "GLON"
            ycoord = "GLAT"
        elif ctype in ['SGAL']:
            xcoord = "SLON"
            ycoord = "SLAT"
        else:
            raise Exception("Unknown coordinate system: %s" % ctype)

        # Find the projection type
        cproj = ('%+4s' % self.Spatial.CoordsystemProjection).replace(' ', '-')

        wcs.wcs.ctype[0] = (xcoord + cproj).encode('ascii')
        wcs.wcs.ctype[1] = (ycoord + cproj).encode('ascii')

        # Find the equinox
        if self.Spatial.Equinox is None:
            warnings.warn("Spatial.Equinox is not present, assuming 2000")
            wcs.wcs.equinox = 2000.
        elif type(self.Spatial.Equinox) is str:
            if self.Spatial.Equinox == "J2000":
                wcs.wcs.equinox = 2000.
            elif self.Spatial.Equinox == "B1950":
                wcs.wcs.equinox = 1950.
            else:
                try:
                    wcs.wcs.equinox = float(self.Spatial.Equinox)
                except ValueError:
                    raise ValueError("Unknown equinox: %s" %
                                     self.Spatial.Equinox)
        else:
            wcs.wcs.equinox = float(self.Spatial.Equinox)

        # Set standard WCS parameters
        if self.Spatial.ReferenceDimension is not None:
            wcs_naxis1, wcs_naxis2 = self.Spatial.ReferenceDimension
            if hasattr(wcs, 'naxis1'):  # PyWCS and Astropy < 0.4
                wcs.naxis1, wcs.naxis2 = wcs_naxis1, wcs_naxis2
        else:
            wcs_naxis1, wcs_naxis2 = None, None

        wcs.wcs.crval = self.Spatial.ReferenceValue
        wcs.wcs.crpix = self.Spatial.ReferencePixel

        if self.Spatial.CDMatrix is not None:
            wcs.wcs.cd = [
                self.Spatial.CDMatrix[0:2], self.Spatial.CDMatrix[2:4]
            ]
        elif self.Spatial.Scale is not None:
            # AVM Standard 1.2:
            #
            # "The scale should follow the standard FITS convention for sky
            # projections in which the first element is negative (indicating
            # increasing RA/longitude to the left) and the second is positive.
            # In practice, only the absolute value of the first term should be
            # necessary to identify the pixel scale since images should always
            # be presented in an undistorted 1:1 aspect ratio as they appear in
            # the sky when viewed from Earth.This field can be populated from
            # the FITS keywords: CDELT1, CDELT2 (or derived from CD matrix)."
            #
            # Therefore, we have to enforce the sign of CDELT:
            wcs.wcs.cdelt[0] = -abs(self.Spatial.Scale[0])
            wcs.wcs.cdelt[1] = +abs(self.Spatial.Scale[1])
            if self.Spatial.Rotation is not None:
                wcs.wcs.crota = self.Spatial.Rotation, self.Spatial.Rotation

        # If `target_image` is set, we have to rescale the reference pixel and
        # the scale
        if target_image is not None:

            # Find target image size
            from PIL import Image
            nx, ny = Image.open(target_image).size

            if self.Spatial.ReferenceDimension is None:
                raise ValueError(
                    "Spatial.ReferenceDimension should be set in order to determine scale in target image"
                )

            # Find scale in x and y
            scale_x = nx / float(wcs_naxis1)
            scale_y = ny / float(wcs_naxis2)

            # Check that scales are consistent
            if abs(scale_x - scale_y) / (scale_x + scale_y) * 2. < 0.01:
                scale = scale_x
            else:
                raise ValueError(
                    "Cannot scale WCS to target image consistently in x and y direction"
                )

            wcs.wcs.cdelt /= scale
            wcs.wcs.crpix *= scale

            if hasattr(wcs, 'naxis1'):  # PyWCS and Astropy < 0.4
                wcs.naxis1 = nx
                wcs.naxis2 = ny

        return wcs
Example #24
0
def config_from_string(config_str, portnumfile):
    parser = ConfigParser.SafeConfigParser()
    parser.readfp(BytesIO(config_str))
    return _Config(parser, portnumfile, '<in-memory>')
Example #25
0
url1=" "
url2=" "
url3=" "
import json
import requests
str1=input('enter the name of city')
url1="http://api.openweathermap.org/data/2.5/weather?q="
url1=url1+str1
url3="&appid=5bd3b3302e17b1fb27cd720ccebff986"
url1=url1+url3

output=requests.get(url1)
output2=output.json()
#print(output2)
print("cordinate are {} weather is {} Wind Speed {} Sunset Rise{} and Set timing {}".format(output2["coord"],output2["weather"],output2["wind"],output2["sys"]["sunrise"],output2["sys"]["sunset"])) 


from PIL import Image
import requests
from io import BytesIO

url = "http://forsk.in/images/Forsk_logo_bw.png"
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img.save("forsk-logo.png")

Example #26
0
def chunk(cid, *data):
    test_file = BytesIO()
    PngImagePlugin.putchunk(*(test_file, cid) + data)
    return test_file.getvalue()
Example #27
0
async def handler(event):
    if event.fwd_from:
        return
    if not event.is_reply:
        await event.edit("Reply to a photo/sticker to kang it.")
        return
    await event.edit(
        "```Me kanging your shitty stickers and you can't do anything about that shitty hooman...```"
    )
    reply_message = await event.get_reply_message()
    sticker_emoji = "🔥"
    pack_id = ""
    input_str = event.pattern_match.group(1)
    if input_str:
        input_str = input_str.split()
        is_int = False
        for char in input_str:
            try:
                is_int = int(char)
            except:
                is_int = False
                sticker_emoji = char
            if is_int:
                pack_id = char

    botuser = await client.get_me()
    botuser = f"@{botuser.username}"
    userid = event.from_id
    if ENV.STICKER_PACK is None:
        if not pack_id:
            pack_id = 1
        packname = f"{botuser}'s kang pack vol.{pack_id}"
        packshortname = f"cyberdoge_kang_pack_vol{pack_id}_{userid}"
    else:
        if pack_id:
            pack_id = f" {pack_id}"
        packname = f"{ENV.STICKER_PACK}{pack_id}"
        packshortname = f"Uniborg_Pack{pack_id}_{userid}"

    is_a_s = is_it_animated_sticker(reply_message)
    file_ext_ns_ion = "@CyberDoge_Sticker.png"
    file = await client.download_file(reply_message.media)
    uploaded_sticker = None
    if is_a_s:
        file_ext_ns_ion = "@CyberDoge_ANIMATED.tgs"
        uploaded_sticker = await client.upload_file(file,
                                                    file_name=file_ext_ns_ion)
        packname = f"{packname} [ANIMATED]"
        packshortname = f"{packshortname}_animated"
    elif not is_message_image(reply_message):
        await event.edit("Invalid message type")
        return
    else:
        with BytesIO(file) as mem_file, BytesIO() as sticker:
            resize_image(mem_file, sticker)
            sticker.seek(0)
            uploaded_sticker = await client.upload_file(
                sticker, file_name=file_ext_ns_ion)

    async with client.conversation("@Stickers") as bot_conv:
        now = datetime.datetime.now()
        dt = now + datetime.timedelta(minutes=1)
        if not await stickerset_exists(bot_conv, packshortname):
            await silently_send_message(bot_conv, "/cancel")
            if is_a_s:
                response = await silently_send_message(bot_conv,
                                                       "/newanimated")
            else:
                response = await silently_send_message(bot_conv, "/newpack")
            if "Yay!" not in response.text:
                await event.edit(
                    f"**FAILED**! @Stickers replied: {response.text}")
                return
            response = await silently_send_message(bot_conv, packname)
            if not response.text.startswith("Alright!"):
                await event.edit(
                    f"{packname} is full, try .kang <optional_emoji> {pack_id+1}"
                )
                return
            w = await bot_conv.send_file(file=uploaded_sticker,
                                         allow_cache=False,
                                         force_document=True)
            response = await bot_conv.get_response()
            if "Sorry" in response.text:
                await event.edit(
                    f"**FAILED**! @Stickers replied: {response.text}")
                return
            await silently_send_message(bot_conv, sticker_emoji)
            await silently_send_message(bot_conv, "/publish")
            response = await silently_send_message(bot_conv, f"<{packname}>")
            await silently_send_message(bot_conv, "/skip")
            response = await silently_send_message(bot_conv, packshortname)
            if response.text == "Sorry, this short name is already taken.":
                await event.edit(
                    f"**FAILED**! @Stickers replied: {response.text}")
                return
        else:
            await silently_send_message(bot_conv, "/cancel")
            await silently_send_message(bot_conv, "/addsticker")
            response = await silently_send_message(bot_conv, packshortname)
            if "Whoa!" in response.text:
                await event.edit(
                    f"{packname} is full, try .kang <optional_emoji> {int(pack_id) + 1}"
                )
                return
            await bot_conv.send_file(file=uploaded_sticker,
                                     allow_cache=False,
                                     force_document=True)
            response = await bot_conv.get_response()
            if "Sorry" in response.text:
                await event.edit(
                    f"**FAILED**! @Stickers replied: {response.text}")
                return
            await silently_send_message(bot_conv, response)
            await silently_send_message(bot_conv, sticker_emoji)
            await silently_send_message(bot_conv, "/done")

    await event.edit(
        f"Sticker successfully kanged to [{packname}](t.me/addstickers/{packshortname})!"
    )
Example #28
0
def load(data):
    return Image.open(BytesIO(data))
async def analyze(request):
    data = await request.form()
    img_bytes = await (data['file'].read())
    img = open_image(BytesIO(img_bytes))
    return JSONResponse({'result': learn.predict(img)[0]})
Example #30
0
def form_01(request_data):
    """
    Форма 003/у - cстационарная карта
    """

    num_dir = request_data["dir_pk"]
    direction_obj = Napravleniya.objects.get(pk=num_dir)
    hosp_nums_obj = hosp_get_hosp_direction(num_dir)
    hosp_nums = f"- {hosp_nums_obj[0].get('direction')}"

    ind_card = direction_obj.client
    patient_data = ind_card.get_data_individual()

    hospital: Hospitals = request_data["hospital"]

    hospital_name = hospital.safe_short_title
    hospital_address = hospital.safe_address
    hospital_kod_ogrn = hospital.safe_ogrn

    if sys.platform == 'win32':
        locale.setlocale(locale.LC_ALL, 'rus_rus')
    else:
        locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')

    pdfmetrics.registerFont(
        TTFont('PTAstraSerifBold',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf')))
    pdfmetrics.registerFont(
        TTFont('PTAstraSerifReg',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf')))

    buffer = BytesIO()
    doc = SimpleDocTemplate(buffer,
                            pagesize=A4,
                            leftMargin=20 * mm,
                            rightMargin=12 * mm,
                            topMargin=6 * mm,
                            bottomMargin=4 * mm,
                            allowSplitting=1,
                            title="Форма {}".format("003/у"))
    width, height = portrait(A4)
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifReg"
    style.fontSize = 12
    style.leading = 15
    style.spaceAfter = 0.5 * mm

    styleLead = deepcopy(style)
    styleLead.leading = 12
    styleLead.alignment = TA_JUSTIFY

    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"
    styleCenter = deepcopy(style)
    styleCenter.alignment = TA_CENTER
    styleCenter.fontSize = 12
    styleCenter.leading = 15
    styleCenter.spaceAfter = 1 * mm
    styleCenterBold = deepcopy(styleBold)
    styleCenterBold.alignment = TA_CENTER
    styleCenterBold.fontSize = 12
    styleCenterBold.leading = 15
    styleCenterBold.face = 'PTAstraSerifBold'
    styleCenterBold.borderColor = black
    styleJustified = deepcopy(style)
    styleJustified.alignment = TA_JUSTIFY
    styleJustified.spaceAfter = 4.5 * mm
    styleJustified.fontSize = 12
    styleJustified.leading = 4.5 * mm

    styleRight = deepcopy(styleJustified)
    styleRight.alignment = TA_RIGHT

    objs = []

    styleT = deepcopy(style)
    styleT.alignment = TA_LEFT
    styleT.fontSize = 10
    styleT.leading = 4.5 * mm
    styleT.face = 'PTAstraSerifReg'

    print_district = ''
    if SettingManager.get("district", default='True', default_type='b'):
        if ind_card.district is not None:
            print_district = 'Уч: {}'.format(ind_card.district.title)

    opinion = [
        [
            Paragraph(
                '<font size=11>{}<br/>Адрес: {}<br/>ОГРН: {} <br/><u>{}</u> </font>'
                .format(hospital_name, hospital_address, hospital_kod_ogrn,
                        print_district), styleT),
            Paragraph(
                '<font size=9 >Код формы по ОКУД:<br/>Код организации по ОКПО: 31348613<br/>'
                'Медицинская документация<br/>форма № 003/у</font>', styleT),
        ],
    ]

    tbl = Table(opinion, 2 * [90 * mm])
    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 0.75, colors.white),
            ('LEFTPADDING', (1, 0), (-1, -1), 80),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]))

    objs.append(tbl)
    space_symbol = '&nbsp;'
    if patient_data['age'] < SettingManager.get(
            "child_age_before", default='15', default_type='i'):
        patient_data['serial'] = patient_data['bc_serial']
        patient_data['num'] = patient_data['bc_num']
    else:
        patient_data['serial'] = patient_data['passport_serial']
        patient_data['num'] = patient_data['passport_num']

    p_phone = ''
    if patient_data['phone']:
        p_phone = 'тел.: ' + ", ".join(patient_data['phone'])

    p_address = patient_data['main_address']
    work_place = patient_data['work_place_db'] if patient_data[
        'work_place_db'] else patient_data['work_place']
    p_work = work_place

    card_num_obj = patient_data['card_num'].split(' ')
    p_card_num = card_num_obj[0]

    # взять самое последнее направленеие из hosp_dirs
    hosp_last_num = hosp_nums_obj[-1].get('direction')
    ############################################################################################################
    # Получение данных из выписки
    # Взять услугу типа выписка. Из полей "Дата выписки" - взять дату. Из поля "Время выписки" взять время
    hosp_extract_data = hosp_extract_get_data(hosp_last_num)

    extrac_date, extract_time, final_diagnos, other_diagnos, near_diagnos, outcome, doc_fio, manager_depart, room_num, depart_extract = '', '', '', '', '', '', '', '', '', ''
    days_count = '__________________________'

    if hosp_extract_data:
        extrac_date = hosp_extract_data['date_value']
        extract_time = hosp_extract_data['time_value']
        final_diagnos = hosp_extract_data['final_diagnos']
        other_diagnos = hosp_extract_data['other_diagnos']
        near_diagnos = hosp_extract_data['near_diagnos']
        days_count = hosp_extract_data['days_count']
        if hosp_extract_data['outcome']:
            outcome = hosp_extract_data['outcome'] + ' (' + hosp_extract_data[
                'result_hospital'] + ')'
        doc_fio = hosp_extract_data['doc_fio']
        manager_depart = hosp_extract_data['manager_depart']
        room_num = hosp_extract_data['room_num']
        iss_last_hosp = Issledovaniya.objects.filter(
            napravleniye__pk=hosp_last_num)[0]
        depart_extract = iss_last_hosp.research.title

    # Получить отделение - из названия услуги или самого главного направления
    hosp_depart = hosp_nums_obj[0].get('research_title')

    ############################################################################################################
    # Получить данные из первичного приема (самого первого hosp-направления)
    hosp_first_num = hosp_nums_obj[0].get('direction')
    primary_reception_data = primary_reception_get_data(hosp_first_num)

    ###########################################################################################################
    # Получение данных группы крови
    fcaction_avo_id = Fractions.objects.filter(
        title='Групповая принадлежность крови по системе АВО').first()
    fcaction_rezus_id = Fractions.objects.filter(title='Резус').first()
    group_blood_avo = get_fraction_result(ind_card.pk,
                                          fcaction_avo_id.pk,
                                          count=1)
    if group_blood_avo:
        group_blood_avo_value = group_blood_avo[0][5]
    else:
        group_blood_avo_value = primary_reception_data['blood_group']
    group_blood_rezus = get_fraction_result(ind_card.pk,
                                            fcaction_rezus_id.pk,
                                            count=1)
    if group_blood_rezus:
        group_rezus_value = group_blood_rezus[0][5].replace('<br/>', ' ')
    else:
        group_rezus_value = primary_reception_data['resus_factor']

    ###########################################################################################################
    # получение данных клинического диагноза
    clinical_diagnos = hosp_get_clinical_diagnos(hosp_nums_obj)

    #####################################################################################################
    # получить даные из переводного эпикриза: Дата перевода, Время перевода, в какое отделение переведен
    # у каждого hosp-направления найти подчиненное эпикриз Перевод*
    transfers_data = hosp_get_transfers_data(hosp_nums_obj)
    transfers = ''
    for i in transfers_data:
        transfers = f"{transfers} в {i['transfer_research_title']} {i['date_transfer_value']}/{i['time_transfer_value']};"

    #####################################################################################################
    title_page = [
        Indenter(left=0 * mm),
        Spacer(1, 8 * mm),
        Paragraph(
            '<font fontname="PTAstraSerifBold" size=15>МЕДИЦИНСКАЯ КАРТА № {} <u>{}</u>, <br/> стационарного больного</font>'
            .format(p_card_num, hosp_nums), styleCenter),
        Spacer(1, 2 * mm),
        Spacer(1, 2 * mm),
        Spacer(1, 2 * mm),
        Paragraph(
            'Дата и время поступления: {} - {}'.format(
                primary_reception_data['date_entered_value'],
                primary_reception_data['time_entered_value']), style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            'Дата и время выписки: {} - {}'.format(extrac_date, extract_time),
            style),
        Spacer(1, 0.5 * mm),
        Paragraph('Отделение: {}'.format(hosp_depart), style),
        Spacer(1, 0.5 * mm),
        Paragraph(f"Палата №: {room_num} {depart_extract}", style),
        Spacer(1, 0.5 * mm),
        Paragraph('Переведен в отделение:', style),
        Spacer(1, 8 * mm),
        Paragraph('Проведено койко-дней: {}'.format(days_count), style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            'Виды транспортировки(на каталке, на кресле, может идти): {}'.
            format(primary_reception_data['type_transport']), style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            'Группа крови: {}. Резус-принадлежность: {}'.format(
                group_blood_avo_value, group_rezus_value), style),
        Spacer(1, 1 * mm),
        Paragraph('Побочное действие лекарств(непереносимость):', style),
        Spacer(1, 12 * mm),
        Paragraph("1. Фамилия, имя, отчество:&nbsp;", style),
        Spacer(1, 2 * mm),
        Paragraph(
            '2. Пол: {} {} 3. Дата рождения: {}'.format(
                patient_data['sex'], 3 * space_symbol, patient_data['born']),
            style),
        Spacer(1, 0.5 * mm),
        Paragraph('4. Постоянное место жительства: ', style),
        Spacer(1, 3.5 * mm),
        Paragraph('5. Место работы, профессия или должность:', style),
        Spacer(1, 0.5 * mm),
        Paragraph('6. Кем направлен больной:', style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            '7. Доставлен в стационар по экстренным показаниям: {}'.format(
                primary_reception_data['extra_hospital']), style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            ' через: {} после начала заболевания, получения травмы; '.format(
                primary_reception_data['time_start_ill']), style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            ' госпитализирован в плановом порядке (подчеркнуть) {}.'.format(
                primary_reception_data['plan_hospital']), style),
        Spacer(1, 0.5 * mm),
        Paragraph('8. Диагноз направившего учреждения:', style),
        Spacer(1, 8 * mm),
        Paragraph('9. Диагноз при поступлении:', style),
        Spacer(1, 10 * mm),
        Paragraph('10. Диагноз клинический:', style),
        PageBreak(),
    ]

    closed_bl_result = closed_bl(hosp_nums_obj[0].get('direction'))
    data_bl = ''
    if closed_bl_result['start_date'] and closed_bl_result[
            'end_date'] and closed_bl_result['num']:
        data_bl = (
            f"<br/>открыт <u>{closed_bl_result['start_date']}</u>{5 * space_symbol}закрыт: <u>{closed_bl_result['end_date']}</u> {3 * space_symbol}"
            f"к труду: <u>{closed_bl_result['start_work']}</u> <br/>Номер ЛН: <u>{closed_bl_result['num']}</u> Выдан кому: {closed_bl_result['who_get']} "
        )

    second_page = [
        Spacer(1, 2 * mm),
        Paragraph('11. Диагноз заключительный клинический:', style),
        Spacer(1, 0.5 * mm),
        Paragraph('а) основной:', style),
        Spacer(1, 45 * mm),
        Paragraph('б) осложнение основного:', style),
        Spacer(1, 18 * mm),
        Paragraph('в) сопутствующий:', style),
        Spacer(1, 19 * mm),
        Paragraph(
            '12. Госпитализирован в данном году по поводу данного заболевания: {}, <br/>'
            'всего  - {} раз.:'.format(
                primary_reception_data['what_time_hospitalized'],
                primary_reception_data['all_hospitalized']),
            styleLead,
        ),
        Spacer(1, 1 * mm),
        Paragraph(
            '13. Хирургические операции, методы обезболивания и послеоперационные осложнения:',
            styleLead),
        Spacer(1, 40 * mm),
        Paragraph(
            '14. Другие виды лечения:___________________________________________',
            styleLead),
        Spacer(1, 0.2 * mm),
        Paragraph('для больных злокачественными новообразованиями.',
                  styleLead),
        Spacer(1, 0.2 * mm),
        Paragraph(
            ' 1.Специальное лечение: хирургическое(дистанционная гамматерапия, рентгенотерапия, быстрые '
            'электроны, контактная и дистанционная гамматерапия, контактная гамматерапия и глубокая '
            'рентгенотерапия); комбинированное(хирургическое и гамматерапия, хирургическое и рентгено - '
            'терапия, хирургическое и сочетанное лучевое); химиопрепаратами, гормональными препаратами.',
            styleLead,
        ),
        Spacer(1, 1 * mm),
        Paragraph('2. Паллиативное', styleLead),
        Spacer(1, 0.2 * mm),
        Paragraph('3. Симптоматическое лечение.', styleLead),
        Spacer(1, 0.2 * mm),
        Paragraph(f"15. Отметка о выдаче листка нетрудоспособности:{data_bl}",
                  styleLead),
        Spacer(1, 1 * mm),
        Paragraph('16. Исход заболевания: {}'.format(outcome), styleLead),
        Spacer(1, 1 * mm),
        Paragraph(
            '17.  Трудоспособность восстановлена полностью, снижена, временно утрачена, стойко утрачена в связи '
            'с данным заболеванием, с другими причинами(подчеркнуть): {}'.
            format(''),
            styleLead,
        ),
        Spacer(1, 1 * mm),
        Paragraph(
            '18. Для поступивших на экспертизу - заключение:___________________',
            styleLead),
        Spacer(1, 1 * mm),
        Paragraph(
            '___________________________________________________________________',
            styleLead),
        Spacer(1, 1 * mm),
        Paragraph('19. Особые отметки', style),
        Spacer(1, 2 * mm),
        Paragraph('Лечащий врач: {}'.format(doc_fio), style),
        Paragraph('Заведующий отделением: {}'.format(manager_depart), style),
    ]
    if primary_reception_data['weight']:
        second_page.append(
            Paragraph(f"Вес: {primary_reception_data['weight']}", styleRight))
    objs.extend(title_page)
    objs.extend(second_page)

    closed_bl_result = closed_bl(hosp_nums_obj[0].get('direction'))

    def first_pages(canvas, document):
        canvas.saveState()
        if closed_bl_result.get('is_closed', None):
            canvas.setFont('PTAstraSerifBold', 12)
            canvas.drawString(7 * mm, 290 * mm, 'ЛН')
        # Переведен
        transfers_text = [Paragraph('{}'.format(transfers), styleJustified)]
        transfers_frame = Frame(27 * mm,
                                206 * mm,
                                175 * mm,
                                7 * mm,
                                leftPadding=0,
                                bottomPadding=0,
                                rightPadding=0,
                                topPadding=0,
                                id='diagnos_frame',
                                showBoundary=0)
        transfers_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            transfers_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        transfers_frame.addFromList([transfers_inframe], canvas)

        # Побочное действие лекарств(непереносимость) координаты
        medicament_text = [
            Paragraph(
                '{}'.format(primary_reception_data['medicament_allergy']),
                styleJustified)
        ]
        medicament_frame = Frame(27 * mm,
                                 171 * mm,
                                 175 * mm,
                                 9 * mm,
                                 leftPadding=0,
                                 bottomPadding=0,
                                 rightPadding=0,
                                 topPadding=0,
                                 id='diagnos_frame',
                                 showBoundary=0)
        medicament_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            medicament_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        medicament_frame.addFromList([medicament_inframe], canvas)

        # ФИО
        fio_text = [
            Paragraph(
                "<font size=11.7 fontname ='PTAstraSerifBold'> {}</font> ".
                format(patient_data['fio']), style)
        ]
        fio_frame = Frame(77 * mm,
                          159 * mm,
                          125 * mm,
                          8 * mm,
                          leftPadding=0,
                          bottomPadding=0,
                          rightPadding=0,
                          topPadding=0,
                          id='diagnos_frame',
                          showBoundary=0)
        fio_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            fio_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        fio_frame.addFromList([fio_inframe], canvas)

        # Постоянное место жительства
        live_text = [Paragraph('{}, {}'.format(p_address, p_phone), style)]
        live_frame = Frame(88 * mm,
                           144 * mm,
                           115 * mm,
                           9 * mm,
                           leftPadding=0,
                           bottomPadding=0,
                           rightPadding=0,
                           topPadding=0,
                           id='diagnos_frame',
                           showBoundary=0)
        live_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            live_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        live_frame.addFromList([live_inframe], canvas)

        # Место работы
        work_text = [Paragraph('{}'.format(p_work), style)]
        work_frame = Frame(108 * mm,
                           138.5 * mm,
                           95 * mm,
                           5 * mm,
                           leftPadding=0,
                           bottomPadding=0,
                           rightPadding=0,
                           topPadding=0,
                           id='diagnos_frame',
                           showBoundary=0)
        work_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            work_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        work_frame.addFromList([work_inframe], canvas)

        # Кем направлен больной
        who_directed_text = [
            Paragraph('{}'.format(primary_reception_data['who_directed']),
                      style)
        ]
        who_directed_frame = Frame(77 * mm,
                                   129.5 * mm,
                                   126 * mm,
                                   7 * mm,
                                   leftPadding=0,
                                   bottomPadding=0,
                                   rightPadding=0,
                                   topPadding=0,
                                   id='diagnos_frame',
                                   showBoundary=0)
        who_directed_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            who_directed_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        who_directed_frame.addFromList([who_directed_inframe], canvas)

        # Диагноз направившего учреждения координаты
        diagnos_directed_text = [
            Paragraph(
                '{}'.format(primary_reception_data['diagnos_who_directed']),
                styleJustified)
        ]
        diagnos_directed_frame = Frame(27 * mm,
                                       98 * mm,
                                       175 * mm,
                                       9 * mm,
                                       leftPadding=0,
                                       bottomPadding=0,
                                       rightPadding=0,
                                       topPadding=0,
                                       id='diagnos_frame',
                                       showBoundary=0)
        diagnos_directed_inframe = KeepInFrame(
            175 * mm,
            10 * mm,
            diagnos_directed_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        diagnos_directed_frame.addFromList([diagnos_directed_inframe], canvas)

        # Диагноз при поступлении координаты
        diagnos_entered_text = [
            Paragraph('{}'.format(primary_reception_data['diagnos_entered']),
                      styleJustified)
        ]
        diagnos_entered_frame = Frame(27 * mm,
                                      83 * mm,
                                      175 * mm,
                                      10 * mm,
                                      leftPadding=0,
                                      bottomPadding=0,
                                      rightPadding=0,
                                      topPadding=0,
                                      id='diagnos_frame',
                                      showBoundary=0)
        diagnos_entered_inframe = KeepInFrame(
            175 * mm,
            10 * mm,
            diagnos_entered_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        diagnos_entered_frame.addFromList([diagnos_entered_inframe], canvas)

        # клинический диагноз координаты
        diagnos_text = [
            Paragraph('{}'.format(clinical_diagnos), styleJustified)
        ]
        diagnos_frame = Frame(27 * mm,
                              22 * mm,
                              175 * mm,
                              55 * mm,
                              leftPadding=0,
                              bottomPadding=0,
                              rightPadding=0,
                              topPadding=0,
                              id='diagnos_frame',
                              showBoundary=0)
        diagnos_inframe = KeepInFrame(175 * mm, 55 * mm, diagnos_text)
        diagnos_frame.addFromList([diagnos_inframe], canvas)

        # представитель пациента
        p_agent = None
        agent_status = ''
        agent = ''
        if ind_card.who_is_agent:
            p_agent = getattr(ind_card, ind_card.who_is_agent)
            agent_status = ind_card.get_who_is_agent_display()
        if p_agent:
            agent_data = p_agent.get_data_individual()
            agent_fio = agent_data['fio']
            agent_phone = ','.join(agent_data['phone'])
            agent = f"{agent_status}: {agent_fio}, тел.:{agent_phone}"

        agent_text = [Paragraph('<u>{}</u>'.format(agent), styleRight)]
        agent_frame = Frame(27 * mm,
                            5 * mm,
                            175 * mm,
                            7 * mm,
                            leftPadding=0,
                            bottomPadding=0,
                            rightPadding=0,
                            topPadding=0,
                            id='diagnos_frame',
                            showBoundary=0)
        agent_inframe = KeepInFrame(175 * mm, 10 * mm, agent_text)
        agent_frame.addFromList([agent_inframe], canvas)
        canvas.restoreState()

    # Получить все услуги из категории операции
    styleTO = deepcopy(style)
    styleTO.alignment = TA_LEFT
    styleTO.firstLineIndent = 0
    styleTO.fontSize = 9.5
    styleTO.leading = 10
    styleTO.spaceAfter = 0.2 * mm

    # Таблица для операции
    opinion_oper = [[
        Paragraph('№', styleTO),
        Paragraph('Название операции', styleTO),
        Paragraph('Дата, &nbsp час', styleTO),
        Paragraph('Метод обезболивания', styleTO),
        Paragraph('Осложнения', styleTO),
        Paragraph('Оперировал', styleTO),
    ]]

    hosp_operation = hosp_get_operation_data(num_dir)
    x = 0
    operation_result = []
    for i in hosp_operation:
        operation_template = [''] * 6
        x += 1
        operation_template[0] = Paragraph(str(x), styleTO)
        operation_template[1] = Paragraph(
            f"{i['name_operation']} <br/><font face=\"PTAstraSerifBold\" size=\"8.7\">({i['category_difficult']})</font>",
            styleTO)
        operation_template[2] = Paragraph(
            i['date'] + '<br/>' + i['time_start'] + '-' + i['time_end'],
            styleTO)
        operation_template[3] = Paragraph(i['anesthesia method'], styleTO)
        operation_template[4] = Paragraph(i['complications'], styleTO)
        operation_template[5] = Paragraph(i['doc_fio'], styleTO)
        operation_result.append(operation_template.copy())

    opinion_oper.extend(operation_result)

    t_opinion_oper = opinion_oper.copy()
    tbl_o = Table(
        t_opinion_oper,
        colWidths=(
            7 * mm,
            62 * mm,
            25 * mm,
            30 * mm,
            15 * mm,
            45 * mm,
        ),
    )
    tbl_o.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.black),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 2.1 * mm),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))

    def later_pages(canvas, document):
        canvas.saveState()
        # Заключительные диагнозы
        # Основной заключительный диагноз
        final_diagnos_text = [
            Paragraph('{}'.format(final_diagnos), styleJustified)
        ]
        final_diagnos_frame = Frame(27 * mm,
                                    230 * mm,
                                    175 * mm,
                                    45 * mm,
                                    leftPadding=0,
                                    bottomPadding=0,
                                    rightPadding=0,
                                    topPadding=0,
                                    showBoundary=0)
        final_diagnos_inframe = KeepInFrame(
            175 * mm,
            50 * mm,
            final_diagnos_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        final_diagnos_frame.addFromList([final_diagnos_inframe], canvas)

        # Осложнения основного заключительного диагноза
        other_diagnos_text = [
            Paragraph('{}'.format(other_diagnos), styleJustified)
        ]
        other_diagnos_frame = Frame(27 * mm,
                                    205 * mm,
                                    175 * mm,
                                    20 * mm,
                                    leftPadding=0,
                                    bottomPadding=0,
                                    rightPadding=0,
                                    topPadding=0,
                                    showBoundary=0)
        other_diagnos_inframe = KeepInFrame(
            175 * mm,
            20 * mm,
            other_diagnos_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        other_diagnos_frame.addFromList([other_diagnos_inframe], canvas)

        # Сопутствующие основного заключительного диагноза
        near_diagnos_text = [
            Paragraph(
                '{}'.format(
                    near_diagnos.replace('<', '&lt;').replace('>', '&gt;')),
                styleJustified)
        ]
        near_diagnos_frame = Frame(27 * mm,
                                   181 * mm,
                                   175 * mm,
                                   20 * mm,
                                   leftPadding=0,
                                   bottomPadding=0,
                                   rightPadding=0,
                                   topPadding=0,
                                   showBoundary=0)
        near_diagnos_inframe = KeepInFrame(
            175 * mm,
            20 * mm,
            near_diagnos_text,
            vAlign='TOP',
        )
        near_diagnos_frame.addFromList([near_diagnos_inframe], canvas)

        # Таблица операции
        operation_text = [tbl_o]
        operation_frame = Frame(22 * mm,
                                123 * mm,
                                170 * mm,
                                40 * mm,
                                leftPadding=0,
                                bottomPadding=0,
                                rightPadding=0,
                                topPadding=0,
                                showBoundary=0)
        operation_inframe = KeepInFrame(175 * mm,
                                        40 * mm,
                                        operation_text,
                                        hAlign='CENTRE',
                                        vAlign='TOP',
                                        fakeWidth=False)
        operation_frame.addFromList([operation_inframe], canvas)

        canvas.setFont('PTAstraSerifBold', 8)
        hospital: Hospitals = request_data["hospital"]

        hospital_name = hospital.safe_short_title

        canvas.drawString(55 * mm, 12 * mm, '{}'.format(hospital_name))
        canvas.drawString(
            55 * mm, 9 * mm,
            '№ карты : {}; Номер истории: {}'.format(p_card_num, hosp_nums))
        canvas.drawString(
            55 * mm, 6 * mm, 'Пациент: {} {}'.format(patient_data['fio'],
                                                     patient_data['born']))
        canvas.line(55 * mm, 11.5 * mm, 200 * mm, 11.5 * mm)

        canvas.restoreState()

    doc.build(objs, onFirstPage=first_pages, onLaterPages=later_pages)
    pdf = buffer.getvalue()
    buffer.close()

    return pdf