text:
Q: Giving Code for what is probably homework I just answered this question: https://stackoverflow.com/questions/19909488/print-the-2-smallest-numbers-in-a-loop#comment29622280_19909488
If you look at the three answers we clearly have three levels of helping what is probably a homework question. My pseudocode pythonish answer, Someone's really pseudocode answer, and someone who just wrote out the code. Which is preferable?

A: There is no one right answer.  It depends greatly on the personal preferences of individuals, and the specifics of any given question.  People are free to vote based on what they feel is appropriate, so in a general sense the "best" option is entirely up to the voting practices of the community.  That can change based on the tags your in, the time of day the question is posted, luck, the time of year, the quality of the question, the quality of the answer, the popularity of the question, and any number of other factors.
It's an issue that is reasonably controversial; there are many people on different sides, and a such there is no clear singular community consensus across the network.  You'll simply need to determine on your own what you want to do, along with what "the community" of active members for that particular question is likely to think appropriate.
Of course, the fact that a question is related to a homework problem as virtually no direct effect on its quality.  There are fantastic questions that happen to be related to a homework problem someone has, and there are terrible questions related to a homework problem someone has.
Likewise, there are factors to answer quality beyond just whether there is a complete code answer.  An answer that describes the solution without code can be good or bad, based on what it describes, how well it describes it, etc.  An answer with a full code solution can also vary in quality; it may be a really good solution to the problem, or it may not be.  This adds yet another (major) variable to consider when evaluating such answers.

A: I often see a lot of negative attitude toward homework questions, and I don't understand it. Personally, I'm of the opinion that a lot of the people coming here for help with homework questions are simply trying to pass a course and don't really care how much they actually learn about Java or C++ or whatever they're learning. Now, you could argue that they're lazy and didn't do their own research from the course materials, but I feel more compassion for the students than I do for the people who are getting paid to solve the same kinds of problems, yet come to a community such as ours to essentially sub-contract for them.
I'm almost always an explicit-code-answer type of guy; very rarely opting for pseudo-code or wordy answers. What I tend to do when it is clear the OP is not overly familiar with the technology is do more around the code in terms of comments and/or naming variables and objects more explicitly. This can help a newbie (whether they are in school or not), and is only annoying to the very strict experienced coder who prefers tight, terse code.
In the end, the answers provided to a homework question will help the OP in one way, but they'll help future readers in other ways. They may even help the OP in a different way later when they revisit the question. For the most part my recommendation is to ignore whether the question seems to be homework or not (or at least don't think negatively about it), and focus on the question. Whether they are a student or not, someone who has little experience in a specific technology still has little experience in a specific technology, and the same type of guidance can be helpful.


text:
Q: Null Pointer Exception In Paypal Express Checkout And also give blank page In Express Checkout that total is display but product name and other details not showing
    and give error NUll pointer Exception and add the '=' then showing  blank
public HashMap CallShortcutExpressCheckout(String item, String paymentAmount, String currencyCodeType, String paymentType,
                                            String returnURL, String cancelURL,
                                            HttpSession session)
{
    session.setAttribute("paymentType", paymentType);
    session.setAttribute("currencyCodeType", currencyCodeType);

    /*
    Construct the parameter string that describes the PayPal payment
    the varialbes were set in the web form, and the resulting string
    is stored in $nvpstr
    */
    String nvpstr = "&PAYMENTREQUEST_0_AMT=" + paymentAmount + "&PAYMENTREQUEST_0_PAYMENTACTION=" + paymentType + "&ReturnUrl=" + URLEncoder.encode( returnURL ) + "&CANCELURL=" + URLEncoder.encode( cancelURL ) + "&PAYMENTREQUEST_0_CURRENCYCODE=" + currencyCodeType;

         nvpstr=nvpstr+ "&L_PAYMENTREQUEST_0_NAME0="+item;
         nvpstr=nvpstr+ "&L_PAYMENTREQUEST_0_QTY0="+item;
          nvpstr=nvpstr+ "&L_PAYMENTREQUEST_0_AMT0="+item;
         System.out.println("item="+item);
    /*
    Make the call to PayPal to get the Express Checkout token
    If the API call succeded, then redirect the buyer to PayPal
    to begin to authorize payment.  If an error occured, show the
    resulting errors
    */
        System.out.println("amountpay="+paymentAmount);
        HashMap nvp = httpcall("SetExpressCheckout", nvpstr);
    String strAck = nvp.get("ACK").toString();
    if(strAck !=null && strAck.equalsIgnoreCase("Success"))
    {
        session.setAttribute("TOKEN", nvp.get("TOKEN").toString());
    }

    return nvp;
}

and showing blank expresscheckout.jsp

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use 'file_get_contents('php://input');' to return data on localhost I Am using localhost server to store response from mpesa Daraja gateway api but unfortunately I can get back the response using
file_get_contents('php://input');

Any help especially on integration of Daraja Mpesa gateway for C2B

A: First thing is that when working with the Daraja API you need your endpoint to be publicly accessible. Localhost is only accessible from your machine which means Daraja won't be able to send over data to you.
So this means you may need to have a domain eg https://www.mycompany.com and then your url https://www.mycompany.com/api/gateway that points to your hosted application.
Also, to get the contents of the request that the callback receives, you use:
$data=Json_decode(file_get_contents('php://input'));

Whose details you can go through like so:
$transactionTime = $data['TransTime'];


text:
Q: How to use Queue correctly with ProcessPoolExecutor in Python? I am trying to use a queue to load up a bunch of tasks and then have a process pool setup go at it where each process pops-out a task out of the queue and works on it.  I am running into problems in that the setup is not working.  Something is blocking the processes from getting started and I need help in figuring out the bug.  E.g. the queue is filled up correctly, however, when the individual process runs, it doesn't start processing the task subroutine.
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 30 17:08:42 2022

