python 3.x – Wrap functions which run in two threads in one class

My application consist of two threads.
One – is running http server with aiohttp

Second thread is asking another web resource about current currency.

So there are two threads with asyncronous requests.
But I was struggling to run my http-server in another thread, I found solution here

I need two threads here because server must be asyncronous and request to another server must also be asyncronous , that is why two threads.

My code is below:

import asyncio
import json
import threading

from aiohttp import web, ClientSession
from random import randint


common_dict = {
    'USD': 60,
    'EUR': 70,
    'RUB': 1,
}


async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()



# GETTING CURRENCY
# Thread number one
async def fetch_currency():
    """ Here we get currency once in 30 seconds from 
      https://www.cbr-xml-daily.ru/daily_json.js)

    """
    while True:
        async with ClientSession() as session:
            await asyncio.sleep(30)
            data = await fetch(session,
                               'https://www.cbr-xml-daily.ru/daily_json.js')

            response_from_server = json.loads(data, strict=False)
            try:
                usd_value = response_from_server('Valute')('USD')('Value')
            except Exception:
                print(Exception)
            else:
                if usd_value != common_dict.get('USD'):
                    await spit_data_into_console(currency=usd_value)
                    common_dict('USD') = usd_value


#SERVER IN THREAD
# THREAD NUMBER TWO
def aiohttp_server():
    """
    REST API for http-server

    """
    def get_usd_currency(request):
        common_dict('USD') = randint(1, 10)
        return web.Response(text=str(common_dict('USD')))

    def get_euro_currency(request):
        return web.Response(text=str(common_dict('EUR')))

    def get_rub_currency(request):
        return web.Response(text=str(common_dict('RUB')))

    # ...
    # many APIs

    app = web.Application()
    app.add_routes(
        (web.get('/usd/get', get_usd_currency),
         # ...
         # many APIs
         web.get('/eur/get', get_euro_currency),
         web.get('/rub/get', get_rub_currency),
         )
    )
    runner = web.AppRunner(app)
    return runner


def run_server(runner):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    loop.run_until_complete(runner.setup())

    site = web.TCPSite(runner, 'localhost', 8080)
    loop.run_until_complete(site.start())

    loop.run_forever()


# Possible(?) Thread number three
async def spit_data_into_console(currency=None,
                                 total_amount=None):

    """one time in a minute spit data into stdout if currency has changed"""

    await asyncio.sleep(60)
    if currency is not None:
        print('Value of {} has changed'.format(currency))


def main():
    # оthread for http-server
    t = threading.Thread(target=run_server, args=(aiohttp_server(),))
    t.start()

    # thread for json-response from another server
    loop = asyncio.get_event_loop()
    loop.run_until_complete(fetch_currency())


if __name__ == '__main__':
    main()

This is working example.

But it is not looking good. For example I have common_dict as a global variable to exchange data between threads (I must use mutex here probably).

And my server as a

def aiohttp_server():
    """
    REST API for http-server

    """
    def get_usd_currency(request):
        common_dict('USD') = randint(1, 10)
        return web.Response(text=str(common_dict('USD')))

    def get_euro_currency(request):
        return web.Response(text=str(common_dict('EUR')))

    def get_rub_currency(request):
        return web.Response(text=str(common_dict('RUB')))

    # ...
    # many APIs

    app = web.Application()
    app.add_routes(
        (web.get('/usd/get', get_usd_currency),
         # ...
         # many APIs
         web.get('/eur/get', get_euro_currency),
         web.get('/rub/get', get_rub_currency),
         )
    )
    runner = web.AppRunner(app)
    return runner


def run_server(runner):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    loop.run_until_complete(runner.setup())

    site = web.TCPSite(runner, 'localhost', 8080)
    loop.run_until_complete(site.start())

    loop.run_forever()

does not look perfect because I am using here a function (aiohttp_server()) and then define my APIs in this function. What if I need many APIs?

Since this code serves to a task of handling currency I would prefer to wrap it into a class, but I do not know if it is appropriete here or not.

And if it is then how can I create (probably!) a class and then run two different tasks in two threads…?

Thank you very much in advance!

Javascript – How to split and wrap lines in a section in each section?

I use "Detect Browser Wrapped Lines Using Javascript" to enclose each line in a line . However, I have a problem when more than one element needs to be split and wrapped.

