Q: Deserializing JSON object to runtime type in WinRT (C#) I have a small WinRT client app to my online service (Azure Web Service). The server sends a JSON encoded object with (with potential additional metadata) to the client and the client's responsibility would be to deserialize this data properly into classes and forward it to appropriate handlers.
Currently, the objects received can be deserialized with a simple
TodoItem todo = JsonConvert.DeserializeObject<TodoItem>(message.Content);

However, there can be multiple types of items received. So what I am currently thinking is this:

*

*I include the type info in the header serverside, such as "Content-Object: TodoItem"

*I define attributes to TodoItem on the client side (see below)

*Upon receiving a message from the server, I find the class using the attribute I defined.

*I call the deserialization method with the resolved type

(Example of the attribute mentioned in 2.)
[BackendObjectType="TodoItem"]
public class TodoItem

My problem with this approach however is the Type to Generics in the deserialization as I can't call:
Type t = ResolveType(message);
JsonConvert.DeserializeObject<t>(message.Content);

I tried finding some solutions to this and getting method info for the DeserializeObject and calling it using reflection seemed to be the way to go. However, GetMethod() does not exist in WinRT and I was not able to find an alternative I could use to retrieve the generic version of the DeserializeObject (as fetching by the name gives me the non-generic overload). I don't mind using reflection and GetMethod as I can cache (?) the methods and call them every time a message is received without having to resolve it every time.
So how do I achieve the latter part and/or is there another way to approach this?

A: Alright, I feel like this was not really a problem at all to begin with as I discovered the DeserializeObject(string, Type, JsonSerializerSettings) overload for the method. It works splendidly. However, I would still like to hear some feedback on the approach. Do you think using attributes as a way to resolve the type names is reasonable or are there better ways? I don't want to use the class names directly though, because I don't want to risk any sort of man-in-the-middle things be able to initialize whatever.

A: Just a few minutes ago we have posted the alternative way to do what you want. Please look here, if you will have any questions feel free to ask:
Prblem in Deserialization of JSON

A: Try this
http://json2csharp.com/

Put your Json string here it will generate a class
then
 public static T DeserializeFromJson<T>(string json)
    {
        T deserializedProduct = JsonConvert.DeserializeObject<T>(json);
        return deserializedProduct;
    }

 var container = DeserializeFromJson<ClassName>(JsonString);


Q: From plugin to theme folder: reference not working as expected In a given wordpress theme, the javascipt and jquery files are located at /functions/extended/js/
Originally they were located in a plugin folder. I need to retarget the references to a folder within the theme.
my previous code:
if ( is_front_page() ) :
    wp_dequeue_script( 'theme-script' );
    wp_dequeue_script( 'theme-slider' );

    wp_enqueue_script( 'xt-script', plugin_dir_url( __FILE__ ) . 'js/functions.js', array( 'jquery', 'xt-slider' ), '' , true );

    wp_enqueue_script( 'xt-slider', plugin_dir_url( __FILE__ ) . 'js/jquery.flexslider-min.js', array( 'jquery', ), '' , true );
    wp_localize_script( 'xt-slider', 'featuredSliderDefaults', array(
        'prevText' => __( 'Previous', 'xt' ),
        'nextText' => __( 'Next', 'xt' )
    ));

    if ( get_theme_mod( 'xt_slider_transition' ) ==  'slide' ) :
        wp_enqueue_script( 'xt-slider-slide', plugin_dir_url( __FILE__ ) . 'js/slider-slide.js', array( 'jquery', ), '' , true );

    elseif ( get_theme_mod( 'xt_slider_transition' ) == 'fade' ) :
        wp_enqueue_script( 'xt-slider-fade', plugin_dir_url( __FILE__ ) . 'js/slider-fade.js', array( 'jquery', ), '' , true );
    endif;

endif;

my new code doesn't seem to do the trick; the scripts don't get loaded:
if ( is_front_page() ) :
    wp_dequeue_script( 'theme-script' );
    wp_dequeue_script( 'theme-slider' );

    wp_enqueue_script( 'xt-script', bloginfo('template_url') . '/functions/extended/js/functions.js', array( 'jquery', 'xt-slider' ), '' , true );

    wp_enqueue_script( 'xt-slider', bloginfo('template_url') . '/functions/extended/js/jquery.flexslider-min.js', array( 'jquery', ), '' , true );
    wp_localize_script( 'xt-slider', 'featuredSliderDefaults', array(
        'prevText' => __( 'Previous', 'xt' ),
        'nextText' => __( 'Next', 'xt' )
    ));

    if ( get_theme_mod( 'xt_slider_transition' ) ==  'slide' ) :
        wp_enqueue_script( 'xt-slider-slide', bloginfo('template_url') . '/functions/extended/js/slider-slide.js', array( 'jquery', ), '' , true );

    elseif ( get_theme_mod( 'xt_slider_transition' ) == 'fade' ) :
        wp_enqueue_script( 'xt-slider-fade', bloginfo('template_url') . '/functions/extended/js/slider-fade.js', array( 'jquery', ), '' , true );
    endif;

endif;

I've tried get_bloginfo, bloginfo, and get_template_directory_uri(). No bun.

A: You are looking for get_template_directory()


Q: Get the price of tokens with web3js I wanted to know if it was possible to get the price of tokens with web3.js
For example I would like to get the price of WBTC on Uniswap and on SushiSwap
If you have any documentation or tutorials I'm interested
Thanks in advance

A: If you need any price information you could use chainlink oracle. Here is official docs for evm data feeds;
https://docs.chain.link/docs/using-chainlink-reference-contracts/ .
For a simple implementation example you can take a look at freeCodeCamp.org 's 32-hour course/lesson4 on youtube.
Also you can take a look at uniswap API ;  https://docs.uniswap.org/protocol/V2/reference/API/entities

A: If you want it to be compatible across multiple chains and multiple DEXs, the easiest way I could think of is to call the router by using the method getAmountsOut.
router.methods.getAmountsOut(amountIn, [inAddress, outAddress]).call()

amountIn would be 1 * Math.pow(10, inAddress token decimals)
inAddress is WBTC address
outAddress is USDC address
The output will be:
100000000,22397189858

Output[0] is amount in. Output[1] is amount out. You then have to divide that by
(1 * Math.pow(10, out address decimal), where you will get WBTCprice: 22397.189858
The only caveat of doing this method is that you need to know the stable pair that exist on that dex. Some dex may use WBTC/USDT, some may use WBTC/USDC.


Q: How to update SQLite table based on checkbox value in Flask? I have SQLite database which contains data regarding products such as Product Name, Description and Like which shows if the user likes or doesn't like the product.
A user search for different products which populate a table with the name, description and a checkbox which is clicked in if the value of Like is 1 in the database and unchecked if not.
I have implemented the button through (as seen in index.html)
<form method = "POST"> <input type="checkbox" name="like" {% if product.like == 1 %} checked {% else %} {% endif %}>
I now want the user to be able to check and uncheck the boxes in the table, and then press a button that updates the Like column in the database, how do I do this?
(I can't even access the value of the button in app.py. When trying print(requests.form['like']) on the line after name=requests.form['search'] it returns BadRequestKeyError: The browser sent a request that this server could not understand. KeyError: 'like')
app.py
...
product = []
@app.route('/', methods = ['POST'])
def index():
   name = None
   if request.method == 'POST':
     name = request.form['search']
     if name is not None or name != "":
        query_product = Products.query.filter(Products.productname==name).first()
        if (query_product is not None) and (query_product not in product):
            company.append(query_company)
   print(company, file = sys.stderr)
   return render_template('index.html', companies = company)

Products class
class Products(db.Model):
   index = db.Column(db.Integer(), primary_key = True)
   productname = db.Column(db.String(), primary_key = False)
   description = db.Column(db.String(), primary_key = False)
   like = db.Column(db.Integer(), primary_key = False)
   ...more columns

index.html

{% extends 'base.html' %}
{% block content %}
    <form method="POST">
        <input type="text" placeholder="Search for Product.." name="search">
        <button type="submit" name="submit">Search</button> <button type="submit" name="update" value = company.index style = margin-left:45%>Update</button>

                        Product Name
                        Description
                        Like

                {% for product in products %}

                        {{ product.productname}}
                         {{ product.description }}
                        <form method = "POST"> <input type="checkbox" name="like" {% if product.like == 1 %} checked {% else %} {% endif %}></form>
                {% endfor %}

{% endblock %}

A: I guess you need to do this with javascript and add another route to your backend which then updates the database.
maybe something like this, if it should happen automatically:
<input type="checkbox" onchange="updateLike('productId', this.checked)">

or you could add a button which sends the request to the server.
<input type="checkbox" name="like"/>
<button onclick="updateLike('productId', document.querySelector('input[name=like]').checked)">confirm</button>


Q: Why isn't this MySQL statement working? I have a table Seats with the columns, SeatID, Date, RouteID and Seats. The primary key is SeatsID. The value of seats is 50, and I wish to subtract whatever the user has entered into $tickettotal from 50 and then insert the new value.
The user also has to enter which RouteID and Date they wish to travel. I want these to be inserted into the Seats table along with the new value of Seats.
If another user enters the same Date and RouteID then the Seats should be updated. Otherwise a new record should be inserted with SeatID, Date, RouteID, and the reduced value for Seats.
I thought this statement should do it but I keep getting errors back such as
Can't find string terminator '"' anywhere before EOF, although when i put " at the end of the statement i just get another syntax error line 108, near ""') ON DUPLICATE KEY UPDATE Seats=Seats-'"$tickettotal" .

Update
I now have it inserting fine, although on a duplicate entry of both Date and RouteID it doesn't update Seats: it still just inserts a new value. The Seats - $tickettotal isn't working either.
$dbh->do("INSERT INTO $Stable(Date,RouteID)
VALUES ('$Tdate','$Rid') ON DUPLICATE KEY UPDATE Seats=Seats-'$tickettotal'");

Update Answer
Because i didn't have a unique column, I created one using both date and RouteID added together so.
$Tdate =~ s/-//gi;
$dateandrid = $Tdate . $Rid;

The first line removes the hyphens and the second puts them together. Then using these statements get the desired effect i wanted.
$dbh->do("INSERT INTO $Stable(RouteAndDate,Date,RouteID) VALUES    ('$dateandrid','$Tdate','$Rid') ON DUPLICATE KEY UPDATE Seats=Seats");
$dbh->do("INSERT INTO $Stable(RouteAndDate,Date,RouteID) VALUES ('$dateandrid','$Tdate','$Rid') ON DUPLICATE KEY UPDATE Seats=Seats-'$tickettotal'");

A: You must avoid SQL Injection with parameter binding:
$dbh->do( qq{
     INSERT INTO $Stable(Date, RouteID)
     VALUES (?, ?)
     ON DUPLICATE KEY UPDATE Seats=Seats-?
     },
     undef,
     $Tdate, $Rid, $tickettotal
);


Q: Dynamic view dimensions for different Devices
Possible Duplicate:
How to write app for multiple screen resolutions?

My Question is Suppose application has to  rendered views dynamically for different devices say for example
1.Frame to display images (eg 90 X 90 for mdpi 140 X 140 for hdpi)
  2.ListView Height (eg 120X 120 for mdpi 150 X 150 for hdpi)
Like if i have many things to set according to device size
What is the standard way to implement this instead of hard coding values in respective activities?
 Before loading application i want to calculate all dynamic view dimensions
Thanks in advance. Any Sample code really helps me a lot

A: use images in drawable-mdpi and drawable-hdpi
for different height set use dimension in values
res/values-mdpi/dimen.xml
res/values-hdpi/dimen.xml

dp, dip will change according to the density.
use px in different dimension


Q: Abline not fitting to barplot I'm trying to ad an abline plot to a barplot grafic but the x-axis don't seem to fit.
So this is my code:
#Emotion im FB darstellen
y <- FB$Ärger[FB$Episode ==1] #Subset erstellen
data <- factor(y, levels = c(1:7)) #faktorisieren
table(data)
#barplot erstellen
barplot(table(data),
        main = "E1 - Ärger",
        xlab = "Rating",
        ylab = "Häufigkeit",
        ylim = c(0, 8))

#w2v integrieren
abline(v=1,col="red")
abline(v=2,col="red")
abline(v=3,col="red")
abline(v=4,col="red")
abline(v=5,col="red")
abline(v=6,col="red")
abline(v=7,col="red")
abline(v=index(my.xts.data)[endpoints(my.xts.data, "days")]

And this is what I get:

Ideally abline(v=1) should show up in the center of the first bar and so one.
But the scale of the abline x-axis seems to be shorter than the one of the barplot.
Any ideas how I cold make both of them fit?
Thanks a lot!
Lorena

A: The problem is that barplot automatically adds a space of 0.2 before each bar. This means you have two options. One is to get rid of the spaces, then subtract 0.5 from the value of each abline to make it match up to the centre of the bar:
Rating <- factor(c(1, 2, 2, 2, 2, 2, 3, 3, 4, 5), levels = 1:7)
barplot(table(Rating),
        main = "E1 - Ärger",
        xlab = "Rating",
        ylab = "Häufigkeit", space = 0)
abline(v = seq(7) - 0.5, col = "red")

The other option is to leave the spaces by starting at 0.7 and incrementing by 1.2 for each bar:
barplot(table(Rating),
        main = "E1 - Ärger",
        xlab = "Rating",
        ylab = "Häufigkeit")
abline(v = seq(0.7, 8, 1.2), col = "red")

To make this easier, you could define a function that does the calculation for you:
add_vlines <- function(x) abline(v = (x * 1.2) - 0.5, col = "red")

So you could just do:
add_vlines(1:7)

to get the lines you are looking for.


Q: How to make a textbox clickable can anyone help how to make a textbox clickable while it is a in readonly state.
I want to do is a can click my textboxes just like a button because i have plans to it.
<input type="text" readonly value="Click me" id="clickme" />

A: You can use:
$('#clickme').click(function(){
  // logic here
});

A: Like this, readonly catch click, disabled doesen't . fiddle
$(function(){
    $('#clickme').on('click', function(){
        alert(1)
    })
})

A: <input type="text" readonly value="Click me" id="clickme" onClick="myFunction()"/>

<script>
    ...
    function myFunction(){
        // Your function
    }
    ...
</script>

A: Just add a click event to the textbox.
JQuery:
$("#clickme").click(function(){
alert("do something");
});

JsFiddle

A: Jquery is awesome if you include it.
$('#clickme').on('click', function(e) {
   // do something
});

A: Without more information as to what, precisely, you want to do, I'd suggest:
$('#clickme').on('click', function(){
    // to allow for editing of contents:
    $(this).prop('readonly', false);
});

JS Fiddle demo.
Or:
$('#clickme').on('click', function(){
    // to do something if this is readonly:
    if (this.readOnly) {
        // for example:
        console.log('this input is readonly');
    }
});

JS Fiddle demo.

A: You can use jquery as
$('#clickme').click(function(){
 alert('clickable');
// Your Method.
});

Add few style too
#clickme
{
cursor:pointer;
cursor:hand;
}

Check out this Demo

A: you can use onclick function, like
    <input type="text" readonly value="Click me" id="clickme" onclick="myfunction()" />

A: $('#clickme').click(function(){
  alert('Textbox is clicked)
});


Q: How do i count the number of attempts the user took to guess the correct sequence I would like to count the number of attempts the user took to guess the correct color sequence. I have been stuck for quite a while as I tried to add a count function but it kept being stuck at 0. I'm new at python so any help is much appreciated (I had to remove some unrelated part of the code because I cant fit it in the box (at compare_list section)
import random

colours = ['PINK', 'BLUE', 'YELLOW', 'RED']
random_colours = []
colours_input = []

#handles the users input and stores in a list (colours_input)
def user_input():
    i = 1
    while i < 5:
        a = input('Please enter your selected colours in sequence, colour ' + str(i) + ': ').upper()
        while a not in colours:
            print('Please only type the colours in the range (PINK, BLUE, YELLOW, RED) ')
            a = input('Please enter a valid colour ' + str(i) + ': ').upper()

        colours_input.append(a)
        i+=1
    print('Your selected colour sequence is: ' + str(colours_input))

#Automatically generate four random colours for the user to guess
def randomize():
    for i in range (0,4):
        random_colours.append(random.choice(colours))

#To check 2 variables: Correct colour in the correct place and correct colour but in the wrong place
def compare_list():
    correct_place = 0
    if random_colours[0] == colours_input[0]:
        colour_1 = True
        correct_place = correct_place + 1
    else:
        colour_1 = False
    if random_colours[1] == colours_input[1]:
        colour_2 = True
        correct_place = correct_place + 1
    else:
        colour_2 = False
    if random_colours[2] == colours_input[2]:
        colour_3 = True
        correct_place = correct_place + 1
    else:
        colour_3 = False
    if random_colours[3] == colours_input[3]:
        colour_4 = True
        correct_place = correct_place + 1
    else:
        colour_4 = False

    print('Correct colour in the correct place: ' + str(correct_place))

    while correct_place == 4:
        print('Congratulations! You are a master mind')
        break
    else:
        colours_input.clear()
        user_input()
        compare_list()

A: You're going to want to have some driver code, that acts as the entry point to your program and orchestrates how functions will be called. Currently you are doing this in your compare_list() function, simply move this code (and change it a bit, there were some mistakes with the while loop structure) to a new function.
Typically this code is placed in a main function. In your case, it could look something like:
def main():
    random_colours = []
    colours_input = []

    randomize() # you forgot to call this in your code
    while True:
        user_input()
        if compare_list():
            print('Congratulations! You are a master mind')
            break # exit the program

        colours_input.clear()

Then, we just need to refactor our compare_list() function so that it only compares the lists, and returns the result of the comparison (I just return a boolean representing whether the comparison was successful, but you could also return the correct_place value for example).
def compare_list():
    correct_place = 0
    if random_colours[0] == colours_input[0]:
        colour_1 = True
        correct_place = correct_place + 1
    else:
        colour_1 = False
    if random_colours[1] == colours_input[1]:
        ...

    print('Correct colour in the correct place: ' + str(correct_place))

    return correct_place == 4 # returns True, if correct_place equals 4, False otherwise

Now, in our main function, we can count how many times we have run this main  loop for each user attempt:
def main():
    random_colours = []
    colours_input = []

    attempts = 0
    while True:
        attempts += 1
        user_input()
        randomize()
        if compare_list():
            print('Congratulations! You are a master mind')
            print('It only took you {} attempt{}!'.format(attempts, 's' if attempts > 1 else "")
            break # exit

        colours_input.clear()
        random_colours.clear()

Now we simply call the main() function in our file to run the driver code. Typically this is done in an if block that runs only if your script is being run directly as opposed to being imported by something else:
...

def compare_list():
    ...

def main():
    ...

if __name__ == "__main__":
    main()

(You can read up about this practice here: What does if __name__ == “__main__”: do?)
A final refactor would be to reduce the use of global variables. You should aim to make your functions units of code that operate on input(s) and return output(s). Designing your functions so that they mutate global variables to produce a result is an anti-pattern.
Here's one way to refactor it:
import random

colours = ('PINK', 'BLUE', 'YELLOW', 'RED') # this is okay since it is a constant. We can make it an immutable tuple to clearly indicate that this is read-only.
# remove the following global variables
# random_colours = []
# colours_input = []

#handles the users input and stores in a list (colours_input)
def user_input():
    colours_input = [] # define the variable here. We create a new list that this function will populate, then return it

    for i in range(5):
        ...

    print('Your selected colour sequence is: ' + str(colours_input))
    return colours_input # return the populated list

def randomize():
    random_colours = [] # define the variable here. Similar to above.

    for i in range (0,4):
        random_colours.append(random.choice(colours))

    return random_colours # return it to the caller

# we take in the lists to compare as parameters to the function, rather then getting them from the global scope
def compare_list(colours_input, random_colours):
     ... # (everything else is the same)

def main():
    random_colours = randomize()

    # colours_input = []

    attempts = 0
    while True:
        attempts += 1
        colours_input = user_input()
        if compare_list(colours_input, random_colours): # pass the returned lists in as arguments to this function call
            print('Congratulations! You are a master mind')
            print('It only took you {} attempt{}!'.format(attempts, 's' if attempts > 1 else "")
            break # exit the program

        # no need to clear this anymore. We get a new list from each call to user_input()
        # colours_input.clear()