@author: Rahul
"""

import threading
import queue
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
import multiprocessing as mp
import time

q = queue.Queue()

# some worker task

def worker(id, q):

    print(f'{id}:: Worker running', flush=True)
    while q.unfinished_tasks > 0:
        item = q.get()
        print(f'{id}::Working on {item}', flush=True)
        print(f'{id}::Finished {item}', flush=True)
        q.task_done()

        print(f'{id}::Sleeping. Item: {item}', flush=True)

        time.sleep(0.1)
    print(
        f'We reached the end.  Queue size is {q.unfinished_tasks}', flush=True)

def main():

    print('running main')
    # Send thirty task requests to the worker.
    for item in range(30):
        q.put(item)

    # Confirm that queue is filled
    print(f'Size of queue {q.unfinished_tasks}')
    id = 0

    # start process pool
    with ProcessPoolExecutor(max_workers=4) as executor:
        executor.map(worker, [1, 2, 3, 4], [q, q, q, q])

    # Block until all tasks are done.
    q.join()
    print('All work completed')

if __name__ == "__main__":
    main()

This creates the following output and is stuck after that, no control of keyboard etc., have to shutdown IDE and restart.
running main
Size of queue 30

A: For multiprocessing, there are 2 ways to uses a queue.
You have to either

*

*use queue as shared global via initializer parameter or

*use a manager

See Python multiprocessing.Queue vs multiprocessing.manager().Queue() for examples for how to set it up.
Below is an example of using a manager of OP's use case.
A few things to highlight:

*

*Uses manager.Queue() which helps share the queue across different processes.

*Typically for worker process, it's better to use while True loop that terminates when seeing some SENTINEL value. This will allow the worker to wait even if all current work is done, in case there are more work coming. It's also more robust than q.empty() check (or q.unfinished_tasks, which doesn't exist in multiprocessing version)

*Using the SENTINEL approach requires adding 4 SENTINEL values, 1 for each process, after all the tasks.

*with ProcessPoolExecutor ... context manager is blocking, meaning it will wait until all Processes exits before continuing to the next lines. You may consider using explicit shutdown for non-block statments, e.g.
executor = ProcessPoolExecutor(max_workers=4)
executor.map(...)
executor.shutdown(wait=False)

Now finally, the example solution:
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
import multiprocessing as mp
import time

# some worker task
SENTINEL = 'DONE'

def worker(id, q):

    print(f'{id}:: Worker running', flush=True)
    # better to use the while True with SENTINEL
    # other methods such as checking 'q.empty()' may be unreliable.
    while True:
        item = q.get()
        if item == SENTINEL:
            q.task_done()
            break
        print(f'{id}::Working on {item}', flush=True)
        print(f'{id}::Finished {item}', flush=True)
        q.task_done()

        print(f'{id}::Sleeping. Item: {item}', flush=True)

        time.sleep(0.1)
    print(
        f'We reached the end.', flush=True)

def main():

    print('running main')
    # Send thirty task requests to the worker.
    with mp.Manager() as manager:
        q = manager.Queue()

        for item in range(30):
            q.put(item)

        # adding 4 sentinel values at the end, 1 for each process.
        for _ in range(4):
            q.put(SENTINEL)

        # Confirm that queue is filled
        print(f'Approx queue size: {q.qsize()}')
        id = 0

        # start process pool
        with ProcessPoolExecutor(max_workers=4) as executor:
            executor.map(worker, [1, 2, 3, 4], [q, q, q, q])

        print('working')
        # Block until all tasks are done.
        q.join()
        print('All work completed')

if __name__ == "__main__":
    main()


text:
Q: Dynamic Name Routing / Dynamic Route Matching in VueJS I have some products that are being iterated over and being displayed. I'd like to use the images of the products as links to the specific page of each individual product. I want each product page to pull from the same template, substituting the props with the appropriate product details.
An example url for a product would be something like: /shop/product/name-of-product
Here is the relevant code:
<template>

        <router-link :to={ name: 'avaibleProducts' , params: { id: 1 }}>

        </router-link>

{{ item.name }}

€{{ item.price }}

            <button class="add-to-cart">ADD TO CART</button>

</template>

Router/Index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Shop from '../views/Shop.vue'
import Product from '../views/Product'

Vue.use(VueRouter)

  const routes = [
  {
    path: '/shop',
    name: 'Shop',
    component: Shop
  },
  {
    path: '/product/:id',
    name: Product,
    component: Product
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

A: hey :)) first you must add a unique property to your product list like a uuid or anything, also you can use id property but its not a good method

step 1:
you must add uuid propery to your product object :
{
      name: 'PLASTIC BAGS 3-PACK v1',
      price: 0.33,
      image: require('@/assets/plastic-bag-pack.jpg'),
      description:
        'First version plastic bags pack containing 3 HQ assets. Make sure to get yours today.',
      id: 1,
      uuid: 'prd-001' // pay attention to this line
    },

step 2:
you need to create an computed propery
computed: {
  showProduct() {
    const id = this.$route.params.id;
    const product = this.avaibleProducts.find((p) => p.uuid == id);
    return product;
  },

step 3:
and in your template you can access it like this:

{{ showProduct.name }} - {{ showProduct.price }}

step 4:
you can load single product in this route:
/product/prd-001

the above route return your first product in your available products state
step 5:
change your this line in your Router/Index.js file

name: Product
and put it in single quotation like this :
name: 'Product'
and change your router-link like this :
<router-link :to="{name: 'Product' , params:{ id: product.uuid }}">{{ product.name}}</router-link>

well done!

A: You're missing one important part in your router index.js file. You need to enable prop passing in the Product components
Router/Index.js
{
  path: '/product/:id',
  name: Product,
  component: Product,
  props: true
}

Now you can actually pass props to your routes via a <router-link> element.
Now all you have to do is pass the appropriate props to the component. You can do this by emulating an API call on the component's created() hook.
I recommend you make a JSON file that you put somewhere in your src directory with all the details for the products. Instead of importing your image via webpack, just do it statically by putting the images in public/images.
You then need to make sure that the id is a unique URL-valid string if you want to use it as the param in the URL as you specified. It would look something like this:
@/assets/json/productList.json:
[
    {
        "id": "plastic-bag",
        "name": "PLASTIC BAGS 3-PACK v1",
        "price": 0.33,
        "image": "/images/products/1.jpg",
        "description": "First version plastic bags pack containing 3 HQ assets. Make sure to get yours today."
    },
    ....
]

Then in your Product.vue component:
<template>

{{ product.name }}

${{ product.price }} USD

{{ product.description }}

</template>


text: Q: Docked Control doesn't always have same width as parent I have a panel docked to the top of another panel.  The parent panel lives inside of an Actipro DockManager.  If I resize the parent panel, everything is fine.  If I resize the form, the child panel doesn't end up with the same width as the parent panel.  Any idea how to fix this?  I tried manually setting the Width on the child panel and that is ignored.


text:
Q: Share Anglar2 codebase between web app and hybrid app I want to create an mobile app based on my existing Angular2 web app codebase. For my understanding there is two options of doing so which is Ionic2 and NativeScript.
I looked in to both and I see at least one problem - it is seams to be both of them have their own specific UI elements so I cant just take my codebase and wrap it somehow with Ionic2 or NativeScript. Also I discovered that Ionic2 does not support Component Router so in that case I would need to implement my routing using Ionic2 NavigationCompenent, etc.
May be someone already done something like that and can share some thoughts?

A: I can't speak much on ionic but people are doing it with NativeScript, here is one seed project to get started with https://github.com/NathanWalker/angular-seed-advanced . Both frameworks are going to come with pros/cons. If you really want to share all of your app with mobile and web ionic is your easiest option because it's all web based whereas NativeScript uses native ui rendering so the ui cannot be the same as the web, however with the seed setup most of your logic/services are shared and you only need to implement the ui for both. Some work has been done on the idea of using one markup file for native ui and web DOM but it's difficult to map a good native ui to a web ui that scales for all screens. I imagine it will definitely be a thing in the future but right now I've not seen much on this specific topic. Another benefit of ionic is their PWA support they've added recently. You should probably give both a quick try at a small app and see how you like the shared logic, etc and what gives you the best outcome.


text:
Q: Does jQuery accept parameters in any order? I've noticed when using jQuery.fn.animate() I can pass some or all of the parameters (css for animation, callback function, easing, and duration) in any order to the function.
Looking into the function source code, it starts like this:
function (prop, speed, easing, callback) {
    var empty = jQuery.isEmptyObject(prop),
        optall = jQuery.speed(speed, easing, callback),
.
.
.

And then it starts to actually process the information passed. So, obviously the css properties object has to be first in the chain - otherwise it will break the function (or is it?). But then look at jQuery.speed:
function (speed, easing, fn) {
    var opt = speed && typeof speed === "object" ? jQuery.extend({},
    speed) : {
        complete: fn || !fn && easing || jQuery.isFunction(speed) && speed,
        duration: speed,
        easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
    };
.
.
.

Obviously this is where the magic's at. But jQuery's approach to cutting down on parentheses and braces makes it difficult for me to breakdown all those conditionals. Can you please simplify the jQuery.speed function? Thanks.

A: Written in a more comprehensive way, this is what jQuery does:
function (speed, easing, fn) {
    var opt;
    if (speed && typeof speed === "object") {
        opt = jQuery.extend({}, speed);
    }
    else {
        var complete_p,
            duration_p = speed,
            easing_p;

        // Find out what's the "complete" property
        if (fn) complete_p = fn;
        else {
            if (easing) {
                complete_p = easing;
            }
            else {
                if (jQuery.isFunction(speed)) {
                    complete_p = speed;
                }
            }
        }

        // Find out what's the "easing" property
        if (fn) {
            easing_p = easing;
        }
        else {
            if (easing) {
                if (!jQuery.isFunction(easing)) {
                    easing_p = easing;
                }
            }
        }

        opt = {
            complete: complete_p,
            duration: duration_p,
            easing: easing_p
        };
    }
.
.
.

So... yes, it's doing some checks to allow you to change the order. I wouldn't rely on it, though.


text:
Q: My app.py is not able to recive the request at the backend and getting 404 error My app.py is
app=flask.Flask(__name__,template_folder='templates')
@app.route('/')

def main():
 if flask.request.method == 'GET':
    return(flask.render_template('main.html'))
 if flask.request.method == 'POST':
    news = flask.request.form['article']
    input_variables = pd.DataFrame([[news]],
                                   columns=['news'],
                                   dtype=object)
    prediction = model.predict(input_variables)[0]
    return flask.render_template('main.html',
                                 original_input={'news':news},
                                 result=prediction,
                                 )
if __name__=='__main__':
 app.run()

<!doctype html>

    <title>News Classification Model</title>

<form action="{{ url_for('main') }}" method="POST">
    <fieldset>
        <legend>Input values:</legend>
        Enter any news:
        <input name="news" type="object" required>

        <input type="submit">
    </fieldset>
</form>

    {% if result %}
        {% for variable, value in original_input.items() %}
            {{ variable }} : {{ value }}
        {% endfor %}

 Predicted Class of the news :

{{ result }}

    {% endif %}

I think I'm having a problem in html file so any help would be great to rectify it.
I'm new to Flask so i'm not able to solve it.My main.html file I've taken from someone so thats why i guess I'm having this Problem.

A: You need to delete the blank line between these two lines:
@app.route('/')

def main():


text:
Q: Show that the field is conservative, and find its associated scalar field. A field $\vec{F}(\vec{r})$ is defined as $\displaystyle{\vec{F} = \frac{\vec{r}}{r^n}}$ with $n \neq 0$. Show that the field is conservative, and find its associated scalar field.
I understand the concepts of vector field, my problem starts by solving for $\displaystyle{\vec{F} = \frac{\vec{r}}{r^n}}$. Thanks in advance...


text:
Q: Short way to keep all fields in mySQL? In MySQL I'm creating a table ts2 from another table ts1 by only keeping the distinct rows with the following command
CREATE TABLE ts2 AS SELECT DISTINCT
name, date_of_birth, position, email, ... FROM ts1;

Is there a short way to indicate that I want to pick all fields?

A: You can use the * operator:
CREATE TABLE ts2 AS SELECT DISTINCT * FROM ts1;

A: There are two ways to do this.
If you just want the data, use CREATE TABLE ... AS SELECT DISTINCT *, like this:
CREATE TABLE ts2 AS SELECT DISTINCT * FROM ts1;

If you want the indexes as well, do two queries:
CREATE TABLE ts2 LIKE ts1;
INSERT INTO ts2 SELECT DISTINCT * FROM ts1;


text:
Q: 'Incorrect syntax near 'X3'. The identifier that starts with........is too long I trying to save datagridview data to the database. Here is my code.
Dim cmd3 As New SqlCommand("insert into Tab_sale_bill (Col_Date, Col_Time, Col_Bill_Id, Col_Bill_Ty, Col_Inv_No, Col_Acc_Ty, Col_Acc_Name, Col_Bar, Col_Pro_Name, Col_Color_Code, Col_Bra, pricategory, Col_HSN, Col_Sec, Col_Cate, Col_Subcate, Col_Pack_Size, Col_Quan, Col_Unit, COL_MRP, Col_Re_Rate, Col_C_Rate, Col_Rate_Ex, Col_Rate_Diff, Col_Dis_Val, Col_Inv_Val, Col_Taxable_Val, Col_Tax_Rate, Col_CGST, Col_SGST, Col_P_Rate, Col_P_Val, Col_Total_Val, Col_Freight, Col_Oth_Dis, Col_Bill_Amnt, Col_Multiunit, factoronoff, netdiscount, marginvalue, marginper, Col_Comm_Typ, Col_Comm, Col_Item_Id, Col_Cust_Name, Col_Mob, Col_GSTIN, Col_Cust_Add, Col_Narr, Col_User_Id, Col_User) values('" & row.Cells(0).Value & "', @time, '" & row.Cells(2).Value & "', '" & row.Cells(3).Value & "', '" & row.Cells(4).Value & "', '" & row.Cells(5).Value & "', '" & row.Cells(6).Value & "', '" & row.Cells(7).Value & "', '" & row.Cells(8).Value & "', '" & row.Cells(9).Value & "', '" & row.Cells(10).Value & "', @pricri, '" & row.Cells(12).Value & "', '" & row.Cells(13).Value & "', '" & row.Cells(14).Value & "', @subcate, '" & row.Cells(16).Value & "', '" & row.Cells(17).Value & "', '" & row.Cells(18).Value & "', @mrp, @rerate, @crate, @rateex, '" & row.Cells(23).Value & "', @disper, @totval, @taxableval, '" & row.Cells(27).Value & "', @cgst, @sgst, @prate, @pval, '" & row.Cells(32).Value & "', '" & row.Cells(33).Value & "', '" & row.Cells(34).Value & "', @debit, '" & row.Cells(36).Value & "', '" & row.Cells(37).Value & "', '" & row.Cells(41).Value & "', '" & row.Cells(42).Value & "', '" & row.Cells(43).Value & "', '" & row.Cells(48).Value & "', '" & row.Cells(49).Value & "', '" & row.Cells(50).Value & "', '" & row.Cells(51).Value & "', '" & row.Cells(52).Value & "', @gst, @address, '" & row.Cells(55).Value & "', '" & row.Cells(56).Value & "', '" & row.Cells(57).Value & "')", conn3)
                        cmd3.Parameters.Add("@debit", SqlDbType.NVarChar).Value = Decimal.Parse(row.Cells(35).Value)
                            cmd3.Parameters.Add("@time", SqlDbType.Time).Value = Date.Now.ToString("hh:mm:ss")
                        cmd3.Parameters.Add("@pricri", SqlDbType.NVarChar).Value = row.Cells(11).Value
                        cmd3.Parameters.Add("@subcate", SqlDbType.NVarChar).Value = row.Cells(15).Value
                        cmd3.Parameters.Add("@gst", SqlDbType.NVarChar).Value = row.Cells(53).Value
                        cmd3.Parameters.Add("@address", SqlDbType.NVarChar).Value = row.Cells(54).Value
                        cmd3.Parameters.Add("@mrp", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(19).Value)), 6)
                        cmd3.Parameters.Add("@rerate", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(20).Value)), 6)
                        cmd3.Parameters.Add("@crate", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(21).Value)), 6)
                        cmd3.Parameters.Add("@rateex", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(22).Value)), 6)
                        cmd3.Parameters.Add("@disper", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(24).Value)), 6)
                        cmd3.Parameters.Add("@totval", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(25).Value)), 6)
                        cmd3.Parameters.Add("@taxableval", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(26).Value)), 6)
                        cmd3.Parameters.Add("@cgst", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(28).Value)), 6)
                        cmd3.Parameters.Add("@sgst", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(29).Value)), 6)
                        cmd3.Parameters.Add("@prate", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(30).Value)), 6)
                        cmd3.Parameters.Add("@pval", SqlDbType.NVarChar).Value = Math.Round((Decimal.Parse(row.Cells(31).Value)), 6)
                        conn3.Open()
                        cmd3.ExecuteNonQuery()
                            conn3.Close()

This causes the error as:
'Incorrect syntax near 'X3'.
The identifier that starts with '', '30', 'PCS', @mrp, @rerate, @crate, @rateex, '0', @disper, @totval, @taxableval, '18', @cgst, @sgst, @prate, @pval, '140049',' is too long. Maximum length is 128.
Unclosed quotation mark after the character string '', '30', 'PCS', @mrp, @rerate, @crate, @rateex, '0', @disper, @totval, @taxableval, '18', @cgst, @sgst, @prate, @pval, '140049', '.'
Can you please tell me what is this error indicate. What can I solved this error.
Thanks in Advance.


text:
Q: How to use ng2-bootstrap datepicker as popup mode? I use ng2-bootstrap date-picker in my project. I want to show the date-picker when I am click on the calendar icon. And also want to hide it when select a date.
Date:

   <input type="text" value="{{ getDate() | date:'dd-MMMM-yyyy' }}" class="datepicker">

             <datepicker [(ngModel)]="Date" [minDate]="minDate" [showWeeks]="false"></datepicker>

And my component is as follows
private opened:boolean = false;
public open():void {
    this.opened = !this.opened;
}

public getDate():number {
    return this.Date && this.Date.getTime() || new Date().getTime();
}

private clearDate() {
    this.Date = null;
}

Now the issue was it will be closed only when I click on the icon again.

A: Just separate "open" and "close" in two functions (now your "open" is actually "toggle"). Then use (not yet documented) event selectionDone($event) to close your datepicker.
<datepicker [(ngModel)]="dt" [minDate]="minDate" [showWeeks]="false" (selectionDone)="onSelectionDone($event)"></datepicker>

and in your code:
public onSelectionDone(a) {
    this.close();
}


text:
Q: how can i set different menus on different pages in wordpress? I am trying to setup diffrent menu for diffrent page like.
In Home Page I need to main menu link like this
Home
Product
Services
Contact Us

In product Page
Home
Product
Services
Contact Us

I am using one page theme so please help me for this logic development.
Thanks

A: It is impossible to answer this question without seeing more code, but in an abstract sense this can be achieved quite easily. As Yatendra pointed out, you need to register two menus as so in your functions.php file:
function register_my_menus() {
  register_nav_menus(
    array(
      'home-menu' => __( 'Header Menu' ),
      'product-menu' => __( 'Product Menu' )
    )
  );
}
add_action( 'init', 'register_my_menus' );

Then, you will want to embed something similar into your header.php where you navigation should like usding the is_page_template() and wp_nav_menu() functions.
<?php

    if (is_page_template( 'products.php' )) // change this to the name of the file
    {
         // load the product-menu
         wp_nav_menu( array( 'theme_location' => 'product-menu' ) );
    }
    else
    {
         // load the header-menu
         wp_nav_menu( array( 'theme_location' => 'header-menu' ) );
    }
?>

However, for a one-page theme, something like a parallax theme you are better not putting in a conditional and wrapping them in
 tags and show and hiding them with jQuery. However, we would really need to see more code.
Codex References:

*

*is_page_template()

*Registering a Menu


text:
Q: Hiding/unhiding excel sheets based of a matrix I have a macro that works, but it's not very effective and could be done a lot better.
I simply have a list with all sheet names(they could change so it needs to be dynamic) in one row and in the next row I have a "yes/no" answer that displays if the sheet should be hidden or not.
Example:
Sheet 1, sheet2, sheet3, sheet4,
yes, yes, no, yes
My code so far:
Sub HidingSheets()

'Checking the first sheet
'-------------------------------------------------------------------------------------------
Sheets(Worksheets("Sheet1").Range("E9").Value).Visible = True
Sheets(Worksheets("Sheet1").Range("E9").Value).Activate

If ActiveSheet.Range("A1") = "NO" Then
    ActiveSheet.Visible = False
End If
'-------------------------------------------------------------------------------------------

'Checking the second sheet
'-------------------------------------------------------------------------------------------
Sheets(Worksheets("Sheet1").Range("F9").Value).Visible = True
Sheets(Worksheets("Sheet1").Range("F9").Value).Activate

If ActiveSheet.Range("A1") = "NO" Then
    ActiveSheet.Visible = False
End If
'-------------------------------------------------------------------------------------------

End Sub

I basically do it manually per every sheet instead of a loop, and this also requires that I need the "yes/no" displayed in every sheet(the "if" formula checking if A1 = "no"). The "yes/no" that s displayed in cell A1 is taken from the matrix that I explained before.
Note: The matrix could be "tranposed", the direction of it doesn't matter.
Thank you in advance if you can help me.
My second attempt is this:
Sub Hiding2()

Dim i As interger

For i = 1 To 10

    a = ActiveSheet.Range("E9").Value

    If Offset(a(1, 0)) = YES Then
        Sheets(a).Visible = True
    Else
       Sheets(a).Visible = False
    End If

Next i

End Sub

But I dont know how to reference the cells that I need, and then get them to move over for every "i".

A: You can use Cells instead of Range. With it, you can use column numbers to iterate over some range of columns. There is also other possibilities to exit the code... it depends on the data in your worksheet.
Sub Hiding()
    Dim sh as Worksheet, col as Integer
    For col = 5 to 100
        shName = Worksheets("Sheet1").Cells(9, col).Value
        On Error GoTo TheEnd ' in case there is no such sheet
        Set sh = Worksheets(shName)
        If UCase(sh.Range("A1").Value) = "YES" Then
            sh.Visible = xlSheetVisible
        Else
            sh.Visible = xlSheetHidden
        End If
    Next col
    TheEnd:
End Sub

A: Sub HideWorksheets()
    Dim Cell As Range
    Dim Data As Range: Set Data = Worksheets("Sheet1").Range("E9:N9")
    On Error Resume Next
    For Each Cell In Data
        Worksheets(Cell.value).Visible = IIf(Cell.Offset(1, 0) = "YES", xlSheetHidden, xlSheetVisible)
    Next Cell
End Sub


text:
Q: Getting Eclipse to open .html in text-editor by default? Eclipse Juno keeps opening my HTML files in a embedded web-browser, rather than in an embedded syntax-highlighting editor.
I have installed:

*

*Web Page Editor

*Eclipse Web Developer Tools

*PyDev for Eclipse

Specifically see the screenshot of my install applications.
I need it to work with Django templates + any other Python templates with HTML + normal HTML+JS files.
How do I find this editor, and select it as default?

A: Select Window -> Preferences from the main Eclipse menu.
Select General -> Editors -> File Associations from the Preferences menu.

For .htm and .html, left click on the extension in the upper view.  Left click on the Add button to the right of the lower view to add one or more HTML editors.  Left click on your favorite HTML editor and left click on the Default button to make it the default editor.
If the extension you want is missing, left click on the Add button to the right of the upper view to add the extension.

A: I had a similar problem.
Once I installed the html editor (thanks to CgodLEY), still my html files wouldnt show up with that editor.
Solution? Right click on the html/htm file, go to "open with" and select "HTML editor". Fortunately that solve everything...

A: For those still finding their way here, yes, do add an HTML editor to Eclipse as CgodLEY suggests, if you're having this problem. However, even if you already have an HTML editor in your Eclipse installation, consider installing CodeMix for a superlative HTML editing experience - take a look at the differences here.

A: If you want to add an HTML editor to Eclipse:

*

*Go to Help -> Install New Software

*Choose the site http://download.eclipse.org/releases/your_eclipse_version

*Type the filter text Web Page Editor

*There should be one result. Check off the box and press the Finish button.

Now you should have the option to choose the HTML editor when opening files by right-clicking, Open With -> HTML Editor.
If you want to always use the HTML editor to open HTML files then go to the Eclipse preferences -> General -> Editors -> File Associations. Select the extension up top (e.g. *.htm, *.html) then select the HTML editor in the bottom pane and press the Default button.

A: Now, there's a Django-aware template editor available for free:
http://eclipse.kacprzak.org/
I installed it in Eclipse Kepler / Django 1.6, it's working fine for me.
Note: if you previously opened a specific .HTML file with some other editor, you need to go back to the project view, right click on the .HTML file, select 'open with...' and explicitly select Django editor.

A: To answer the opening of your question: Note that Eclipse will use the built-in web-browser to view html files if you are opening them outside of a project, as in "File->Open File ...", when that file isn't part of a project.
I just created a dummy project, and now the html files are correctly opened with the editor selected in my preferences. Success!

A: Nothing worked and I had begun getting an unrelated error on startup with a troubleshooting step requiring reinstall.
This time I downloaded Eclipse for Mobile Developers, and since then I have added my other packages and it's all working fine =).
None of the editors work the way I want them to though, however I have ended up with Django-Editor (which is slightly better than Aptana's one).


text:
Q: Error Connecting to Google Datastore outside GAE Hi I am trying to connect to Datastore using the below command
DatastoreOptions options = DatastoreOptions.builder().projectId("project-id").authCredentials(AuthCredentials.createForJson(new FileInputStream("c:\GoogleCredentials\.json"))).build();
I have created a folder GoogleCredentials in my C: Drive and downloaded the Service account's JSON keyfile into this folder
But I am getting the below error:
Line 38, Column 67: No applicable constructor/method found for actual parameters "java.lang.String"; candidates are: "com.google.cloud.ServiceOptions$Builder com.google.cloud.ServiceOptions$Builder.projectId(java.lang.String)"


text:
Q: Delegate translations to non developers I'm using Django 1.5 and would like to delegate the translation to people who are not developer.
I imagine a simple web editor displaying readonly msgid with each related editable msgstr.
This editor would allow to select the target language and do the validations on submit.
Is there something similar existing ?

A: I believe  that your requirements are covered by django-rosetta (https://github.com/mbi/django-rosetta).
Copying from the project README:

Rosetta is a Django application that eases the translation process of
  your Django projects.

*

*Database independent

*Reads and writes your project's gettext catalogs (po and mo files)

*Installed and uninstalled in under a minute

*Uses Django's admin interface CSS


text:
Q: MATCH AGAINST gives 0 for 'Depression' against 'Depressed' My MATCH AGAINST is otherwise working, I am just curious what is going on under the hood that
SELECT `rfv`, MATCH `rfv` AGAINST('Depressed') FROM `rfvs`

returns a match score of 0 when rfv is 'Depression'.  I just think it should be higher. Clearly not a perfect match, but the best match it gives me against a list of medical complaints (no lie) is 'Anal-rectal itching'

A: What you're describing is a feature of some search engines called "stemming". It means different forms of the same word match. Like plurals, gerunds, conjugations, or other suffixes.
MySQL's fulltext indexing does not support stemming. They have a worklog on file, but it hasn't been implemented. https://dev.mysql.com/worklog/task/?id=2423 The worklog is unassigned, and it's marked for implementation in MySQL 7.1, which dates the worklog from quite a few years ago, because there never was a MySQL 7.x version released. They skipped from 5.7 directly to 8.0.
The feature request was filed in 2005: https://bugs.mysql.com/bug.php?id=15085 Feel free to vote for that issue by logging in to the bug tracker and clicking "Affects Me". After you do that, you may have to wait between 2 and 20 years for it to be implemented.
Or you could copy your searchable data into another search engine that supports stemming, for example Apache Solr.


text:
Q: I want to execute a piece of code when the window is closed in vsts? I want to delete a query when the user closes the query tab in TFS server which is open .
I am using typescript to develop vsts extensions . here i want to delete one query when user closes a window

A: No such event that can capture the query tab/query result close action in VSTS.


text:
Q: Same index in Pandas Dataframe, delete NaN rows How can I get the data from this dataframe into 2 rows only, deleting the NaN? (I concated 3 different Dataframes into a new one, showing averages from another Dataframe)enter image description here
This is what i want to achieve:
0 Bitcoin (BTC) 36568.673315   5711.3.059220.      1.229602e+06
1 Ethereum (ETH) 2550.870272   670225.756425       8.806719e+05

It can either be in a new dataframe or using the old one. Thank you so much for ur help :)

A: Try this:
df.bfill(axis ='rows', inplace=True) # filling the missing values
df.dropna(inplace=True) # drop rows with Nulls


text:
Q: Solving the PDE $u_{xx}-3u_{xt}-4u_{tt}=0$ I am aware that the PDE is already solved in this thread.
But, I want to know how that person got from $u_x+u_t=g(4x+t)$ to $2u_{x'}=g(4x+t)$ by using the change of variables $x′=x+t,t′=x−t$. I don't understand the $2u_{x'}$ part. Finally, after doing all that, how do you arrive at the final solution?

A: I prefer not following external links unless I have to, so I hope the following might help.
Since $a^2-3 ab-4b^2=(a+b)(a-4b)$ we can (not rigorously) write: $$ \left( \frac{\partial^2}{\partial x^2} -3 \frac{\partial^2}{\partial x \partial t}-4 \frac{\partial^2}{\partial t^2}\right)u=\left( \frac{\partial}{\partial x} +\frac{\partial}{\partial t}\right)\left( \frac{\partial}{\partial x} -4\frac{\partial}{\partial t}\right)u=0$$
And obtain two 1st order PDEs:
$$\left( \frac{\partial}{\partial x} +\frac{\partial}{\partial t}\right)u_1=0$$
$$\left( \frac{\partial}{\partial x} -4\frac{\partial}{\partial t}\right)u_2=0$$
Where we are searching for the solution as:
$$u(x,t)=A u_1(x,t)+B u_2(x,t)$$
By the form of the above equations, it's clear that we should search for solutions as:
$$u_1(x,t)=f(x-t)$$
$$u_2(x,t)=g(4x+t)$$
You can check all of this by direct substitution in the original PDE.


text:
Q: Force JSON.stringify() to emit NaN / Infinity or JS JSON lib that does so I'm looking into the feasibility of adding NaN/Infinity support to a pre-existing scientific application that uses JSONRPC for client/server interactions. Many JSON libs do handle (optionally in some cases) NaNs and Infs, for example:

*

*Python json reads and writes

*Java Jackson reads but writes strings instead of barewords

*Java GSON reads and writes

*Javascript can read
I'm aware that NaN and Infinity are not supported in the JSON spec, and am aware of the related questions. However, AFAICT the question of whether there's some way of coercing the native JS JSON.stringify() method to emit NaN/Infinity or, alternately, there's a JS JSON library that does the same is unanswered. A subtle difference to the referenced questions, perhaps, but important. So far I've been unable to discover such a method or library, so here I am. Is the only option writing one's own JSON serializer?
Note that the replacement parameter of JSON.stringify() is not helpful, at least in my hands.
UPDATE: Emitting NaN/Infinity etc. as strings makes the semantics of those strings ambiguous. They need to be emitted as barewords as in the Python and GSON implementations.

A: Here is an example
Javascript
var array1 = [-Infinity, -1, 0, 1, 2, NaN, 4, 5, Infinity],
    json = JSON.stringify(array1, function (key, value) {
        if (value !== value) {
            return 'NaN';
        }

        if (value === Infinity) {
            return 'Infinity';
        }

        if (value === -Infinity) {
            return '-Infinity';
        }

        return value;
    }),
    array2 = JSON.parse(json, function (key, value) {
        if (value === 'NaN') {
            return NaN;
        }

        if (value === 'Infinity') {
            return Infinity;
        }

        if (value === '-Infinity') {
            return -Infinity;
        }

        return value;
    });

console.log(json);
console.log(array2);

Output
["-Infinity",-1,0,1,2,"NaN",4,5,"Infinity"]
[-Infinity, -1, 0, 1, 2, NaN, 4, 5, Infinity]

References
JSON.stringify
JSON.parse
On jsFiddle
Update:
Javascript
var array1 = [-Infinity, -1, 0, 1, 2, NaN, 4, 5, Infinity],
    json = JSON.stringify(array1, function (key, value) {
        if (value !== value) {
            return '0/0';
        }

        if (value === 1/0) {
            return '1/0';
        }

        if (value === -1/0) {
            return '-1/0';
        }

        return value;
    }),
    array2 = JSON.parse(json, function (key, value) {
        if (value === '0/0') {
            return 0/0;
        }

        if (value === '1/0') {
            return Infinity;
        }

        if (value === '-1/0') {
            return -1/0;
        }

        return value;
    });

console.log(json);
console.log(array2);

Output
["-1/0",-1,0,1,2,"0/0",4,5,"1/0"]
[-Infinity, -1, 0, 1, 2, NaN, 4, 5, Infinity]

On jsFiddle

A: replacement parameter of JSON.stringify is quite right tool for the job.
JSON.stringify(data, function(key, value) {
   if (value === Infinity) {
      return "Infinity";
   } else if (value === -Infinity) {
      return "-Infinity";
   } else if (value !== value) {
      return "NaN";
   }
   return value;
});

And on the other side you can use reviver parameter of JSON.parse.
 JSON.parse(data, function(key, value) {
   if (value === "Infinity") {
      return Infinity;
   } else if (value === "-Infinity") {
      return -Infinity;
   } else if (value === "NaN") {
      return NaN;
   }
   return value;
});


text:
Q: Unnecessary line break in UITextView I am programmatically writing to a UITextView a comma separated string.
Example: NSString* str = @"cat,dog,big dog,kitten".
On [textView setText:str]; I get the results as:
       cat,dog,big
       dog,kitten.
I don't understand why is the space getting converted to a line break. Any idea?

A: the space gets converted to a line break, because the text did not fit into one line. This line break mode cannot be disabled, or changed. But you can rise the width of the textview.


text:
Q: Should templates, views, and models go in the Django config app? Is it considered against Django "best practices" to place templates, views, or models inside the Django config app? (The same app with settings.py)
Templates are probably a "no" because template files in a templates directory under the config app will not be found by default, I had to add a django.template.loaders.filesystem.Loader to load them.
Thank you for any advice.

A:
There's no restriction that a project package can't also be considered
  an application and have models, etc. (which would require adding it to
  INSTALLED_APPS).

https://docs.djangoproject.com/en/1.11/ref/applications/

A: Its normally a good practice to leave your project directory as such and keep the apps in their own separate directory and have them defined in the settings.py. This will make your project much more organised and easy to maintain.


text:
Q: TypeScript Generic to change all types of a particular type to another I'm trying to come up with a typescript type that takes an object and sets all keys of type number to be string.  The following doesn't work:
export type ChangeTypeOfKeys<T extends object> = {
  [key in keyof T]: key extends number ? string : T[key]
}

const c: ChangeTypeOfKeys<{ a: number, b: boolean }> = {
    a: 'ok',
    b: false,
}

The resulting type should be { a: string, b: boolean }, but instead I get a TS error:
Type 'string' is not assignable to type 'number'.(2322)
input.tsx(5, 29): The expected type comes from property 'a' which is declared here on type 'ChangeTypeOfKeys<{ a: number; b: boolean; }>'

TS playground link
I think the issue is related to how I'm using key in key in keyof T, since replacing key extends number with another argument works:
export type ChangeTypeOfKeys<T extends object, Replace> = {
  [key in keyof T]: Replace extends number ? string : T[key]
}

const c: ChangeTypeOfKeys<{ a: number, b: boolean }, number> = {
    a: 'ok',
    b: 'ok',
}

TS playground link
Not sure if there are any special properties with key that I'm missing here.  TIA!

A: To get the value of property referenced by key, do this:
export type ChangeTypeOfKeys<T extends object> = {
  [key in keyof T]: T[key] extends number ? string : T[key]
  //                ^^^^^^
}

Playground Link

The type of key will always be string in the example you gave. To be absolutely clear, in your code:

*

*key refers to the name of a property,

*T[key] refers to the property named key on type T.

Also note, extends object allows for [] types (among others), which might not be what you want. Try extending from {} or Record<string, any> instead.


text:
Q: Has eclipselink JPA2 Criteria API pom.xml configuration been simplified? From my pom   http://code.google.com/p/memorizeasy/source/browse/MemoPlatform/persistence/pom.xml:
<plugin>
                <groupId>org.bsc.maven</groupId>
                <artifactId>maven-processor-plugin</artifactId>
                <version>1.3.7</version>
                <executions>
                    <execution>
                        <id>process</id>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <phase>generate-sources</phase>
                        <configuration>
              <!-- Without this, the annotation processor complains about persistence.xml not being present and fail -->
                            <compilerArguments>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml -Aeclipselink.persistenceunits=com.mysimpatico_MemoPlatform-database_nbm_1.0-SNAPSHOTPU</compilerArguments>
              <!-- For an unknown reason, the annotation processor is not discovered, have to list it explicitly -->
                            <processors>
                                <processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
                            </processors>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <inherited>true</inherited>
                <configuration>
                    <compilerArgument>-proc:none</compilerArgument>
                </configuration>
            </plugin>

We discussed this last year here, and reported a relevant bug (no one cared about @eclipselink).

A: Note: I'm the author of the plugin.
To make configuration a lot simpler I would recommend you test: https://github.com/ethlo/eclipselink-maven-plugin.

A: With EclipseLink 2.2.0, it works for me without specifying the processor. The compiler argument is still needed.


text:
Q: jfreechart : BarChart total label positioning issue? I am using following code to position the total label on the bar chart's bar. The position is supposedly on the top of the each rendered bar. But some reason the label rendering is messing up the entire chart!
UPDATE Positioning Total Labels issue The totals for each bar should be on the top-center of the each bar! instead it positioned random somewhere near top and not aligned to bars.
Following lines are trouble having rendering chart lable:
ItemLabelAnchor labelAnchor = "O".equals(direction) ? ItemLabelAnchor.OUTSIDE12 : ItemLabelAnchor.INSIDE8;
TextAnchor textAnchor = "O".equals(direction) ? TextAnchor.TOP_CENTER : TextAnchor.CENTER;
TextAnchor rotationAnchor = "O".equals(direction) ? TextAnchor.TOP_CENTER : TextAnchor.BOTTOM_CENTER;
renderer.setSeriesPositiveItemLabelPosition(0,
        new ItemLabelPosition(labelAnchor, textAnchor, rotationAnchor, ((angle * Math.PI) / 180)));

I am using jdk 8 with jFreeChart-1.0.19. Following complete code listing:
CategoryPlot plot = chart.getCategoryPlot();

if (plot != null) {
if (log.isDebugEnabled()) {
    log.debug("Total Renderers : " + plot.getRendererCount());
}
try {
    JRPropertiesMap propMap = jasperChart.getPropertiesMap();
    if (propMap.containsProperty(APPLY_LABEL_ROTATION)) {
        DecimalFormat dfKey = new DecimalFormat("###,###");

       /* {0} - label would be equal to Series expression,
       * {1} - label would be equal to Category expression,
       * {2} - label would be equal to Value expression
       */
    StandardCategoryItemLabelGenerator labelGenerator = new    StandardCategoryItemLabelGenerator("{2}", dfKey);

LegendItemCollection lic = new LegendItemCollection();
List<LegendItem> legendList = new ArrayList<LegendItem>();
LegendItem totalOpenLegend = null;
for (int i = 0; i <= (plot.getRendererCount() - 1); i++) {

    String prop = propMap.getProperty("Chart_" + (i + 1));

    Double angle = null == prop ? 0D : Double.valueOf(prop.substring(0, prop.length() - 1));
    String direction = null == prop ? "O" : "" + prop.charAt(prop.length() - 1);
    if (log.isDebugEnabled()) {
        log.debug("Property value for renerer : " + i + " Chart_" + (i + 1) + "  angle : " + angle + ", Direction : " + direction);
    }

    CategoryItemRenderer renderer = plot.getRenderer(i);
    renderer.setBaseItemLabelsVisible(true);
    renderer.setBaseItemLabelGenerator(labelGenerator);

    if (i == 0) {
        Shape shape = ShapeUtilities.createLineRegion(new Line2D.Double(-6, 0, 6, 0), 1);
        ((LineAndShapeRenderer) renderer).setSeriesShape(0, shape);
        ((LineAndShapeRenderer) renderer).setBaseItemLabelsVisible(false);
    }

    if (i == 1) {
        //shape = ShapeUtilities.createLineRegion(new Line2D.Double(0, 0, 1, 1), 2);
        ((LineAndShapeRenderer) renderer).setBaseShapesFilled(false);
        ((LineAndShapeRenderer) renderer).setBaseItemLabelPaint(Color.RED);
    }

    if (i == 2) {
        ((LineAndShapeRenderer) renderer).setBaseItemLabelsVisible(false);
    }

    if (i == 3) {
        ((LineAndShapeRenderer) renderer).setBaseItemLabelPaint(new Color(139, 90, 43));
    }

    LegendItem item = renderer.getLegendItem(i, 0);

    if ((i >= 0) && (i < 4)) {
        legendList.add(item);
    } else {
        totalOpenLegend = item;
        BarRenderer barRenderer = (BarRenderer) renderer;
        barRenderer.setMaximumBarWidth(0.3);
        barRenderer.setItemMargin(0.1);
    }

    ItemLabelAnchor labelAnchor = "O".equals(direction) ? ItemLabelAnchor.OUTSIDE12 : ItemLabelAnchor.INSIDE8;
    TextAnchor textAnchor = "O".equals(direction) ? TextAnchor.TOP_CENTER : TextAnchor.CENTER;
    TextAnchor rotationAnchor = "O".equals(direction) ? TextAnchor.TOP_CENTER : TextAnchor.BOTTOM_CENTER;
    renderer.setSeriesPositiveItemLabelPosition(0,
            new ItemLabelPosition(labelAnchor, textAnchor, rotationAnchor, ((angle * Math.PI) / 180)));
    //--
    plot.setRenderer(i, renderer);
}

lic.add(totalOpenLegend);

for (LegendItem li : legendList) {
    lic.add(li);
}
System.out.println("Setting Legend Items");
plot.setFixedLegendItems(lic);
plot.getDomainAxis().setLowerMargin(0);


text:
Q: Fresh Ubuntu 19.04 installation only booting in recovery mode. (failed to reset PPM!) I just did a fresh Ubuntu 19.04 install alongside Windows 10 from USB.
Now, that installation won't boot to the login screen. The installation starts to hang after the following messages:
ucsi_ccg 0-0008: i2c_transfer failed -110
ucsi_ccg 0-0008: failed to reset PPM!
ucsi_ccg 0-0008: PPM init failed (-110)

Windows 10 still works fine, so GRUB ain't the problem.
My specs are the following:

*

*CPU: AMD Ryzen 5 2600

*RAM: 16 GB DDR4 @ 3200Mhz

*GPU: NVIDIA GeForce RTX 2060

*Mainboard: ASUS PRIME B450M-A

I also tried to run nvidia-detector in recovery mode and that returned nothing.
I installed an ssh-server via recovery mode so I can ssh into the machine.
Did anyone encounter this problem, too? Thanks for any help.


text:
Q: C++ pull a card from deck I'm trying to create a program that will pull a card from a deck of 52 regular playing cards.

*

*Suits: Heart, Spad, Diamond, Club.

*Rank: A,2,3,4,5,6,7,8,9,10,J,Q,K.
This should be the output:
Let's pull a card!
This time we got AH
Wanna pull a card again?
y
This time we got 3J
Wanna pull a card again?
n

My output is:
Let's pull a card!
DKThis time we got 00
Wanna pull a card again?
n

This is my code:
#include <iostream>
#include <ctime>
using namespace std;

// Function Declaration
int rankCard(), suitCard();

int main()
{
    srand(time(0));

    char answer;

    cout << "Let's pull a card!" << endl;

    do {
        cout << "This time we got " << rankCard() << suitCard() << endl;
        cout << "Wanna pull a card again?" << endl;
        cin >> answer;
    } while ((answer == 'y') || (answer == 'Y'));

    return 0;
}

int rankCard() {
    int rank = (rand() % 13) + 1;
    switch (rank) {
    case 1: cout << "A";
        break;
    case 10: cout << "T";
        break;
    case 11: cout << "J";
        break;
    case 12: cout << "Q";
        break;
    case 13: cout << "K";
        break;
    default: cout << rank;
        break;
    }

    return 0;
}

int suitCard() {
    int suit = (rand() % 4) + 1;
    switch (suit) {
    case 1: cout << "H";
        break;
    case 2: cout << "D";
        break;
    case 3: cout << "C";
        break;
    case 4: cout << "S";
        break;
    }
    return 0;
}

I can't figure out why the cards pulled (DK) are in that position and why I also get the 00. What am I doing wrong? Thanks

A: Your calls to rankCard() and suitCard() always return 0.
That 0 value is what's passed to cout in your main function.
The weird 'DK' is caused by the calls to cout inside rankCard and suitCard.
You could modify your functions to avoid the confusion:
#include <string>

std::string rankCard() {
    int rank = (rand() % 13) + 1;
    switch (rank) {
       case 1: return "A";
       case 10: return "T";
       case 11: return "J";
       case 12: return "Q";
       case 13: return "K";
       default: return std::to_string( rank );
    }
    return "";
}
std::string suitCard() {
    int suit = (rand() % 4) + 1;
    switch (suit) {
        case 1: return "H";
        case 2: return "D";
        case 3: return "C";
        case 4: return "S";
    }
    return "";
}

A: This line:
cout << "This time we got " << rankCard() << suitCard() << endl;

So those functions print the card, and then they return 0, so if you call them in cout, they will do their thing witch is printing the card and then print the return value witch is 0.
What you can do is to  call them outside the cout, just do:
//...
cout << "This time we got ";
rankCard();
suitCard();
cout << endl;
cout << "Wanna pull a card again?" << endl;
//...

Personally I would refactor the functions to return the respective card char:
Live sample
const char rankCard() {
    int rank = (rand() % 13) + 1;
    switch (rank) {
    case 1: return 'A';
    case 10: return 'T';
    case 11: return 'J';
    case 12: return 'Q';
    case 13: return 'K';
    default: return rank + 48; // convert to decimal digit
    }
}

const char suitCard() {
    int suit = (rand() % 4) + 1;
    switch (suit) {
    case 1: return 'H';
    case 2: return 'D';
    case 3: return 'C';
    case 4: return 'S';
    default: return 0;  //ASCII code for null character
    }
}


text:
Q: QSocketNotifier: Can only be used with threads started with QThread I'm getting the following error with just a very basic application and with no sockets or anything fancy:

QSocketNotifier: Can only be used with threads started with QThread

Machine:

*

*Fedora 32 (Workstation Edition)

*Python 3.8

*PyQt5

*Fedora is inside VirtualBox

*Host is Windows 10

From Script.py
#!/usr/bin/python3.8
from PyQt5.QtWidgets import QApplication, QLabel
app = QApplication([])
label = QLabel('Hello World!')
label.show()
app.exec_()


text:
Q: How to make ideal conditions to measure performance of my app on Windows 7 I want to measure performance of my RayTracer and I want to create some ideal test conditions on my PC.
I am using Windows 7.
Is there some application, which can turns the system into "measurement mode"?
I mean, some scenes will be rendered several hours and I would like to every test has exact the same conditions as previous test. There are many issues like random reading from disk, antivirus scanning, etc...
So, is there a way to start Windows 7 in some light mode - running just with necessary processes?
Hope you understand my needs.

A: Don't forget to check the bottom of my answer too.
You will want to follow the Performance Testing Guide which instructs in details how to prepare your system for Performance Testing. It takes a lot of into account: From the impact of your hardware, installing your OS fresh, tweaking it, capturing a baseline trace to the actual testing. Definitely worth reading if you take scientific measuring seriously. Here is its extensive table of contents:
Introduction
Windows Performance Testing Challenges
  Background Tasks
  Scheduled Tasks
  Memory Management and SuperFetch
  Performance versus Power
Performance Test Design Considerations
  Automating User Presence
  Testing End-User Scenarios
Effects of Hardware on Performance
  CPU
  RAM
  Type of Storage Device
  Graphics Subsystem
Recommended Test Methodology
  Step 1. Set Up the Operating System
  Step 2. Set Up the Test Software
  Step 3. Run Windows Update
  Step 4. Reboot the System
  Step 5. Download Windows Defender Definition Files
  Step 6. Disable Windows Update
  Step 7. Calculate the Windows Experience Index
  Step 8. Reboot the System
  Step 9. Let Windows Defender Build a System File Cache
  Step 10. Disable User Account Control
  Step 11. Complete Indexing
  Step 12. Use SuperFetch to Train the System
  Step 13. Complete Idle-Time Tasks
  Step 14. Disable System Restore
  Step 15. Review Scheduled Tasks
  Step 16. Run the Test
Best Practices
  Best Practices for Designing Performance Tests
  Best Practices for Running Performance Tests
Resources
Appendix. Scheduled Tasks

You will also want to check out GPUView which can definitely help ironing out performance issues in your ray tracer. If you do, the presentations listed at the bottom go into quite some details, perhaps you might be able to find its video recordings if the slides aren't enough.

A: Use a clean install with your render software. If there is an existing install, then you can try to shut down every single process manually in taskmanager and in the msconfig window (press start and type msconfig) you can prevent applications from starting up at boot.
I've done some benchmarking myself and I would always use the same install image before running every test. (clean install it)


text:
Q: I need help making the word UpperCase in a for loop, the word isn't written in eclipse but it is imported from a txt file import java.util.*;
import java.io.*;

public class Cascader {
    public static void main(String args[]) throws IOException {
        Scanner inputfile = new Scanner(new File("name.txt"));
        String name = inputfile.nextLine();
        System.out.println("Reading the name...");
        for(int i = 0; i < name.length(); i++) {
            System.out.println(name.charAt(i));
        }
        inputfile.close();
    }
}

A: To answer your question: you're probably not 'saving' the new String. The toUpperCase() method returns a new String, in which each character has been changed to upper case.
name.toUpperCase(); // does not do anything to the String in the variable 'name'
String newName = name.toUpperCase(); // if name was 'john', newName will be 'JOHN'
name = name.toUpperCase(); // if name was 'john', name will now be 'JOHN'


text:
Q: How is a JavaScript hash map implemented? I currently work with OpenLayers and have a huge set of data to draw into a vector layer (greater than 100000 vectors).
I'm now trying to put all these vectors into a JavaScript hash map to analyze the performance.  I want to know how is the hash map in JavaScript implemented, is it a real hash function or just a wrapped function that uses a simple data structure and a search algorithm?

A: While plain old JavaScript objects can be used as maps, they are usually implemented in a way to preserve insertion-order for compatibility with most browsers (see Craig Barnes's answer) and are thus not simple hash maps.
ES6 introduces proper Maps (see MDN JavaScript Map) of which the standard says:

Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection.

A: JavaScript objects cannot be implemented purely on top of hash maps.
Try this in your browser console:
var foo = {
    a: true,
    b: true,
    z: true,
    c: true
}

for (var i in foo) {
    console.log(i);
}

...and you'll recieve them back in insertion order, which is de facto standard behaviour.
Hash maps inherently do not maintain ordering, so JavaScript implementations may use hash maps somehow, but if they do, it'll require at least a separate index and some extra book-keeping for insertions.
Here's a video of Lars Bak explaining why v8 doesn't use hash maps to implement objects.

A: every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:
var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;

javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode() function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)
2020 Update:
javascript today supports other datatypes as well: Map and WeakMap. They behave more closely as hash maps than traditional objects.

A: Should you try this class Map:

var myMap = new Map();

// setting the values
myMap.set("1", 'value1');
myMap.set("2", 'value2');
myMap.set("3", 'value3');

console.log(`Map size: ${myMap.size}`); // 3

// getting the values
console.log(`Key: "1", Value: ${myMap.get("1")}`);    // "value associated with "value1"
console.log(`Key: "2", Value: ${myMap.get("2")}`);    // "value associated with "value2"
console.log(`Key: "3", Value: ${myMap.get("3")}`);    // "value associated with "value3"

Notice: key and value can be any type.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

A: Here is an easy and convenient way of using something similar to the Java map:
var map= {
    'map_name_1': map_value_1,
    'map_name_2': map_value_2,
    'map_name_3': map_value_3,
    'map_name_4': map_value_4
    }

And to get the value:
alert( map['map_name_1'] );    // fives the value of map_value_1

......  etc  .....

A:

function test() {
  var map = {
    'm1': 12,
    'm2': 13,
    'm3': 14,
    'm4': 15
  }
  alert(map['m3']);
}
<input type="button" value="click" onclick="test()" />

A: I was running into the problem where i had the json with some common keys. I wanted to group all the values having the same key. After some surfing I found hashmap package. Which is really helpful.
To group the element with the same key, I used multi(key:*, value:*, key2:*, value2:*, ...).
This package is somewhat similar to Java Hashmap collection, but not as powerful as Java Hashmap.


text:
Q: How to integrate $5^{5^{5^x}}5^{5^x}5^x$? How to integrate $5^{5^{5^x}}5^{5^x}5^x$ ?
I guess it's simple but can't figure it out !

A: Start with $5^x=y\implies5^x\cdot\ln5\ dx=dy$ to get
$$\ln5\int5^{5^{5^x}}5^{5^x}5^x=\int 5^{5^y}5^ydy$$
again set $5^y=u$

A: Let $u=5^{5^x}$, then $x = \frac{\frac{\ln(u)}{\ln(5)}}{\ln{5}}$ and $du = 5^{x+5^x}\ln^2(5)\hspace{.1cm} dx \implies dx = \frac{5^{-x-5^x}}{\ln^2(5)} \hspace{.1cm} du$. Thus we transform
$ \begin{align}
\int 5^{5^{5^x}} 5^{5^x} 5^x \hspace{.1cm} dx &= \int 5^uu5^x \frac{5^{-x-5^x}}{\ln^2(5)} \hspace{.1cm} du \\
&= \int \frac{u5^{u-5\frac{\frac{\ln(u)}{\ln(5)}}{\ln{5}}}}{\ln^2(5)} \hspace{.1cm} du \\
&= \frac{1}{\ln^2(5)} \int u5^{u-5\frac{\frac{\ln(u)}{\ln(5)}}{\ln{5}}} \hspace{.1cm} du \\
&= \frac{1}{\ln^2(5)} \int 5^u \hspace{.1cm} du \\
&= \frac{1}{\ln^2(5)} \frac{5^u}{\ln(5)} \\
&= \frac{1}{\ln^2(5)} \frac{5^{5^{5^x}}}{\ln(5)} \\
&= \frac{5^{5^{5^x}}}{\ln^3(5)}
\end{align}$


text:
Q: Intercept page request and add value to it I am trying to intercept the GET request of a post and add a value to it.
function foo($request) {
    $request['vid'] = wp_generate_uuid4();

    return $request;
}
add_filter( 'request', 'foo' );

and hope that it would be available later with
$_REQUEST['vid']

but no access so far any ideas?

A: WordPress doesn't add the vid to the $_REQUEST array. Instead, it's saved in a class property — see WP::$query_vars which is an array.
And to access the value of items in that array, use get_query_var() like so in your case:
$vid = get_query_var( 'vid' );
echo "vid value is $vid";


text:
Q: Is variadic arguments list null-terminated? The title covers my question pretty much completely. For some context - from various sources I know that variadic functions are supposed to have signature where first argument gives information about how many arguments were passed, but after playing around with it a bit i found that vs_arg always returns nullptr right after the last argument so this code works well (with MS Visual Studio):
void func(MClass *t_instance...) {
    std::va_list arguments;
    va_start(arguments, t_instance);
    for (MClass *instance = t_instance; instance != nullptr; instance = va_arg(arguments, MClass *)) {
        std::out << instance->name << std::endl;
    }
    va_end(arguments);
}

Of course provided that there is no nullptr passed as an argument, is this a valid assumption? I couldn't find that this list is supposed to be null-terminated, but couldn't find the opposite either.

A: No, it is not a valid assumption that calling va_arg at the last parameter will return a null pointer. According to the standard* calling va_arg when there are no parameters left, i.e when it is pointing at the last parameter, has undefined behavior. As far as I know there is no way for the program to check when it is at the last parameter, this information must be provided by some other mean.
* The C++ standard refers the behavior of va_arg to the C standard, which defines this in section 7.16.1.1 clause 2.


text:
Q: How to print the $_REQUEST that is available inside a specific AJAX function? I'm a beginner in PHP, and I'm having some trouble debugging AJAX, because I can't just print_r what I want to know inside the script.
I'm using a AJAX image upload plugin that have a lot of functions such as receive post, file check, etc, to finally get to the "insertTodatabase" funcion. I want to know what data is being sent to this final fuction, how can I echo the $_REQUEST of such function, for example?
I'm sorry if my question is vague, I'm doing my best to explain.
Thank you.

A: You can use the error_log function to write data to your error log. Then just view your error log and you can have the information stored there.
Example:
error_log('UserName: ' . $username);


text:
Q: ngx-drag-drop - Cannot access 'DndDraggableDirective' before initialization I'm updating angular and it's dependencies to 13th version and encountered an issue with ngx-drap-drop package in jest tests. Previously it was on 2.0.0 version and now on 13.0.0. So I have a component which uses some directives from ngx-drag-drop package in component's html file.
When I run jest tests(v27.4) I see this error:
ReferenceError: Cannot access 'DndDraggableDirective' before initialization
which points to DndModule import in my test file:
import { DndModule } from 'ngx-drag-drop'
I import DndModule into TestBed.configureTestingModule, so this is not the case(BTW ngx-drag-drop v2.0.0 been throwing the error Unexpected value 'DndModule' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.
Any help appreciated.

A: Looks like it's angular compiler issue (or not, I'm not sure) so for now I fixed it by mocking DndDraggableDirective and DndDropZoneDirective in my code.
Also I cloned ngx-drag-drop repo to try to fix the issue and I wasn't able to compile project on master branch. So, working on it.


text:
Q: If $f: M\to M$ an isometry, is $f$ bijective? $f: M\to M$ an isometry between metric spaces, is $f$ bijective?
$f$ obviously is injective. I proved bijection for $M=\mathbb{R}^n$. But I'm not sure if is true in general metric spaces.

A: Jasons answers give a very nice example, but there are even examples when you have much more than only a metric.
Just giving an example for Hilbert spaces. Taking $\ell^2$ with  the norm
$$\|(a_k)_{k\in \mathbb{N}}\|=\sum_{k=0}^\infty |a_k|^2$$
(which is induced from the skalarproduct)
$$\langle (a_k)_{k \in \mathbb{N}}, (b_k)_{k\in \mathbb{N}}\rangle=
 \sum_{k=0}^\infty a_k b_k $$
and taking something like a switch function so that
$$f(a_0,a_1,a_2,\dots)=(0,a_0,a_1,a_2,\dots)$$
This one is obviously an isometry, but obviously not surjective.
For Hilbertspaces there are no finite dimensional examples, as with a scalarproduct ones always get that a isometry is affine linear (I will consider the linear cases which doesn't make a big difference), and as every isometry is injective the kernel is trivial (here I say it is linear) and hence the isometry is in finite dimensional case a bijection.

A: Let $M = \mathbb{N}$ with the inherited metric from $\mathbb{R}$.  Then the fuction $f(x) = x+1$ is an isometry, but is not surjective.  As Yoni points out in the comments, one can use $(0,\infty)$ in place of $\mathbb{N}$ if, say, one wants a connected example.
Further, we can do a similar thing on any infinite space with discrete metric.
Incidentally, when $M$ is compact, any isometry must be surjective.  See the corresponding question asked here.


text:
Q: Bokeh Select widget does not update plot glyph I am programming a Bokeh application and trying to implement a select widget. Before I had my whole plot with glyph etc. in one function and used this function as the callback function for my select widget and everything worked fine. But the performance was pretty bad. So, I tried to make the plot outside of a function and then the callback functions separately. Now the select widget does not work properly anymore. I do not get any error when starting the application (I use the Bokeh serve --show main.py method). The select widget shall change the values of the y-axis and update the y-axis label at the same time. The label gets updated but the values are not changing. My code looks like this:
sel_yaxis = Select(
    title='Select Y Axis',
    options=sorted(head_columns.keys()),
    value='Demonstrative word'
)

def set_axis(attr, old, new):
    # Save value for y-axis from select input widget within the "top" variable
    # in the glyph. It will automatically update on changing the select widget within the application.
    y_axis = head_columns[sel_yaxis.value]

    # Set the label on y-axis so that the glyph displayed and y-axis label match
    p.yaxis.axis_label = sel_yaxis.value
    c.yaxis.axis_label = sel_yaxis.value

sel_yaxis.on_change('value', set_axis)

p = figure(
    title='',
    plot_width=1000,
    plot_height=700,
    x_axis_label='ID',
    toolbar_location='above',
    tools='pan, box_select, save, undo, redo, xwheel_zoom, reset'
)

c = figure(
    title='',
    plot_width=1000,
    plot_height=700,
    x_axis_label='ID',
    toolbar_location='above',
    tools='pan, box_select, save, undo, redo, xwheel_zoom, reset'
)

# Holds the x-axis ID values for the glyph
id = head_columns['id']

p.yaxis.axis_label = sel_yaxis.value
c.yaxis.axis_label = sel_yaxis.value

# Render glyph into plot
p.vbar(
    x=id,
    top=y_axis,
    source=source,
    width=0.8,
    line_alpha=0.3,
)

c.scatter(
    x=id,
    y=y_axis,
    source=source
)

The same way it was working good within one main function to create the plot.
Any ideas?
Regards


text:
Q: RoR, Devise: Route to sign in redirects to users#show When I go to localhost:3000/users/sign_in, I am redirected to users#show with an error (as there is no current user) instead of the sign in page. By everything I can figure, this should not be happening, yet it is. I am redirected both if I click a link to new_user_session_path, or if I type the URI directly.
I have looked through my routes for duplicates and I have cleared the session and cache. Honestly the whole Devise interface is so simple, I'm not sure what else to check. And this worked earlier, so clearly something has changed.
What else could be going wrong?
Rake Routes
# output from rake:routes
# there are no other routes for this GET path

new_user_session GET    /users/sign_in(.:format)         devise/sessions#new

Routes.rb
#config/routes.rb

resources :users
devise_for :users

Controller
#app/controllers/user_controller.rb

before_action :confirm_signed_in

def confirm_signed_in
  unless user_signed_in?
    initiate_return_to_last_successful
    flash.now[:notice] = 'Please sign in.'
    redirect_to new_user_session_path
  end
end

Note: I most recently was trying to modify the Devise registrations controller create action. I'm not sure if that caused it, but I've backed out of all changes associated with it (I believe. Checked three times.)

A: You need to switch these two lines. Routes at the top of the file take precedence, and so the issue is resources for uses route pattern-matching.
This route, generated by the resources method, matches any route in the format of /users/anything_can_go_here, and the part that replaces :id will be available in the controller as params[:id].
GET '/users/:id' => 'users#show'

This route, generated by devise, needs to be placed above the call to resources :users, for it to have precedence in the eyes of Rails.
GET 'users/sign_in' => 'users#sign_in'

To fix this problem, this
resources :users
devise_for :users

Should be
devise_for :users
resources :users

To learn more about routing in Ruby on Rails, check out this guide/tutorial.


text:
Q: Python: print last line of text file first and first line last (reverse) I'd like to take a .txt file and paste the contents into a Multiline element, last line first - first line last, using PySimpleGUI.
The problem is, I want the file to print from the last line to the first.
e.g.
line1
line2
line3
line4
line5

would print
line5
line4
line3
line2
line1

I've tried
with open('file.txt','r') as f:
  x=f.read()
print(reversed(x))

and
with open('file.txt', 'r') as f:
  x=f.read()
print(x[::-1]

but both just invert/reverse everything. I want to print the last line first and the last line last but in the order that the characters initially appear.
I get something like
5enil
4enil
3enil
...

A: You can use readlines like this:
lines = []
with open("lines", "r") as f:
    lines = f.readlines()

print("".join((reversed(lines))))

Output
line5
line4
line3
line2
line1

A: Try the below code:
with open('file.txt', 'r') as f:
   x=f.readlines()
   print(x[::-1])

It's working.

A: Could use the readlines() method
# '''this is line 1\nthis is line 2\nthis is line 3'''

with open('test_text.txt', 'r') as f:
    last_line = f.readlines()[-1]
    first_line = f.readlines()[0]

print(first_line)
print(last_line)

output
'this is line 1'
'this is line 3'

A: you can this
print("\n".join (reversed(open('list.txt',"r").read().splitlines())))


text:
Q: Partitioned table query still scanning all partitions I have a table with over a billion records. In order to improve performance, I partitioned it to 30 partitions. The most frequent queries have (id = ...) in their where clause, so I decided to partition the table on the id column.
Basically, the partitions were created in this way:
CREATE TABLE foo_0 (CHECK (id % 30 = 0)) INHERITS (foo);
CREATE TABLE foo_1 (CHECK (id % 30 = 1)) INHERITS (foo);
CREATE TABLE foo_2 (CHECK (id % 30 = 2)) INHERITS (foo);
CREATE TABLE foo_3 (CHECK (id % 30 = 3)) INHERITS (foo);
.
.
.

I ran ANALYZE for the entire database and in particular, I made it collect extra statistics for this table's id column by running:
ALTER TABLE foo ALTER COLUMN id SET STATISTICS 10000;

However when I run queries that filter on the id column the planner shows that it's still scanning all the partitions. constraint_exclusion is set to partition, so that's not the problem.
EXPLAIN ANALYZE SELECT * FROM foo WHERE (id = 2);

                                               QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------
 Result  (cost=0.00..8106617.40 rows=3620981 width=54) (actual time=30.544..215.540 rows=171477 loops=1)
   ->  Append  (cost=0.00..8106617.40 rows=3620981 width=54) (actual time=30.539..106.446 rows=171477 loops=1)
         ->  Seq Scan on foo  (cost=0.00..0.00 rows=1 width=203) (actual time=0.002..0.002 rows=0 loops=1)
               Filter: (id = 2)
         ->  Bitmap Heap Scan on foo_0 foo  (cost=3293.44..281055.75 rows=122479 width=52) (actual time=0.020..0.020 rows=0 loops=1)
               Recheck Cond: (id = 2)
               ->  Bitmap Index Scan on foo_0_idx_1  (cost=0.00..3262.82 rows=122479 width=0) (actual time=0.018..0.018 rows=0 loops=1)
                     Index Cond: (id = 2)
         ->  Bitmap Heap Scan on foo_1 foo  (cost=3312.59..274769.09 rows=122968 width=56) (actual time=0.012..0.012 rows=0 loops=1)
               Recheck Cond: (id = 2)
               ->  Bitmap Index Scan on foo_1_idx_1  (cost=0.00..3281.85 rows=122968 width=0) (actual time=0.010..0.010 rows=0 loops=1)
                     Index Cond: (id = 2)
         ->  Bitmap Heap Scan on foo_2 foo  (cost=3280.30..272541.10 rows=121903 width=56) (actual time=30.504..77.033 rows=171477 loops=1)
               Recheck Cond: (id = 2)
               ->  Bitmap Index Scan on foo_2_idx_1  (cost=0.00..3249.82 rows=121903 width=0) (actual time=29.825..29.825 rows=171477 loops=1)
                     Index Cond: (id = 2)
.
.
.

What could I do to make the planer have a better plan? Do I need to run ALTER TABLE foo ALTER COLUMN id SET STATISTICS 10000; for all the partitions as well?
EDIT
After using Erwin's suggested change to the query, the planner only scans the correct partition, however the execution time is actually worse then a full scan (at least of the index).
EXPLAIN ANALYZE select * from foo where (id % 30 = 2) and (id = 2);
                                                                         QUERY PLAN
                                                                             QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Result  (cost=0.00..8106617.40 rows=3620981 width=54) (actual time=32.611..224.934 rows=171477 loops=1)
   ->  Append  (cost=0.00..8106617.40 rows=3620981 width=54) (actual time=32.606..116.565 rows=171477 loops=1)
         ->  Seq Scan on foo  (cost=0.00..0.00 rows=1 width=203) (actual time=0.002..0.002 rows=0 loops=1)
               Filter: (id = 2)
         ->  Bitmap Heap Scan on foo_0 foo  (cost=3293.44..281055.75 rows=122479 width=52) (actual time=0.046..0.046 rows=0 loops=1)
               Recheck Cond: (id = 2)
               ->  Bitmap Index Scan on foo_0_idx_1  (cost=0.00..3262.82 rows=122479 width=0) (actual time=0.044..0.044 rows=0 loops=1)
                     Index Cond: (id = 2)
         ->  Bitmap Heap Scan on foo_1 foo  (cost=3312.59..274769.09 rows=122968 width=56) (actual time=0.021..0.021 rows=0 loops=1)
               Recheck Cond: (id = 2)
               ->  Bitmap Index Scan on foo_1_idx_1  (cost=0.00..3281.85 rows=122968 width=0) (actual time=0.020..0.020 rows=0 loops=1)
                     Index Cond: (id = 2)
         ->  Bitmap Heap Scan on foo_2 foo  (cost=3280.30..272541.10 rows=121903 width=56) (actual time=32.536..86.730 rows=171477 loops=1)
               Recheck Cond: (id = 2)
               ->  Bitmap Index Scan on foo_2_idx_1  (cost=0.00..3249.82 rows=121903 width=0) (actual time=31.842..31.842 rows=171477 loops=1)
                     Index Cond: (id = 2)
         ->  Bitmap Heap Scan on foo_3 foo  (cost=3475.87..285574.05 rows=129032 width=52) (actual time=0.035..0.035 rows=0 loops=1)
               Recheck Cond: (id = 2)
               ->  Bitmap Index Scan on foo_3_idx_1  (cost=0.00..3443.61 rows=129032 width=0) (actual time=0.031..0.031 rows=0 loops=1)
.
.
.
         ->  Bitmap Heap Scan on foo_29 foo  (cost=3401.84..276569.90 rows=126245 width=56) (actual time=0.019..0.019 rows=0 loops=1)
               Recheck Cond: (id = 2)
               ->  Bitmap Index Scan on foo_29_idx_1  (cost=0.00..3370.28 rows=126245 width=0) (actual time=0.018..0.018 rows=0 loops=1)
                     Index Cond: (id = 2)
 Total runtime: 238.790 ms

Versus:
EXPLAIN ANALYZE select * from foo where (id % 30 = 2) and (id = 2);
                                                                            QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Result  (cost=0.00..273120.30 rows=611 width=56) (actual time=31.519..257.051 rows=171477 loops=1)
   ->  Append  (cost=0.00..273120.30 rows=611 width=56) (actual time=31.516..153.356 rows=171477 loops=1)
         ->  Seq Scan on foo  (cost=0.00..0.00 rows=1 width=203) (actual time=0.002..0.002 rows=0 loops=1)
               Filter: ((id = 2) AND ((id % 30) = 2))
         ->  Bitmap Heap Scan on foo_2 foo  (cost=3249.97..273120.30 rows=610 width=56) (actual time=31.512..124.177 rows=171477 loops=1)
               Recheck Cond: (id = 2)
               Filter: ((id % 30) = 2)
               ->  Bitmap Index Scan on foo_2_idx_1  (cost=0.00..3249.82 rows=121903 width=0) (actual time=30.816..30.816 rows=171477 loops=1)
                     Index Cond: (id = 2)
 Total runtime: 270.384 ms

A: For non-trivial expressions you have to repeat the more or less verbatim condition in queries to make the Postgres query planner understand it can rely on the CHECK constraint. Even if it seems redundant!
Per documentation:

With constraint exclusion enabled, the planner will examine the
  constraints of each partition and try to prove that the partition need
  not be scanned because it could not contain any rows meeting the
  query's WHERE clause. When the planner can prove this, it excludes
  the partition from the query plan.

Bold emphasis mine. The planner does not understand complex expressions.
Of course, this has to be met, too:

Ensure that the constraint_exclusion configuration parameter is not
  disabled in postgresql.conf. If it is, queries will not be optimized as desired.

Instead of
SELECT * FROM foo WHERE (id = 2);
Try:
SELECT * FROM foo WHERE id % 30 = 2 AND id = 2;
And:

The default (and recommended) setting of constraint_exclusion is
  actually neither on nor off, but an intermediate setting called
  partition, which causes the technique to be applied only to queries
  that are likely to be working on partitioned tables. The on setting
  causes the planner to examine CHECK constraints in all queries, even
  simple ones that are unlikely to benefit.

You can experiment with the constraint_exclusion = on to see if the planner catches on without redundant verbatim condition. But you have to weigh cost and benefit of this setting.
The alternative would be simpler conditions for your partitions as already outlined by @harmic.
An no, increasing the number for STATISTICS will not help in this case. Only the CHECK constraints and your WHERE conditions in the query matter.

A: Unfortunately, partioning in postgresql is fairly primitive. It only works for range and list based constraints. Your partition constraints are too complex for the query planner to use to decide to exclude some partitions.
In the manual it says:

Keep the partitioning constraints simple, else the planner may not be
  able to prove that partitions don't need to be visited. Use simple
  equality conditions for list partitioning, or simple range tests for
  range partitioning, as illustrated in the preceding examples. A good
  rule of thumb is that partitioning constraints should contain only
  comparisons of the partitioning column(s) to constants using
  B-tree-indexable operators.

You might get away with changing your WHERE clause so that the modulus expression is explicitly mentioned, as Erwin suggested. I haven't had much luck with that in the past, although I have not tried recently and as he says, there have been improvements in the planner. That is probably the first thing to try.
Otherwise, you will have to rearrange your partitions to use ranges of id values instead of the modulus method you are using now. Not a great solution, I know.
One other solution is to store the modulus of the id in a separate column, which you can then use a simple value equality check for the partition constraint. Bit of a waste of disk space, though, and you would also need to add a term to the where clauses to boot.

A: In addition to Erwin's answer about the details of the how the planner works with partitions, there is a larger issue here.
Partitioning is not a magic bullet.  There are a handful of very specific things for which partitioning is very useful.  If none of those very specific things apply to you, then you cannot expect a performance improvement from partitioning, and most likely will get a decrease instead.
To do partitioning correctly, you need a thorough understanding of your usage patterns, or your data loading and unloading patterns.


text:
Q: how to create a zoomable widget that when the pinch ends, the zoomed widget gets its initial position? I want to create a Zoomable widget using Matrix_Gesture_Detector package. I have created the widget with this code:
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:matrix_gesture_detector/matrix_gesture_detector.dart';
import 'package:vector_math/vector_math_64.dart';

class ZoomableWidget extends StatefulWidget {
  final Widget child;

  const ZoomableWidget({Key key, this.child}) : super(key: key);
  @override
  _ZoomableWidgetState createState() => _ZoomableWidgetState();
}

class _ZoomableWidgetState extends State<ZoomableWidget> {
  Matrix4 defaultMatrix = Matrix4.diagonal3(
      Vector3(1.0.clamp(1.0, 5.0), 1.0.clamp(1.0, 5.0), 1.0.clamp(1.0, 5.0)));
  Matrix4 matrix;
  @override
  void initState() {
    matrix = defaultMatrix;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ClipRect(
      child: MatrixGestureDetector(
        shouldTranslate: false,clipChild: true,focalPointAlignment: Alignment.center,
        shouldRotate: false,
        onMatrixUpdate: (Matrix4 m, Matrix4 tm, Matrix4 sm, Matrix4 rm) {
          setState(() {
            matrix = m;
          });
        },
        child: Transform(
          transform: matrix,
          alignment: FractionalOffset.center,
          child: widget.child,
        ),
      ),
    );
  }
}

now what I want is that when user releases the screen (the pinch ends) the widget go back to its initial position. any ides how can I achieve this?
also how can I prevent the zooming from zooming out that makes the container smaller from its original size?


text:
Q: Add DataGridViews to Form programatically I have a problem and I'm searching for some ideas how to implement it. I have a DataGridView with ComboBoxColumns, ButtonColumns and TextBoxColumns.
Below I have two Buttons one to add a new DataGridView and one to delete the lastly created DataGridView.
How can I achieve it that a new DataGridView will be added below the already existing DataGridView when clicking add Button and deleted when clicking delete button.
Code for creating new DataGridView, but I want every time a new DataGridView, actually it is only creating a second and then adding columns at the end.
private void add(object sender, EventArgs e)
{
        try
        {
            dataGridView2.Visible = true;
            dataGridView2.Width = 725;
            dataGridView2.BorderStyle = BorderStyle.None;
            dataGridView2.ScrollBars = ScrollBars.Both;
            dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            dataGridView2.BackgroundColor = Color.White;
            dataGridView2.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView2.CellBorderStyle = DataGridViewCellBorderStyle.None;

            for (var i = 0; i < rb_insert_manually_datagridview_detailed.ColumnCount; i++)
            {
                if (rb_insert_manually_datagridview_detailed.Columns[i].GetType().Name == "DataGridViewComboBoxColumn")
                {
                    var cmbColumn = new DataGridViewComboBoxColumn();
                    cmbColumn.DataPropertyName = rb_insert_manually_datagridview_detailed.Columns[i].HeaderText;
                    cmbColumn.HeaderText = rb_insert_manually_datagridview_detailed.Columns[i].HeaderText;
                    cmbColumn.ValueMember = rb_insert_manually_datagridview_detailed.Columns[i].HeaderText;
                    cmbColumn.DisplayMember = rb_insert_manually_datagridview_detailed.Columns[i].HeaderText;
                    cmbColumn.FlatStyle = FlatStyle.Flat;
                    dataGridView2.Columns.Add(cmbColumn);
                }
                if (rb_insert_manually_datagridview_detailed.Columns[i].GetType().Name == "DataGridViewButtonColumn")
                {
                    var btnColumn = new DataGridViewButtonColumn();
                    btnColumn.DataPropertyName = rb_insert_manually_datagridview_detailed.Columns[i].HeaderText;
                    btnColumn.HeaderText = rb_insert_manually_datagridview_detailed.Columns[i].HeaderText;
                    btnColumn.FlatStyle = FlatStyle.Flat;
                    dataGridView2.Columns.Add(btnColumn);
                }

                if (rb_insert_manually_datagridview_detailed.Columns[i].GetType().Name == "DataGridViewTextBoxColumn")
                {
                    var txtColumn = new DataGridViewTextBoxColumn();
                    txtColumn.DataPropertyName = rb_insert_manually_datagridview_detailed.Columns[i].HeaderText;
                    txtColumn.HeaderText = rb_insert_manually_datagridview_detailed.Columns[i].HeaderText;
                    dataGridView2.Columns.Add(txtColumn);
                }
            }

            dataGridView2.Location = new Point(rb_insert_manually_datagridview_detailed.Location.X, rb_insert_manually_btn_new_binder.Location.Y + 40);
            this.Controls.Add(dataGridView2);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error", "Fehler", MessageBoxButtons.Error, MessageBoxIcon.Error);
        }
}

To remove a DataGrid I use actually Visible but it isn't working, and on the commented out version it throws the Exception
private void delete(object sender, EventArgs e)
{
        try
        {
            /*                dataGridView2.Columns.Remove("col1");
                            dataGridView2.Columns.Remove("col2");
                            dataGridView2.Columns.Remove("col3");
                            dataGridView2.Columns.Remove("col4");
                            dataGridView2.Columns.Remove("col5");
                            dataGridView2.Columns.Remove("col6");*/
            dataGridView2.Visible = false;
        }
        catch
        {

                MessageBox.Show("Kann letzen Binder nicht löschen", "Warnung", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
}

I'm thankful for every help, idea.


text:
Q: How to POST xml data while calling API through JAVA? I am creating an application where I want to POST xml data directly (without key value pair) to API. The API needs certification authentication which is done here in code. Now I want to POST the data to same URL.
Here is what I want to do :

My current code is :
@Override
    public String demoAPI(String xmlData) {
        StringBuilder sb = new StringBuilder();
        String output="";
    try {
        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        clientStore.load(new FileInputStream(new File("path-to-pfx-file")),
                "password".toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientStore, "password".toCharArray());
        KeyManager[] kms = kmf.getKeyManagers();
        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(new FileInputStream("path-to-jks-file"), "password".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        TrustManager[] tms = tmf.getTrustManagers();
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kms, tms, new SecureRandom());
        SSLContext.setDefault(sslContext);
        HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        URL url = new URL("URL");
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(100000);
        con.setSSLSocketFactory(sslContext.getSocketFactory());
        con.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        System.out.println(sb.toString());
        output = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
        output = e.getMessage();
    }
    return output;
}

Whereas , for same url , I want to POST xmlData from method.
How can I do that ? What should I change in the code after
con.setRequestMethod("POST"); ?

A: You have a url and you have some XML to post this url via HTTP. And your post request is a SOAP request, you can send this soap message in the body of this request. So nothing special or different than many developers' do. Post your soap data via http by using java.net or Apache or others. Here are the code samples to do this:
HttpsURLConnection con = null;
try{
    URL url = new URL("URL");
    con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("content-type", "application/x-www-form-urlencoded");
    con.setRequestProperty("Content-Language", "application/soap+xml; charset=utf-8"); // request properties, set your needs
    con.setDoOutput(true);
    OutputStream os = con.getOutputStream();
    os.write(xmlData.getBytes("utf-8"));
    os.close();

}catch(Exception e){
      e.printStackTrace();
 }finally{
      con.disconnect();
 }

Another option would be to use Apache library. And the code:
 HttpPost httpPost = new HttpPost("URL");
 StringEntity strEntity = new StringEntity(xmlData, "text/xml", "UTF-8");

 strEntity.setContentType("text/xml");
 httpPost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
 httpPost.setEntity(strEntity);
 HttpClient httpclient = new DefaultHttpClient();
 BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httpPost);