For example: If I want to split and wrap more than one section, like:

    1 - Lorem Khaled Ipsum is a major key to success. They will try to close the door on you, just open it. Watch your back, but more importantly when you get out the shower, dry your back, it’s a cold world out there.
    2 - The key to more success is to get a massage once a week, very important, major key, cloth talk. Eliptical talk.

It will take up all the text .content, divide and wrap it in a and duplicate them. So the put looks like this;

    1 - Lorem Khaled Ipsum is a major key to success. They will try to close the door on you, just open it. Watch your back, but more importantly when you get out the shower, dry your back, it’s a cold world out there. 2 - The key to more success is to get a massage once a week, very important, major key, cloth talk. Eliptical talk.
    1 - Lorem Khaled Ipsum is a major key to success. They will try to close the door on you, just open it. Watch your back, but more importantly when you get out the shower, dry your back, it’s a cold world out there. 2 - The key to more success is to get a massage once a week, very important, major key, cloth talk. Eliptical talk.

Anyway, how to split and enclose each line in a in each section and not creating duplicate content?

Working example: https://codepen.io/openbayou/pen/poJwaXv

JS code:

$(".emails .multi-items").each(function (i) {
var $cont = $('.emails .multi-items .message-contain #content')
var text_arr = $cont.text().split(' ');
for (i = 0; i < text_arr.length; i++) {
  text_arr(i) = '' + text_arr(i) + ' ';
}

$cont.html(text_arr.join(''));
$wordSpans = $cont.find('span');

var lineArray = (),
  lineIndex = 0,
  lineStart = true,
  lineEnd = false

  $wordSpans.each(function(idx) {
      var pos = $(this).position();
      var top = pos.top;

      if (lineStart) {
          lineArray(lineIndex) = (idx);
          lineStart = false;

      } else {
          var $next = $(this).next();

          if ($next.length) {
              if ($next.position().top > top) {
                  lineArray(lineIndex).push(idx);
                  lineIndex++;
                  lineStart = true
              }
          } else {
              lineArray(lineIndex).push(idx);
          }
      }

  });


 //console.log( lineArray)
 for (i = 0; i < lineArray.length; i++) {
  var start = lineArray(i)(0),
      end = lineArray(i)(1) + 1;

  /* no end value pushed to array if only one word last line*/
  if (!end) {
      $wordSpans.eq(start).wrap('')
  } else {
      $wordSpans.slice(start, end).wrapAll('');
  }

 };
});

Signature – Sign P2SH Wrap P2PK

I am creating a redemption script that includes P2PK like https://en.bitcoin.it/wiki/BIP_0016

----- PK -----
cQJx6metUEMqLWXQAAn9tYQGjwpnVX256HR8fEh15HWk2Yiihff8

 ---------- Redeem Script --------- 
2102c937a3cae20375f939f6ec64b11a6c713c8553de88bc1619d2b538053526155bAC

 ---------- scriptPubKey --------- 
2ad60d5cfbf32018e843d81e74ed9d54aed09ded

 ---------- ADDRESS P2SH --------- 
2Mw9inwxkrzXjKFNe5deFQbsHR4yoRpQgZo

If I manually sign the transaction, it works.
If I use something like that

TX_DATA=$(bitcoin-cli createrawtransaction '({"txid":"'$TXID'","vout":'$VOUT',"scriptPubKey":"'$SCRIPTPUBKEY'","redeemScript":"'$REDEEM'"})' '({"'$ADDR_DEST'":'$AMOUNT'})')

bitcoin-cli signrawtransactionwithkey $TX_DATA '("'$PK'")'

I get this error

"Unable to sign input, invalid stack size (possibly missing key)"

My Bitcoin core is 0.19.0 and generate P2SH-encased Segwit by default.
I can use signrawtransactionwithkey only when used getnewaddress ?
Where can I find the default template?

How do I wrap a line in Android Snippet Marker?

Thank you for contributing to the stack overflow in Portuguese!

  • Make sure you Answer the question. Go into your solution in detail and share what you have discovered.

But avoid

  • Ask for clarification or details on other answers.
  • Make statements based only on your opinion; Point references or previous experiences.

For more information, see our tips on writing good answers.

Hooks – wrap post images with a link, not with a figure (image_send_to_editor does not work)

The new version of WP encompasses all of the images in one post with one figure Element instead of a href, I tried to use this hook in my functions.php

if( is_admin() ) {
add_filter( 'image_send_to_editor', 'wp_link_wrap', 10, 8 );  
function wp_link_wrap( $html, $id, $caption, $title, $align, $url, $size, $alt ) {
    return ''. $html .'';
}}

but nothing has changed.

Struct or class to wrap an int if 0 is not a valid value

You need a requirement review.

  1. Not every integer value is valid

This is a very weak requirement. There is no computer for which this is not the case. Some ints are long enough to fill your hard drive. So it doesn't help much to have this requirement here. Think about what this should mean or remove it altogether.

  1. The valid values ​​are not a predefined discrete set, so enumeration is not an option

This is useful information

  1. Two objects with the same value are always considered the same

We call these objects of value. You don't have to have getters and setters.

  1. The validity of a value should be checked in the constructor

That leaves out changeable beans. No setters. Immutable objects are still allowed. The weak thing is that it's about design and implementation. It doesn't tell us why it has to be a constructor.

  1. 0 is not a valid value

This is absolutely incomplete. Is there a max? A min? Do all existing objects need to be checked again if the dynamic set of valid values ​​changes? Is this set unique for every object?

They also behave as if you should be able to do this through a parameterless constructor, but have never specified this as a requirement or justified that requirement.

The most elaborate design for it that I would maintain would be a class that has an int value and an immutable test rule object that can be reused but not even changed. Only allow creation if the validation rules allow it.

This way you can react to changes and still keep everything unchangeable. Remember this is simply revised because these requirements are so vague. By spending 5 minutes to clarify the requirements, 5 days of code can be saved.

Wrap an object and change the enclosed object through the wrapper

I want to wrap some objects around to give them additional properties. However, when I interact with the properties that are defined for the base class, let the original, unpacked object change.

I have a class hierarchy like:

public class SomeBase
{
    public SomeObj Source { get; set; }
    public SomeObj Target { get; set; }

    public SomeBase(SomeObj source, SomeObj target)
    {
        Source = source;
        Target = target;
    }
}

public class SomeDerrived : SomeBase
{
    public SomeDerrived(SomeBase s) : base(s.Source, s.Target) {}
}

public class SomeObj {}

If I have a program like this:

SomeBase s = new SomeBase(new SomeObj(), new SomeObj());
SomeDerrived sd = new SomeDerrived(s);
WriteLine(s.Source.GetHashCode());
WriteLine(sd.Source.GetHashCode());  //The two hash codes are identical as I'd have expected.
sd.Source = new SomeObj();
WriteLine(s.Source.GetHashCode());  //Why does this not have the hash code of `sd`?
WriteLine(sd.Source.GetHashCode());

Is there a way to achieve this?

How SomeDerrived is a SomeBase I would have thought the properties would be one and the same?

Algorithm – Rust dynamic programming: word wrap

I solved this problem: https://leetcode.com/problems/word-break

Assuming a non-empty string s and a dictionary wordDict that contains a list
Use non-empty words to determine whether s can be segmented into a
Sequence of one or more dictionary words separated by spaces.

Note:

The same word in the dictionary can be reused several times in the
Segmentation. You can assume that the dictionary does not contain any duplicates
Words. Example 1:



impl Solution {
    fn dfs(i: usize, words: &HashSet, cur_word: &str, cache: &mut HashMap, n: usize, orig:&str) -> bool {

        if i == n {
            return true;
        }
        if cache.contains_key(&i) {
            return *cache.get(&i).unwrap();
        }
        if words.contains(cur_word) {
            cache.insert(i, true);
            return true;
        }
        let mut res = String::from("");
        for k in i..n {
            let s = orig.chars().nth(k).unwrap();
            res.push(s);
            if words.contains(&res) && Self::dfs(k + 1, &words, orig.get(k+ 1..).unwrap_or_default(), cache, n, orig) {
                cache.insert(i, true);
                return true;
            }
        }
        cache.insert(i, false);
        return false;
    }
    pub fn word_break(s: String, word_dict: Vec) -> bool {
        let set = word_dict.into_iter().collect::>();
        let mut cache = HashMap::new();
        Self::dfs(0, &set, "", &mut cache, s.len(), &s)
    }
}

Please ignore the useless ones Solution struct – this is part of the interface of the website for the solution.

I'm pretty angry like mine dfs Function is structured – I pass too many arguments.

In Python, I would have simply created a recursive nested function that would have captured outer variables. rust does not allow recursive closings because a closure is an unnamed structure. So I had to create an argument-heavy function.

How do I make my code more idiomatic?