text:
Q: Serving dockerized microservices over HTTPS I'm currently struggling with docker and SSL. Let me give you an overview on what I'm trying to do.
I built a microservice-based architecture which is composed by a react web application and some "backend" services written in python and exposed with gunicorn on docker containers. I need to serve it over SSL because of Auth0 which needs the https communication. So, I built the server, bought a domain and got the SSL certificate for the domain with let's encrypt.
Now, here are the troubles, since mi services communicates to each other with a docker network, say services-network. For this reason they refer each other with the url `service:port/example.
At the moment I'm able to successfully connect to my web app with https but whenever this tries to contact the "backend" services the connection is refused because of it came from a non-secure resource (I used http://service:port/endpoint).
I tried to use the let's encrypt certificate generated for the webapp but the communication is blocked with message requests.exceptions.SSLError: HTTPSConnectionPool(host='service', port=8081): Max retries exceeded with url: /endpoint (Caused by SSLError(CertificateError("hostname 'service' doesn't match 'domain.com'",),))
I understand that a possible workaround for this error is to make the services communicate each other without using the docker network but the external one. Anyway I think that is not a good practice and that the communication among containers needs to be done through the docker network.
Finally, my question is: which is the best way to make the containers communicate through https over the docker network?

A: I personally like to use nginx as a reverse proxy. You would configure it normally and set it to proxy_pass <dockerIp:port>.
Many people like to use traefik.io which has many features including Let's Encrypt integration.


text:
Q: Setting delegate value with Groovy JsonBuilder (This is a follow up question to a question asked here)
I'm using Groovy's JsonBuilder to dynamically generate the following JSON:
{
    "type": {
        "__type": "urn",
        "value": "myCustomValue1"
    },
    "urn": {
        "__type": "urn",
        "value": "myCustomValue2"
    },
    "date": {
        "epoch": 1265662800000,
        "str": "2010-02-08T21:00:00Z"
    },
    "metadata": [{
        "ratings": [{
            "rating": "NR",
            "scheme": "eirin",
            "_type": {
                "__type": "urn",
                "value": "myCustomValue3"
            }
        }],
        "creators": [Jim, Bob, Joe]
    }]
}

Using this code:
def addUrn(parent, type, urnVal) {
    parent."$type" {
        __type "urn"
        "value" urnVal
    }
}

String getEpisode(String myCustomVal1, String myCustomVal2, String myCustomVal3) {
    def builder = new groovy.json.JsonBuilder()
    builder {
        addUrn(delegate, "type", myCustomVal1)
        addUrn(delegate, "urn", "some:urn:$myCustomVal2")
        "date" {
            epoch 1265662800000
            str "2010-02-08T21:00:00Z"
        }
       "metadata" ({
                ratings ({
                        rating "G"
                        scheme "eirin"
                        addUrn(delegate, "_type", "$myCustomVal3")
                })
                creators "Jim", "Bob", "Joe"
        })
    }

    return root.toString();
}

The code throws a StackOverflowError because of the third call to addUrn (under the nested ratings element.  If I comment that line out, it works perfectly (other than the fact that I'm missing a necessary chunk of info).

*

*Why is this happening?

*How to I set the delegate to the immediate parent, e.g. ratings?

I've tried using the metaClass to no avail.

A: This is pretty ugly (LOL) , but will give you the expected result:
def addUrn(parent, type, urnVal) {
    parent."$type" {
        __type "urn"
        "value" urnVal
    }
}

String getEpisode(String myCustomVal1, String myCustomVal2, String myCustomVal3) {
    def builder = new groovy.json.JsonBuilder()
    def root = builder {
        addUrn(delegate, "type", myCustomVal1)
        addUrn(delegate, "urn", "some:urn:$myCustomVal2")
        "date" {
            epoch 1265662800000
            str "2010-02-08T21:00:00Z"
        }
        "metadata" ([{([
                "ratings" ([{
                        rating "G"
                        scheme "eirin"
                        this.addUrn(delegate, "_type", "$myCustomVal3")
                }]),
                creators ("Jim", "Bob", "Joe")
        ])}])
    }

    println builder.toPrettyString()
}

Note:-

*

*In the previous question, I was incorrect in saying that delegate has
to refer to immediate parent. Actually it does refer to immediate
parent. Instead, we have to refer to the script (which has the
addUrn method) while calling the method, hence use of this when calling addUrn inside ratings. Alternatively you can ship "ratings" to a method similar to addUrn.

*The use and sequence of parenthesis, chain brace and square brace is important what you see after "metadata". Making understand that will be cumbersome here. But only thing to keep an eye on is to stick to the basics of using method calls, declaring lists and use of closures. Try to indent each brace per line, you would be able to grab the underlying magic. :)

*The reason for StackOverFlow error was that the method getEpisode was unable to reach  the method addUrn which is owned by the script.

Test it directly in Groovy Web Console

redpajama_set_name: RedPajamaStackExchange


text:
Q: Undeclared identifier error on using square() function given in a book I came across the square() function in a book on C++.
On implementing the function as given in the book Xcode gives an 'undeclared identifier' error. I have tried including 'cmath' and 'math.h' header files but it doesn't seem to fix the issue. I cannot find a header file for it and I am not even sure if that's the actual problem.
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    for(int x=0; x<10; ++x)
    {
        cout<< x << '\t' << square(x) << endl;
    }
}

EDIT: The book is called principles of C++ by Bjarne (the creator of C++)
And this guy wrote a whole chapter on Statements explaining it with several examples containing the undefined function square(). After 10 or so examples the next chapter starts with- "In the program above, what was square(i)?"
The code that confused me
Next chapter

A: There is no square() function in the c++ standard library, you need to implement it.
Anyway, there is the function pow(number, power), it calculates the power of a number, you can use it including the cmath header.


text:
Q: How to create rows that fill the time between events in Python I am building a data frame for survival analysis starting from 2018-01-01 00:00:00 and ending TODAY. I have two columns with start and end times only for the events that ocurred associated with an ID.
However, I need to add rows with the times between which the event was not observed
Here I show what I have:

+--------+-----+-----+---------------------+---------------------+
| State  | ID1 | ID2 | Start_Time          | End_Time            |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-04 04:00:00 | 2019-12-04 19:30:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-08 06:30:00 | 2019-12-20 10:00:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-22 11:00:00 | 2019-12-22 23:00:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-26 08:00:00 | 2019-12-29 16:30:00 |
+--------+-----+-----+---------------------+---------------------+
| State2 | 112 | AA2 | 2018-09-19 08:00:00 | 2018-09-20 04:30:00 |
+--------+-----+-----+---------------------+---------------------+
| State2 | 112 | AA2 | 2018-09-25 16:30:00 | 2018-09-26 23:00:00 |
+--------+-----+-----+---------------------+---------------------+
| State2 | 112 | AA2 | 2018-09-27 01:30:00 | 2018-09-27 10:30:00 |
+--------+-----+-----+---------------------+---------------------+

And what I need is:

+--------+-----+-----+---------------------+---------------------+
| State  | ID1 | ID2 | Start_Time          | End_Time            |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2018-01-01 00:00:00 | 2019-12-04 04:00:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-04 04:00:00 | 2019-12-04 19:30:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-04 19:30:00 | 2019-12-08 06:30:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-08 06:30:00 | 2019-12-20 10:00:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-20 10:00:00 | 2019-12-22 11:00:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-22 11:00:00 | 2019-12-22 23:00:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-22 23:00:00 | 2019-12-26 08:00:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-26 08:00:00 | 2019-12-29 16:30:00 |
+--------+-----+-----+---------------------+---------------------+
| State1 | 111 | AA1 | 2019-12-29 16:30:00 | TODAY               |
+--------+-----+-----+---------------------+---------------------+
| State1 | 112 | AA1 | 2018-01-01 00:00:00 | 2018-09-19 08:00:00 |
+--------+-----+-----+---------------------+---------------------+
| State2 | 112 | AA2 | 2018-09-19 08:00:00 | 2018-09-20 04:30:00 |
+--------+-----+-----+---------------------+---------------------+
| State2 | 112 | AA1 | 2018-09-20 04:30:00 | 2018-09-25 16:30:00 |
+--------+-----+-----+---------------------+---------------------+
| State2 | 112 | AA2 | 2018-09-25 16:30:00 | 2018-09-26 23:00:00 |
+--------+-----+-----+---------------------+---------------------+
| State2 | 112 | AA1 | 2018-09-26 23:00:00 | 2018-09-27 01:30:00 |
+--------+-----+-----+---------------------+---------------------+
| State2 | 112 | AA2 | 2018-09-27 01:30:00 | 2018-09-27 10:30:00 |
+--------+-----+-----+---------------------+---------------------+
| State2 | 112 | AA2 | 2018-09-27 10:30:00 | TODAY               |
+--------+-----+-----+---------------------+---------------------+

I have tried this code (borrowed from: How to find the start time and end time of an event in python?), but it gives me only the sequence of events, not the desired rows and the answer provided by @Fredy Montaño (below):
fill_date = []
for item in range(1,df.shape[0],1):
    if (df['End_Time'][item-1] - df['Start_Time'][item]) == 0:
        ""
    else:
        fill_date.append([df["State"][item-1], df["ID1"][item-1], df["ID2"][item-1], df['End_Time'][item-1],df['Start_Time'][item]])

df_add = pd.DataFrame(fill_date)
df_add.columns = ["State", "ID1", "ID2", 'Start_Time', 'End_Time']

df_output = pd.concat([df[["State", "ID1", "ID2", "Start_Time", "End_Time"]], df_add],axis = 0)
df_output = df_output.sort_values(["State", "ID2", "Start_Time"], ascending=True)

I think I have to put a condition over the STATE, ID1 and ID2 variables in order to not to take times from the previous groups.
Any suggestion?

A: Maybe this solution works for you.
I slice the dataframe only to take the dates, but it works for you you can repeat it taking into account the states and ID
df = df[['Start_Time', 'End_Time']]

fill_date = []
for item in range(1,df.shape[0],1):
    if df['Start_Time'][item] - df['End_Time'][item-1] == 0:
        ""
    else:
        fill_date.append([df['End_Time'][item-1],df['Start_Time'][item]])

df_add = pd.DataFrame(fill_date)
df_add.columns = ['Start_Time', 'End_Time']

and finally, I do a concat to join you original dataframe with the new df of dates of not Observed events dates on squares are the new
df_final = pd.concat([df,df_add],axis = 0)
df_final.sort_index(0)


text:
Q: How do i adjust the margin of an imageView according to it's shape? I have a imageView like this:
Primary Image
I want a this imageView margin like this:
 Desired Image
Can this be possible?

A: I had a similar issue to this a while back actually, the best options I know of are to create your own shape using a Path or you could add a few shapes to a Pane of some sort and get a relatively similar shape like so


text:
Q: WordPress takes too long to show 404 error on images (on LEMP stack) I have installed WordPress on LEMP stack on DigitalOcean and noticed that all the 404 images on the pages are taking too long to show a 404 error message.
Those images are not existing so it will give 404 errors but it just takes too long (4 to 6 seconds) to show a 404 error message.

Any suggestions?

A: While it is impossible to pinpoint why it takes so long without access to your server, the core issue is that when the webserver do not find a file it will execute wordpress to handle the URL, and as the URL is unlikely to match any content it will result in a generation of a 404 wordpress page which is obviously much slower than returning 404 at server level.
Usually it is not a problem as pages generated by wordpress rarely contain images which do not exist, but if this is an actual problem you can adjust you webserver config (.htaccess for apach) to not propagate unresolved image urls to wordpress.


text:
Q: Android FTP Upload very slow when using BufferedOutputStream I'm trying to build an Android app to perform upload speed tests using FTP, but with the following code, the upload speed doesn't go above 1 Mbps. While using an FTP client on the same device, I can get upload speeds of 15 Mbps. Can someone give me a help on this?
public class MultiUL extends Thread{

private String id="hhhhh0001";
private int bufferSize=32768;

public void run() {
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(MPSharkVar.Server,21); // Using port no=21
        ftp.login(MPSharkVar.FTPUser, MPSharkVar.FTPPwd);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
    } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
    uploadWork(ftp, id);
    try {
        ftp.disconnect();
    }
    catch (Exception ex)
    {
    }
}

private void uploadWork(FTPClient ftp, String id) {

    byte[] buffer = new byte[bufferSize];
    for (int i = 0; i < bufferSize; i++) {
        buffer[i] = 'F';
    }
    OutputStream os = null;
    BufferedOutputStream bos = null;
    long start = System.currentTimeMillis();
    long end = start;
    try {
        ftp.changeWorkingDirectory("/upload");
        os = ftp.storeFileStream(id);
        bos = new BufferedOutputStream(os);
        start = System.currentTimeMillis();
        end = start;
        while (((end - start) <= MPSharkVar.TestDur)) {
            bos.write(buffer, 0, buffer.length);

            end = System.currentTimeMillis();

        }
        } catch (Exception ex) {
            end = System.currentTimeMillis();
        } finally {

                try {
                    bos.flush();
                    bos.close();
                    os.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

        }
    }

}


text: Q: How to change the path of a falling sprite and let the sprite fall in curve way into a specific position in Andengine? I am having a sprite which falling to bottom.. Now in the touch action I want to change the path of that sprite and let it fall in a curve way(projectile manner).. Please suggest me what should  use..


text:
Q: How can I bring a record from another table with certain conditions from my table in DAX? I have two tables. One with dates and customer ID's of tech support given [Table 1], and the other one with surveys sent to the customers [Table 2]). The problem is that the surveys are sent some days after the service is done. So, I need to find the survey ID with the closest date from the survey table and bring it to my tech support table. Here's a sample of my data and the result wanted.
Table1:
TechSupportDate   CustomerID
01/12/2018          1
02/12/2018          2
05/12/2018          1

Table2:
SurveyID SurveyDate   CustomerID
1001     04/12/2018     1
1002     04/12/2018     2
1003     10/12/2018     1

EXPECTED RESULTS:
TechSupportDate    CustomerID SurveyDate     SurveyID
01/12/2018          1         04/12/2018      1001
02/12/2018          2         04/12/2018      1002
05/12/2018          1         10/12/2018      1003

A: Add calculated columns to Table1:
SurveyDate =
CALCULATE (
    MIN ( Table2[SurveyDate] ),
    FILTER (
        Table2,
        Table2[SurveyDate] >= Table1[TechSupportDate] && Table2[CustomerID] = Table1[CustomerID]
    )
)

and
SurveyID =
CALCULATE (
    FIRSTNONBLANK ( Table2[SurveyID], 1 ),
    FILTER (
        Table2,
        Table2[SurveyDate] = Table1[SurveyDate] && Table2[CustomerID] = Table1[CustomerID]
    )
)

Here's a worked example PBIX: https://excel.solutions/so_54693431/


text:
Q: Insert command result into vim command I'd like to find and replace some text with other text which consist the result of the shell command. This is my trial, which is not working:
:40,43s/'height': 650/'height': system('python -c "import random; print(random.randint(500, 600))"')/g

Vim don't want to evaluate system('python -c "import random; print(random.randint(500, 600)') part.
Please help me to fix this

A: Your "shell command" is not correct!

*

*you should at least check if those quotes (' and ") in your command are paired

*you should at least check if all brackets (..) in your command are paired.
For the vim :s command, you should use \= to get the result of an expression. Read :h :s\= for details.
Your example:
:40,43s/\v('height':) 650/\=submatch(1)." ".system('python -c "import random; print(random.randint(500, 600))"')/

Your command was fixed in above line.


text:
Q: How to make VoiceOver read out a different text than what's in the UITextView? I have a UITextView containing a text that is meant for sighted users. I want to add a different non-sighted user-friendly text that will be read-out when VoiceOver is on. I tried adding it as an accessibilityLabel, but VoiceOver read both text. How can I make it read out just the accessible text when VoiceOver is on?

A: it read out just the accessible text when VoiceOver is on below code useful
UITextView.AccessibilityValue="Your Text";

In that You pass text which

A: I'm not sure it's possible to vocalize a text that's different from the displayed one using a UITextView with VoiceOver... anyway, I haven't found any solution for that.
VoiceOver is not only used by blind people but also by sight-impaired people which means that it's important to maintain a link between what's displayed and what's vocalized.
Using a UITextView means that its text will be vocalized besides the possible accessibility label you add.
If you want to make it read out just the accessible text when VoiceOver is on :

*

*Listen to the UIAccessibilityIsVoiceOverRunning event.

*Update the text of your UITextView accordingly : myTextView.text = "text to be adapted to the context."
Following these steps will allow you to reach your goal.


text:
Q: simple html dom parser getting values I am using simple_html_dom.php
How to get following data
% Change-10.75

I want to get -10.75
t-loss occurs only once in html code

22,621

I want to get 22,621
bsevolume occurs only once in html code
please let me know what code should I use.
edit more info:
$bseVolume = $content->find("//p[contains(@class, 'data')]");

class : data appears multiple times in html but id="bseVolume" appears only once.
I tried
$vaue1 = $html->find("//p[contains(@id, 'bseVolume')]");
$volume1 = $bseVolume1[0]->innertext; echo $volume1 ;

The result is blank. Can you comment?

A: You can use Simple HTML DOM find to find the  or
 elements.
From the docs:

Find (N)th anchor, returns element object or null if not found (zero
  based)
$ret = $html->find('a', 0);

You could find the
 you are looking for like this:
$bseVolume = $html->find("p[id=bseVolume]", 0);
echo $bseVolume->innertext();

You could find the  you are looking for like this:
$tLoss = $html->find("td[class=t-loss] strong", 0);
echo $tLoss->innertext();


text:
Q: error in android studio package android.veiw does not exist 1 it showing a error package android.veiw does not exist in my android studio
2 when i add a buuton and use onClick
package com.example.batman.buttoncheck;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.veiw.Veiw;
import android.view.MenuItem;

public class Button_MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_button__main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_button__main, menu);
        return true;
    }
    public void buttononClick(Veiw v){
        //do nothing
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

A: Typo.
Change
import android.veiw.Veiw

to
import android.view.View

And similarly
public void buttononClick(Veiw v)

to
public void buttononClick(View v)


text:
Q: Eclipse error: Unable to find valid certification path to requested targer I have installed force.com IDE successfully in eclipse and trying to create new project but i am getting the below error message. Coould you please help me to come out from this issue.

A: This might be a bit old but I just encountered the same problem and it turns out that on the corporate network there was a self signed root SSL certificate.
In order to overcome this problem I had to add the SSL into the JVM keystore as described here

A: This looks like a Java truststore issue to me. If you had overwritten anything in the JVM installation, it may be affecting your connection to Salesforce.

A: I have resolved this issue follow the below steps.
Go to Eclipse IDE  Windows → Preferences → Network Connections and set Active Provider to Direct.
This issue is related to the Eclipse IDE Network Connections, i found this workaround from below Link
https://stackoverflow.com/questions/39576290/eclipse-neon-http-proxy-authentication-required-error/42691498#42691498


text:
Q: Keep wildcards from resolving in a ksh script I am reading in a list of file names:
*.txt *.xml

which are space delimited. I read this into a variable in my ksh script, and I want to be able to manipulate it before putting each of them into a find command. The problem is, as soon as I do anything with the variable (for instance, breaking it into an array), the * resolves into filenames that are in my script's directory. What I want is for the *.txt to remain unchanged, so I can put that into my find command.
How do I do this? Unfortunately, I'm at work and can't just use perl or some other language.

A: set -f
turns off globbing in ksh, so * and ? characters are not expanded (globbed).

A: what's wrong with
 '*.txt' '*.xml'

? . Else you have to show us more of your issues. Maybe edit your post to include a small test case that illustrates your problem, plus the desired output or intermediate values.


text:
Q: Как получить Пользовательские поля? Есть пользователи в базе BX24 которых я получаю по REST API посредством запроса user.get. Полученные данные не содержат прикреплённых пользовательских полей (UF_*). Как можно получить пользовательские поля пользователя? Можно и не через REST API.

A: Можно написать REST модуль и обращаться к нему:
$filter = isset($params['filter']) ? $params['filter'] : [];
$list   = CUser::GetList($by = '', $order = '', $filter, ['SELECT' => ['*', 'UF_*']]);

while ($fetch = $list->fetch()) {
    static::$users[$fetch['ID']] = $fetch;
}

A: Работа с пользовательскими полями в битриксе реализована очень плохо, разработчики рекомендуют использовать пользовательские свойства, а не поля. Обновить пользовательское поле (скорее всего любое) можно так:
$GLOBALS["USER_FIELD_MANAGER"]->Update("ORDER", $id, Array("UF_CRM_123123"=>$value));

*

*ORDER - имя сущности, в данном случае заказ

*$id - айди элемента в котором нужно изменить поле

*UF_CRM_123123 - айди поля

*$value - значение


text:
Q: Selecting a Div inside a Nav I am attempting to automate some functions within Chrome using Puppeteer and Chromium. I'm able to log in, select the main navigation element and the sub-navigation menu appears.  I'm currently playing in the console to find the correct selector to pass into Puppeteer, however, I'm having difficulty.
HTML below:

Text

Text

With in the Chrome console I can get somewhat close to making the  items accessible by using document.getElementsByClassName("task_launcher_item_heading")[0].childNodes[0].innerText, which will return the innerText of the element, but using the .click() method comes back undefined.
Any ideas will surely help.

A: It looks like you are just trying to target this guy and make him do something.

Text

if that is the case, can you use const Nav = document.getElementById();
 await Nav.click(); function instead and give it it's own ID while still retaining the task_launcher_item_click class?
Once you have the click on that specific element can you use a promise function https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#frameclickselector-options
const [response] = await Promise.all([
  page.waitForNavigation(waitOptions),
  frame.click(selector, clickOptions),
]);

or an attribute selector https://drafts.csswg.org/selectors-4/#attribute-selectors
const element = await page.$('[href="http://www.iana.org/domains/example"]');
    await element.click();
  } catch (err) {
    console.error(err);
  }
})();

A: Alright, someday I'm going to be a smart person...  my problem was I was using #popupTaskMenu > nav > div.nth-child(2)  when it should have been #popupTaskMenu > nav > div:nth-child(2)
I should have used a COLON rather than the period!!!!  2 hours of my life people!


text:
Q: How to make ubuntu fullscreen all the time How to make the ubuntu go full screen all time, as full screen is better for me. I can use F11 but a lot of system apps won't go full screen such as nautilus, system monitor won't go full screen.

A: It is not quite easy, and options are limited. Unfortunately, Linux desktops provide limited user control on the default size of newly created windows (I do not know whether the situation is any better in other OS´es). Then also, there is a difference between "maximized" and "full screen".
Suggestion 1. devilspie2 is a daemon that monitors the creation of windows, and automatically resizes or repositions them as they are created. You could configure it to full-screen any window, but then you would need to define exceptions such as File or Print dialogs, or any other window you do not want to be maximized.
Suggestion 2. Per application approach:
If you can live with "Maximized" rather than full screen, some applications remember their previous state. Examples include Firefox, Files, Text editor Gedit, Gimp, Inkscape
Other applications provide command line switches, for example Evince document viewer: evince --fullscreen, Gnome terminal: gnome-terminal --full-screen. For these applications, you could change their .desktop file to add the necessary command line arguments. A more robust approach could be to have your own wrapper scripts, which then would call the actual executable with the needed argument. The latter approach would not only work if you launch the application from the menu, but also when it is being launched from within another app, e.g. Evince from within Firefox.
This way, you should be able to set up a working environment where most applications by default open in a mximized state or at least full-screen. Not perfect, however, by all means. An approach with devilspie would be more perfect, but more difficult to setup.


text:
Q: How to write a practical https client in golang I am building a https client in golang, which is supposed to connect to a specified host and get the server name from the header or the certificate of the host. This is my code
package main

import (
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    caCert, _ := ioutil.ReadFile("./cacert.pem")
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    conf := &tls.Config{RootCAs: caCertPool}
    conf.BuildNameToCertificate()
    tr := &http.Transport{TLSClientConfig: conf}
    cli := &http.Client{Transport: tr}
    resp, _ := cli.Head("https://www.google.com")
    fmt.Println(resp.TLS.ServerName)
}

But it is running into a panic
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x88 pc=0x401314]

goroutine 1 [running]:
panic(0x7145e0, 0xc82000a100)
/usr/local/go/src/runtime/panic.go:464 +0x3e6
main.main()
/home/huangjian/anti-GFW/go-checkgoogleip/checkip.go:22 +0x314
exit status 2

Maybe I am lack of solid knowledge of public key encryption but now I just want to make it work. Could anyone tell me where did I do wrongly and how to correct it?


text:
Q: Polygonal Divs -- Making content overflow in a specific shape? Here is the site I'm currently working on: http://willcrichton.net/
If you click on the arrows on each side of the hexagon in the middle, you can see that it transitions left and right using jQuery + jQuery Cycle + jQuery Easing. However, you can also see that it is rather ugly -- because I'm using hexagons and not squares and because divs are square shaped, the content hexagon overlaps with with the background in an unpleasant way.
So, my question is: how would I essentially hack a div into a hexagon? That hexagon should be the same size/shape of the content div, and when content is outside the area of the hexagon it should be invisible.
Edit:
HTML

CSS
/* Container styles */

#container {
    width: 908px;
    height: 787px;
    left: 50%;
    top: 50%;
    position: absolute;
    margin-top: -393.5px;
    margin-left: -452px;
    background-image: url("images/background.png");
    font: 12px "Lucida Sans Unicode", "Arial", sans-serif;
    z-index: 3;
}

#content {
    width: 686px;
    height: 598px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -282px;
    margin-left: -343.5px;
    /*background-image: url("images/hacky_hole2.png");*/
    z-index: 1;
}

    .slide {
        width: 100%;
        height: 100%;
        background-image: url("images/content.png");
        position: relative;
        z-index: 2;
    }
UPDATE: If you check the site now, you'd see my failed attempt at using the "window" method and you can see why the z-index did not work.

A: You can't make a div into a hexagon, but you could use PNG files with alpha transparencies to mask the area you want. So, you would need to make four divs, each with a background that has a PNG file with the transparency that acts as a mask. These divs would be positioned absolutely over your div with the slider.
EDIT: As Pekka noted below, this could also be done with a single, large PNG file acting as a mask.
EDIT #2: Looking at the code you posted, I would revise it like this:

Note that I closed the
 element. This element should be a sibling of your slides, but be positioned above the slides with a higher z-index. Or, you may need to create a new element dedicated to displaying the mask, if your "content" div is used for other purposes than just displaying the mask.

A: If it was me developing, I would make that two layer link of yours, into a tree layer...
ex:

1. Layer with the existing background
2. Layer with the gray hexagon
3. Layer with the surrounding words and the surrounding background

Like that, when you click the left and right arrows, the gray hexagon will me sliding in the middle of the 1. and 3. layers, thus preventing that ugliness that you've mentioned :)
Hope it helps!

A: Eric Meyer's curvelicious concept and demo might point you in the right direction. It's a complicated hack from the "early days of CSS", but it's a powerful technique.


text:
Q: Error in WCF service value does not fall within the expected range In one of our code, we are getting below error.
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Web.Util.Misc.ThrowIfFailedHr(Int32 hresult)
   at System.Web.Hosting.IIS7WorkerRequest.SetUnknownRequestHeader(String name, String value, Boolean replace)
   at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
   at System.Web.HttpHeaderCollection.Add(String name, String value)

Code is as below:
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            string correlationId = newAuditTrail.GetCorrelationIdFromRequest(request).ToString();
            string url = newAuditTrail.GetUrlFromRequest(request).ToString();

            HttpContext.Current.Request.Headers.Add("CorrelatinId", correlationId);
            HttpContext.Current.Request.Headers.Add("Url", url);

Error is thrown on line:
HttpContext.Current.Request.Headers.Add("CorrelatinId", correlationId);
I noticed operation contract of method, it is defined as oneway.
[OperationContract(IsOneWay=true)]

A: If you want to add http header in the http request, please refer to the below code segements.
    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request,  System.ServiceModel.IClientChannel channel)
{
    HttpRequestMessageProperty httpRequestMessage;
    object httpRequestMessageObject;
    if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
    {
        httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
        if (string.IsNullOrEmpty(httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER]))
        {
            httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER] = this.m_userAgent;
        }
    }
    else
    {
        httpRequestMessage = new HttpRequestMessageProperty();
        httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, this.m_userAgent);
        request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
    }
    return null;
}

We could also use WebOperationContext to add http header on the client-side.
Add Request header to WCF when using ConfigurationChannelFactory.CreateChannel
Please refer to the below discussion.
How to add a custom HTTP header to every WCF call?
Feel free to let me know if the problem still exists.


text:
Q: Displaying special character (which name I don't know) I'm writing a summary of a lecture that I'm visiting at the moment. Today, I encountered a symbol, which I did not know and even not know how to write on a computer. Since the summary is written in LaTeX, I decided to post the question here. Unfortunately, since I don't know how the symbol's called, I can't research on my own.
This is the symbol:

EDIT: As in the picture, I assume that this is not a simple block quote symbol. Additionally, the subject environment where I found the symbol is the programming language C.

A: My guess is that that character is a typographic error and the author should have written \verb|'\"'|, producing:

since this is indeed a way to specify one character constant containing the character double quote ("), in C language (in fact, the \ is superflous in this case, but nevertheless it can be put too). I could verify my guess if you provide more context about the part in the book in which that fragment appears.
My main concern now is, how in the world the author of the book managed to type a diaeresis (¨) when he intended to type a double quote (")?
One possible answer is that he doesn't know the difference, which seems unlucky in a book about programming, and even in this case typing a ¨ would be more difficult than typing a ".
Another possible answer is that he writes in an editor configured to use the quote and double quote symbols as diacritics. That is, if he writes ' followed by e, he gets é, or if he types " followed by o he gets ö. In this case to get " he probably would have typed " twice, but instead typed  " followed by a space (or by ') and got ¨.
Finally, a third option, and the most probable IMHO, is that instead of using verbatim to typeset that fragment, the author used the following command:
\texttt{'\textbackslash"'}

This produces:

Which still does not show the diaeresis, but it shows a backslash more similar to the one in your figure.
How the diaeresis could come? I think that the author was using some babel package for foreign languages. It is common that those packages make " an active char in order to facilitate the input of diacritics. For example, spanish package makes so, and when you type "u in the source you get ü in the document. However, the combination "' issues an error with spanish, so that could not be the language the author used. Perhaps you can clarify in which language the document is written.
Addendum (off topic)
About the use of the unicode character U+00A8 in the modern world, I have to say that, despite the fact that letters such as ö, ü, etc. have their own Unicode point (which is U+00F6 and U+00FC respectively) the Unicode standard also allows their codification as the sequence of two unicode chars: o¨ and u¨, respectively (U+006F, U+00A8 and U+0075, U+00A8). So U+00A8 is not entirely useless. In fact, OSX uses this way of coding diacritics in the name of the files and folders in its filesystem! (which causes some troubles).

A: The symbol posted is U+00A8 DIAERESIS. It has hardly any known usage in any human language or formalism; it is a holdover from the old days when such printing characters were sometimes thought of being used as diacritic. It has no defined meaning in C.


text:
Q: google sheets substitute multiple I have a google spreadsheet that I am importing data from a website. When the data is pulled, it has extra quotes and equal signs. I can use the Substitute function to get rid of one of the characters, but when I try to use the substitute function to remove both quotes and text, Sheets only pulls one cell of data.
Formula:
=IMPORTDATA("https://ct.thecmp.org/app/v1/index.php?do=match&task=downloadMatchResultsDetail&MatchId=12504&EventId=4&AwardId=1")

Result: Pulls all data, but includes extra quotes and = signs.
Formula:
=Substitute(IMPORTDATA("https://ct.thecmp.org/app/v1/index.php?do=match&task=downloadMatchResultsDetail&MatchId=12504&EventId=4&AwardId=1"),char(61),"")

Result: Pulls only one cell of data, and only gets rid of equal sign.
Formula:
=Substitute(Substitute( IMPORTDATA("https://ct.thecmp.org/app/v1/index.php?do=match&task=downloadMatchResultsDetail&MatchId=12504&EventId=4&AwardId=1"),char(61),""),char(34),"")

Result: Pulls only one cell of data and removes both extra quotes and equal signs.
A work around I have been able to achieve the desired results:
I can use the
Formula:
=IMPORTDATA("https://ct.thecmp.org/app/v1/index.php?do=match&task=downloadMatchResultsDetail&MatchId=12504&EventId=4&AwardId=1")

and then use formulas like:
=substitute(substitute(B22,char(34),""),char(61),"")

for every cell that has the imported data. It's not very clean though, and if possible I would like to have it done in one step.
One of the complications I will run into at the end of the project is that I am importing the data over my phone's hotspot. The location that I will be in has coverage, but is not very reliable, so any way to keep the amount of data transferred at a minimum would be great.
Link to example spreadsheet:
https://docs.google.com/spreadsheets/d/1-cV3llUpZsrjRb4izTXVtDPsTmP15xkWDmfKjPjopDI/edit?usp=sharing

A: You could also do this: replace the 'download 'parameter in your download url to the word 'get' (see below):
instead of https://ct.thecmp.org/app/v1/index.php?do=match&task=downloadMatchResultsDetail&MatchId=12504&EventId=4&AwardId=1
put:
instead of https://ct.thecmp.org/app/v1/index.php?do=match&task=getMatchResultsDetail&MatchId=12504&EventId=4&AwardId=1
then just use one function for importhtml:
=IMPORTHTML("https://ct.thecmp.org/app/v1/index.php?do=match&task=getMatchResultsDetail&MatchId=12504&EventId=4&AwardId=1","TABLE",1)

A: Try:
=arrayformula(substitute(SUBSTITUTE( IMPORTDATA("https://ct.thecmp.org/app/v1/index.php?do=match&task=downloadMatchResultsDetail&MatchId=12504&EventId=4&AwardId=1") ,char(61) , "" ),char(34),""))


text:
Q: Why I have "model." in front of every key name of the state dict? I have trained my ResNet50 model with Pytorch Lightning framework. Everything was same as usual. After getting my .pth file (which is state dict file for my model), when I loaded the file back and tried to test the model, I got this error. It seens that every keys in the state_dict had "model." added above each key name. Is there any way to fundamentally fix this instead of just replacing keys in the .pth file?
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-6-c321e72c89af> in <module>()
      1 model = ResNet50()
----> 2 model.load_state_dict(torch.load(PATH))
      3 model.eval()

/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in load_state_dict(self, state_dict, strict)
   1481         if len(error_msgs) > 0:
   1482             raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
-> 1483                                self.__class__.__name__, "\n\t".join(error_msgs)))
   1484         return _IncompatibleKeys(missing_keys, unexpected_keys)
   1485

RuntimeError: Error(s) in loading state_dict for ResNet:
    Missing key(s) in state_dict: "conv1.weight", "bn1.weight", "bn1.bias", "bn1.running_mean", "bn1.running_var", "layer1.0.conv1.weight", "layer1.0.bn1.weight", "layer1.0.bn1.bias", "layer1.0.bn1.running_mean", "layer1.0.bn1.running_var", "layer1.0.conv2.weight", "layer1.0.bn2.weight", "layer1.0.bn2.bias", "layer1.0.bn2.running_mean", "layer1.0.bn2.running_var", "layer1.0.conv3.weight", "layer1.0.bn3.weight", "layer1.0.bn3.bias", "layer1.0.bn3.running_mean", "layer1.0.bn3.running_var", "layer1.0.shortcut.0.weight", "layer1.0.shortcut.1.weight", "layer1.0.shortcut.1.bias", "layer1.0.shortcut.1.running_mean", "layer1.0.shortcut.1.running_var", "layer1.1.conv1.weight", "layer1.1.bn1.weight", "layer1.1.bn1.bias", "layer1.1.bn1.running_mean", "layer1.1.bn1.running_var", "layer1.1.conv2.weight", "layer1.1.bn2.weight", "layer1.1.bn2.bias", "layer1.1.bn2.running_mean", "layer1.1.bn2.running_var", "layer1.1.conv3.weight", "layer1.1.bn3.weight", "layer1.1.bn3.bias", "layer1.1.bn3.running_mean", "layer1.1.bn3.running_var", "layer1.2.conv1.weight", "layer1.2.bn1.weight", "layer1.2.bn1.bias", "layer1.2.bn1.running_mean", "layer1.2.bn1.running_var", "layer1.2.conv2.weight", "layer1.2.bn2.weight", "layer1.2.bn2.bias", "layer1.2.bn2.running_mean", "layer1.2.bn2.running_var", "layer1.2.conv3.weight", "layer1.2.bn3.weight", "layer1.2.bn3.bias", "layer1.2.bn3.running_mean", "layer1.2.bn3.running_var", "layer2.0.conv1.weight", "layer2.0.bn1.weight", "layer2.0.bn1.bias", "layer2.0.bn1.running_m...
    Unexpected key(s) in state_dict: "model.conv1.weight", "model.bn1.weight", "model.bn1.bias", "model.bn1.running_mean", "model.bn1.running_var", "model.bn1.num_batches_tracked", "model.layer1.0.conv1.weight", "model.layer1.0.bn1.weight", "model.layer1.0.bn1.bias", "model.layer1.0.bn1.running_mean", "model.layer1.0.bn1.running_var", "model.layer1.0.bn1.num_batches_tracked", "model.layer1.0.conv2.weight", "model.layer1.0.bn2.weight", "model.layer1.0.bn2.bias", "model.layer1.0.bn2.running_mean", "model.layer1.0.bn2.running_var", "model.layer1.0.bn2.num_batches_tracked", "model.layer1.0.conv3.weight", "model.layer1.0.bn3.weight", "model.layer1.0.bn3.bias", "model.layer1.0.bn3.running_mean", "model.layer1.0.bn3.running_var", "model.layer1.0.bn3.num_batches_tracked", "model.layer1.0.shortcut.0.weight", "model.layer1.0.shortcut.1.weight", "model.layer1.0.shortcut.1.bias", "model.layer1.0.shortcut.1.running_mean", "model.layer1.0.shortcut.1.running_var", "model.layer1.0.shortcut.1.num_batches_tracked", "model.layer1.1.conv1.weight", "model.layer1.1.bn1.weight", "model.layer1.1.bn1.bias", "model.layer1.1.bn1.running_mean", "model.layer1.1.bn1.running_var", "model.layer1.1.bn1.num_batches_tracked", "model.layer1.1.conv2.weight", "model.layer1.1.bn2.weight", "model.layer1.1.bn2.bias", "model.layer1.1.bn2.running_mean", "model.layer1.1.bn2.running_var", "model.layer1.1.bn2.num_batches_tracked", "model.layer1.1.conv3.weight", "model.layer1.1.bn3.weight", "model.layer1.1.bn3.bias", "mod...

A: You need to initiate your model in the same manner as done during training.
For example, model= torchvision.models.resnet50() for training.You have to initialize the model in same manner.


text:
Q: Check for DNS records pointing to an IP I have noticed the past few weeks that I am receiving a lot more 404s than usual in my log.
When I looked at the errors I noticed that it's several different IP addresses looking for the same files which leads me to suspect that there might be DNS record(s) out there that could be pointing to my site.
Although this might be unlikely, I did come across difficulty trying to find all records pointing to the server's IP address as a reverse lookup does not meet this requirement.
How can one find all DNS records that point to a particular IP address or is this not possible?
Thanks in advance,
NOTE: Before anyone questions whether or not it is a link in my webapps pointing to it, it's not. For instance, there are queries looking for WordPress files and none of the apps on the server use WordPress.

A: It is not very uncommon to expect those malicious wordpress calls. The bots usually go over a for-loop of public IP addresses and once they find a live host they start the second step i.e. try logging in with a dictionary of username/passwords. You need not worry about them, simply block them or add a basic auth to your web app.


text:
Q: Disable background touch SpriteKit iOS I'm making a simple game that recognises touches on specific nodes and it works when I click on that specific node it NSLog(@"correct"); if clicked on another node NSLog(@"wrong"); I recognise the wrong node using this
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch * touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];

    if ([node.name isEqualToString:@"correct"]){
        NSLog(@"correct");
    }else if (![node.name isEqualToString:@"correct"]){
        NSLog(@"Wrong");
    }
}

that works well but when I click on the background it NSLog(@"Wrong") I want to disable background touches. How can I disable it?
Thanks in advance

A: You must be using some like SKNode *node = [self nodeAtPoint:touchLocation]; in your touchesBegan method. That being the case, check if node == nil. If yes, you are not touching a node.
If you have a background or worldNode, add code to check, by assigning it a unique name, if the background node is being touched.


text:
Q: Trying to get the json data located on http end point I am trying to get the http end point data which is in json format using the below code but the output which I receive is not as it's visible at the link posted below. Can you share your inputs on how to do this?
Code :-
import requests
r = requests.get('http://headers.jsontest.com/')

print( r.json() )

Output what I am receiving :-
{u'Host': u'headers.jsontest.com', u'User-Agent': u'python-requests/2.18.4', u'Accept': u'*/*', u'X-Cloud-Trace-Context': u'9034981eba16654b42daa1d10f503cab/2431501768736408823'}

Output what I would like to see( Pls open the link ) :-
http://headers.jsontest.com/
   {
       "X-Cloud-Trace-Context": "37e49d37206663367d675c2ff01db8a2/15699104367477007142",
       "Upgrade-Insecure-Requests": "1",
       "Accept-Language": "en-US,en;q=0.9",
       "X-IMForwards": "20",
       "Host": "headers.jsontest.com",
       "Referer": "http://www.jsontest.com/",
       "Via": "1.1 ironport-s680.air-worldwide.com:80 (Cisco-WSA/9.0.1-162)",
       "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
       "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
    }

A: In fact you do get the correct HTTP response. It just depends on how you send it (through browser or an empty request from Python)
When you open it through your browser, additional headers are added by the browser itself. When you send your request through requests in Python, those headers are not sent.
The HTTP response just mirrors the headers we sent to it. So if you want to see the same response, you'll have to send the headers manually using requests.
You can add them like that:
headers = {
       "X-Cloud-Trace-Context": "37e49d37206663367d675c2ff01db8a2/15699104367477007142",
       "Upgrade-Insecure-Requests": "1",
       "Accept-Language": "en-US,en;q=0.9",
       "X-IMForwards": "20",
       "Host": "headers.jsontest.com",
       "Referer": "http://www.jsontest.com/",
       "Via": "1.1 ironport-s680.air-worldwide.com:80 (Cisco-WSA/9.0.1-162)",
       "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
       "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
    }

import requests
r = requests.get('http://headers.jsontest.com/', headers = headers)

print( r.json() )

This returns:
{u'Via': u'1.1 ironport-s680.air-worldwide.com:80 (Cisco-WSA/9.0.1-162)', u'Acce
pt-Language': u'en-US,en;q=0.9', u'X-IMForwards': u'20', u'Accept': u'text/html,
application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', u'
Upgrade-Insecure-Requests': u'1', u'Host': u'headers.jsontest.com', u'Referer':
u'http://www.jsontest.com/', u'X-Cloud-Trace-Context': u'37e49d37206663367d675c2
ff01db8a2/14205897462093082399', u'User-Agent': u'Mozilla/5.0 (Windows NT 6.1; W
in64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/53
7.36'}


text:
Q: Efficiency of a sequential process I'm not sure if this is more of a programming question or a mathematical one. Please let me know the proper forum to ask this in, if this isn't the one.
I have a sequential process as follows:

*

*There are $n$ coins scattered in a square grid of $100 \times 100$ points.

*There are $m$ agents at a central location, i.e., the point $(50,50)$.

*These agents can do a random walk on the grid, moving one gridpoint in one step. In one time step, all the agents move one step from their current position.

*The agents are supposed to find the coins. Once an agent finds a coin, the time step is noted. Then, the agent proceeds to move to the central location along the shortest path from the point where the coin was found. Again, in one time step, the agent can move only one gridpoint, while other agents might still be searching for other coins.

*Once the agent with the coin reaches the central location, the coin is left and the agent starts searching for other coins again.

*The process stops when a specified number of time steps are over, irrespective of whether all the coins have been found.

In the general process, I have control over the distribution of coins, whether all the agents leave at once or at certain time steps, and whether they can interact with each other to reduce exploring the same area again. In the end, I want to find how quickly are the coins found by the agents. I'm looking for a way to quantify this efficiency of finding coins in the generalized case of $n$ coins and $m$ agents. This means, if I want to compare 10 agents finding 100 coins with 5 agents finding 50 coins, this quantity should be able to tell me in which case the agents were more efficient in finding the coins. I can plot the percentage of coins found over time, and this is usually an S-curve, but as my parameters increase, I think it'd be better if I had single values to compare rather than plot-lines.
In my opinion, I think the three parameters that would play a role in determining this efficiency are the distance of a coin from the centre, the time steps taken by an agent to find the coin starting from the centre, and the total number of agents in the area searching for coins. But I'm not sure what would be a good way of relating them together.

A: Partial Answer
We have a lattice graph $G$ with an identified node as the central node, $c$.
Let $$N=V \space \text{\\} \space \{c\},$$ i.e., $N$ is the set of nodes of $G$ excluding $c$.
Let $$S = \{ p_n | p_n \text{is the shortest path between } c, n \in N \}$$
If we constrain the problem by saying the number of agents $k$ that will be deployed is determined at $t = 0$ and remains constant throughout the simulation, we can choose $$k = |S|$$
This assigns one agent to each shortest path $p_n$ and we can affirm that there are no contentions between agents that we have to model.
Let $d_{n,0}, d_{n,1}, \dots, d_{n,j}$ be the sorted distances of the coins from $c$ for path $p_n$ i.e., $d_{n,j} < d_{n,j+1}$.
Consider the paths $(c,x)$ and $(c,y)$. We could have two agents on these paths and they could have collected the coins at $x, y$ respectively. Who gets priority while returning back to $c$? The answer is, it does not matter as they are both equidistant from $c$.
Therefore, we will assume the convention without loss of generality that the agent on the shorter path will have priority. This helps us simplify our calculation.

Let $m_n$ be the number of coins on the path $p_n$. Let $c_n$ be the number of coins collected on the path $p_n$.
$c_n$ is constrained by
$$\sum_{k=1}^{m_n} 2d_{n, k} \le t$$
The total number of coins collected is given by
$$C = \sum_{i=1}^{n} c_i$$
Let $M$ be the number of agents. Then the average productivity of the agent is given by
$$C \over M$$
Let $C_{total}$ be the total number of coins. Efficiency $(\eta)$ of the deployment in terms of coins collected would be
$$\eta = {C \over C_{total} } \times 100 \text{%}$$
Prologue: This becomes very complicated if you allow more agents than the number of shortest paths to coins because you would then need to model when those agents can enter the field, how many can enter the field and how they coordinate with the primary agent on the shortest path without causing contention.
In theory, once a shortest path is cleared of all coins (this will occur if $c_k < t$ for any $k$), all paths that are connected to it by an edge can make use of it to line up agents-in-waiting. As soon as one of those agents sees a coin at a distance $x$ from it lying on a connected shortest path $p_m$ and the coin is at a distance of $d_{n,r}$ and there is no other coin between that coin and $c$ and the primary agent is moving towards $c$, the agent-in-waiting can move to collect that coin.

In the figure above, $r$ is an agent moving towards $c$ with a collected coin. The light blue nodes are agents-in-waiting. The agent $a$ can move to collect coin $j$ and follow $r$.
This will help improving the efficiency. We could use the shortest path from an agent-in-waiting to a coin and dispatch the agent to that coin. However, this gets complex very quickly and I am not sure of a simple way to compute the number of coins collected.


text:
Q: moment checking date validate How can I check the validity of the date?
whether she passed or not.
I've tried everything. And I read the documentation. But it's not working for me.
I tried it this way:
 if ('2023-03-03 12:22:16' > moment().format('DD/MM/YYYY h:mm:ss')) {

        } else {
            return reply('Your current subscription has not expired. Wait for it to expire')
        }

tried to use: isBetwen, isBefore i.e

A: You can do this without the use of moment.js, just with native JavaScript methods.
You can't compare date strings, you need to convert them to timestamps and compare two timestamps. In your case you can do this:
if (new Date('2023-03-03 12:22:16').getTime() > new Date().getTime()) {
  ...
} else {
  return reply('Your current subscription has not expired. Wait for it to expire');
}


text:
Q: fetch data contiuously from a url <?php

 $url='http://apidintegra.tkfweb.com/apid/request?method=getListingData&mk=186;6&pk=12,0,1;3,1,1;33,537,1;33,579,1&psk=none&ik1=86103141,344,333&ci=iD2&ui=SG31378-narnapid01&id=893238542';
function get_data($url)
{

$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$xml_data=(get_data($url));

I want to dynamically fetch data from the url which I did,the url being
    stored in $url, now I want to continuously fetch data from this url
    and store it in $url,this is actually stock exchange API,which needs to be
    constantly refreshed.Any help would be appreciated.

A: Use cronjobs if you have server with root access, more about crons here: https://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/
If you have hosting, ask for support, most hostings have custom schedule systems which works like cronjobs.

A: First, Login to UNIX/Linux system.
Type the following command to enter cronjob:
$ crontab -e

Each cronjob has the following syntax:
# +---------------- minute (0 - 59)
# |  +------------- hour (0 - 23)
# |  |  +---------- day of month (1 - 31)
# |  |  |  +------- month (1 - 12)
# |  |  |  |  +---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
  *  *  *  *  *  command to be executed

Ex:
To execute myscript.php every 1 hour do the following:
# crontab -e
00 * * * * /usr/local/bin/php /home/john/myscript.php

Run the php script using URL from the crontab
If your php script can be invoked using an URL, you can lynx, or curl, or wget to setup your crontab as shown below.
The following script executes the php script (every hour) by calling the URL using the lynx text browser. Lynx text browser by default opens a URL in the interactive mode. However, as shown below, the -dump option in lynx command, dumps the output of the URL to the standard output.
00 * * * * lynx -dump http://www.thegeekstuff.com/myscript.php

Reference


text:
Q: What's the sizeof the virtual function table pointer? In single inheritances, is the size of a pointer to virtual table always equal to the size of a void*? Say,
class vft { virtual ~vft(); }
assert (sizeof(vft) == sizeof(void*));

Would that assertion always be true?

A: No, Virtualism is implementation defined. It is an compiler implementation detail.
So you cannot say that will be true always.
Also, You should refrain yourself from writing any code(like the one in Question) that assumes an detail that is left open by the Standard as an compiler implementation detail, Because that makes your code not 100% portable across compilers & might even fail drastically on some compilers.

A: The C++ ISO Standard says nothing about virtual function table pointer in the first place. A Compiler may follow this mechanism to support runtime-polymorphism or can come up with any other which doesn't even involve vptr. Its entirely upto the compiler writers. Since the Standard doesn't say anything about vptr, how can it say about its size? No way. The conclusion is: what you're doing (or assuming) isn't gauranteed by the language. However, for a compiler, it might be always true.
As a sidenote, for your compiler, how can you conclude that sizeof(vft) will be equal to sizeof(vptr)? It could very well be that sizeof(vft) > sizeof(vptr). I don't claim that though.

A: This is implementation-dependent.

A: "Would that assertion always be true?" Depends on what you mean by "always".
As others have already pointed out, this is an implementation detail that is subject to change even with different versions of the same compiler. The C++ standard says nothing about it, so you can't rely on it.
On the other hand, I've never seen a compiler where this wouldn't be true.

A: Aside from the facts that everyone else already pointed out, I feel like the standard does give some guarantees.  Namely, for class vft { void* a, b; virtual ~vft(); } then sizeof(vft) > sizeof(void*).  I'm pretty sure the standard guarantees that much at least, virtual functions or no.


text:
Q: What is the most beginner-friendly book for information geometry? Question: What is the most beginner-friendly book for information geometry?
The book:

*

*Amari and Nagaoka, Methods of Information Geometry,

is often mentioned as a reference for information geometry.
However, Amari has also written several other books about the subject, at least two of which also seem like they are oriented towards beginners:

*

*Amari, Differential Geometric Methods in Statistics.

*Amari, Information Geometry and its Applications.

These two books by different authors also seem targeted towards beginners:

*

*Arwini, Dodson, Information Geometry.

*Murray, Differential Geometry and Statistics.

In case Amari is one of those geniuses who has so much to say about their ideas that they can't possibly explain it concisely/simply/straightforwardly, perhaps it might be better to start with something written secondhand by another author.
I also have access to these other books, which seem like they are more advanced monographs, but I am not really certain, so I am mentioning them here anyway:

*

*Cencov, Statistical Decision Rules and Optimal Inference.

*Kass, Vos, Geometrical Foundations of Asymptotic Inference.

This thesis (later published as a book) also seems relevant:

*

*Lebanon, Riemannian Geometry and Statistical Machine Learning.

What I often do is read a lot of books and get only a little out of each (because I don't spend any time thinking about any of them or doing any of the problems).
However, this time, instead of reading eight books, which would be exhausting anyway, I want to focus on one and only one but get a lot out of it.
Thus any informed suggestions or recommendations would be useful/helpful.
Note: Also there is the issue of there being other applications to statistics of differential geometry than just the field of information geometry itself, per se, although I am not knowledgeable about this distinction at all. All of the above books seem to reference Riemannian metrics and exponential families of random variables in some way, so I assume they are about information geometry, but if that is not the case for one of them, that would make for a simple and easy elimination criterion.

A: I also think these books are quite hard to read at the first place too (but I'm an applied guy). For me, it was simpler to start with scattered material/tutorial/applications using bits of IG such as: Pattern learning and recognition on statistical manifolds: An information-geometric review
.


text:
Q: Forum database design I want to create my own forums system.
a forum contains threaded topics which means a user can response to the main topic
and response can be responded again (tree structure)
my database design for now is one large table which contains all the messages.
every message has 'response_to' field which holds the id of the messages it's responding to.
I'm not sure it's a good design to have all the those messages in one large table, although
it sounds intuitive for me. maybe I should separate topics from response messages?
in conclusion,
what is the best practice in designing DB for forums system?
I want to follow the best practice design and do it once.
so I'd appreciate your help.
thanks, sock.socket :)

A: If any response can be responded to (seperately from the original thread) then a self-referenced table is valid. You might find exactly the same thing in any multi-level hierarchy e.g. employees and managers.
FRom my own experience, the main problem is not the coding of the nested tree structure, it's the performance of a page load when a large number of threads are to be retrieved and displayed, or the self-referencing goes to a large number of levels.
So be careful to make sure you have good indexes on the MessageID and RespondTo columns, to help when joining.


text:
Q: The getter 'todoText' isn't defined for the class 'String' I am getting the following error in my code.

The getter 'todoText' isn't defined for the class 'String'.
Try importing the library that defines 'todoText', correcting the name to the name of an existing getter, or defining a getter or field named 'todoText'.dart(undefined_getter)

    import 'package:flutter/material.dart';
    import 'package:fluttertoast/fluttertoast.dart';
    void main() => runApp(new ToDoApp());

    class ToDoApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'To Do Application',
          theme: new ThemeData(
            primarySwatch: Colors.teal,
           ),
          home: new ToDoList(),
        );
      }
    }

    class ListItem{
      bool _todoCheck;
      ListItem(this._todoCheck);
    }
    class _strikeThrough extends StatelessWidget{

      final String todoText;
      final bool todoCheck;
      _strikeThrough(this.todoText, this.todoCheck) : super();

      Widget _widget(){
        if(todoCheck){
          return Text(
            todoText,
            style: TextStyle(
              decoration: TextDecoration.lineThrough,
              fontStyle: FontStyle.italic,
              fontSize: 22.0,
              color: Colors.red[200],
            ),
          );
        }
        else{
          return Text(
            todoText,
            style: TextStyle(
              fontSize: 22.0
            ),
          );
        }
      }

      @override
      Widget build(BuildContext context){
        return _widget();
      }
    }
    class ToDoList extends StatefulWidget {
      @override
      createState() => new _TodoListState();
    }

    class _TodoListState extends State<ToDoList> {

      var textController = TextEditingController();
      var popUpTextController = TextEditingController();

      List<String> _todoItems = [];
      List<ListItem> WidgetList =[];
      void _addToDoItem(String task){
        if(task.length > 0){
          setState(()=> _todoItems.add(task));
        }
      }

      void _removeToDoItem(int index){
        setState(() => _todoItems.removeAt(index));
      }

      void _promptRemoveToDoItem(int index){
        showDialog(context: context,
        builder: (BuildContext context){
          return new AlertDialog(
            title: new Text('Mark "${_todoItems[index]}" as Completed?'+' This will remove this Item'),
            actions: <Widget>[
              new FlatButton(
                child: new Text('CANCEL'),
                onPressed: () => Navigator.of(context).pop()
                ),
             new FlatButton(
                child: new Text('MARK AS DONE'),
                onPressed: () {
                  _removeToDoItem(index);
                  Navigator.of(context).pop();
                  Fluttertoast.showToast(
                    msg: 'ToDo Task Deleted!'
                    );
                }
                ),
            ]
          );
        }
        );
      }

     Widget _buildToDoList(BuildContext context){
       return Column(
         children: <Widget>[
           new Flexible(
             child: new ListView.builder(
              itemBuilder: (context,index){
                return _buildToDoItem(_todoItems[index], index);
              },
              ),
             ),
             new Expanded(
               child: ReorderableListView(
                children: <Widget>[
                  for(final widget in _todoItems)
                  for(final widget1 in WidgetList)
                  GestureDetector(
                    key: Key(widget.todoText),
                    child: Dismissible(
                      key: Key(widget.todoText),
                      child: CheckboxListTile(
                        value: widget1._todoCheck,
                        title: _strikeThrough(widget.todoText,widget1._todoCheck),
                        onChanged: (checkValue){
                          setState(() {
                            if(!checkValue){
                              widget1._todoCheck = false;
                            }
                            else{
                              widget1._todoCheck = true;
                            }
                          });
                        }),
                        background: Container(
                          child: Icon(Icons.delete),
                          alignment: Alignment.centerRight,
                          color: Colors.orange[300],
                          ),
                          confirmDismiss: (dismissDirection){
                            return showDialog(
                              context: context,
                              barrierDismissible: true,
                              builder: (BuildContext context){
                                return AlertDialog(
                                  title: Text("Delete Todo?"),
                                  actions: <Widget>[
                                    FlatButton(
                                      child: Text("OK"),
                                       onPressed: (){
                                         Navigator.of(context).pop(true);
                                       },
                                      ),
                                      FlatButton(
                                        child: Text("Cancel"),
                                        onPressed: (){
                                          Navigator.of(context).pop(true);
                                        },),
                                  ],
                                  );
                              });
                          },
                          direction: DismissDirection.endToStart,
                          movementDuration: const Duration(milliseconds: 200),
                          onDismissed: (dismissedDirection){
                            WidgetList.remove(widget);
                            Fluttertoast.showToast(
                              msg: "Todo Deleted!"
                              );
                          },
                      ),
                    onDoubleTap: (){
                      popUpTextController.text = widget.todoText;
                      showDialog(
                        context: context,
                        barrierDismissible: true,
                        builder: (BuildContext context){
                          return AlertDialog(
                            title: Text("Edit ToDo"),
                            content: TextFormField(
                              controller: popUpTextController,
                            ),
                            actions: <Widget>[
                              FlatButton(
                                child: Text("OK"),
                                onPressed: (){
                                  setState(() {
                                    widget.todoText=popUpTextController.text;
                                  });
                                  Navigator.of(context).pop(true);
                                },
                              ),
                              FlatButton(
                               child: Text("Cancel"),
                               onPressed: (){
                              Navigator.of(context).pop(false);
                            },
                          )
                            ],
                          );
                        }
                      );
                    },
                  )
                ],
                onReorder:  (oldIndex, newIndex){
              setState(() {
              if(oldIndex < newIndex){
                newIndex -= 1;
                }
              var replaceWiget = WidgetList.removeAt(oldIndex);
              WidgetList.insert(newIndex, replaceWiget);
              });
          },)
              )
           ],
        );
     }

     Widget _buildToDoItem(String todoText, int index){
       return new ListTile(
         title: new Text(todoText),
         onLongPress: () => _promptRemoveToDoItem(index),
       );
     }
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
              appBar: new AppBar(
              title: new Text('To Do List')
              ),
              body:_buildToDoList(context),
              floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
              floatingActionButton: new FloatingActionButton(
                focusElevation: 7,
                onPressed:_pushAddToDoScreen,
                tooltip: 'Add Task',
                child: new Icon(Icons.add)
              ),

            drawer: Drawer(
              child: ListView(
                padding: const EdgeInsets.all(0),
                children: <Widget>[
                    DrawerHeader(
                      child: Text('To Do App Drawer Header'),
                      decoration: BoxDecoration(
                      color: Colors.teal,
                     )
                    ),
                  ListTile(
                    title: Text('Add Items'),
                    onTap: _pushAddToDoScreen,
                  ),
                  ListTile(
                    title: Text('Remove Items'),
                    subtitle: Text('Long Press on any item to remove it'),
                    onTap: (){
                      Navigator.pop(context);
                    },
                  ),
                  ListTile(
                    title: Text('Check Status of Items'),
                    subtitle: Text('If the item is in List, then it is Pending, else long press to mark it done'),
                    onTap: (){
                      Navigator.pop(context);
                    },
                  ),
                ],
              )
            ),
            bottomNavigationBar: BottomAppBar(
                shape: CircularNotchedRectangle(),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    IconButton(
                      icon: Icon(Icons.settings),
                      onPressed: () {},
                    ),
                    IconButton(
                    icon: Icon(Icons.more_vert),
                    onPressed: () {},
                    )
                  ]
                )
              )
          );
      }

     void _pushAddToDoScreen(){
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context){
            return new Scaffold(
              appBar: new AppBar(
                title: new Text('Add a new task')
              ),
              body: new TextField(
                autofocus: true,
                onSubmitted: (val){
                  _addToDoItem(val);
                  Navigator.pop(context);
                },
                decoration: new InputDecoration(
                  hintText: 'Enter Tasks....',
                  contentPadding: const EdgeInsets.all(16.0)
                ),
              )
            );
          }
        )
      );
    }
    }


text:
Q: ASP.Net MVC : Bind drop down list with nested list type collection I am showing student data in webgrid. I am showing student id, first name, last name, state and city. the way I am working now I am getting data. I am doing webgrid in line edit which is working. the moment I click on edit button then textbox and dropdown is coming properly on grid cell. now state and city dropdown is coming. the way I code it now state is showing all state and city also showing all city but I want state dropdown should show all state but city dropdown should show only those city based on student state id.
now in my view model state and city list type property getting load independently but I want to bit redesign the code. I want to load all state but in case of city I want to load it based on student state id.
now my preset view model look like
public class StudentListViewModel
{
    public int StartIndex { get; set; }
    public int EndIndex { get; set; }
    public int page { get; set; }
    public int RowCount { get; set; }
    public int PageSize { get; set; }
    public int CurrentPage { get; set; }

    public string sort { get; set; }
    public string sortdir { get; set; }

    public IList<Student> Students { get; set; }

    public int SelectedStateId { set; get; }
    public IList<State> States { get; set; }

    public int SelectedCityId { set; get; }
    public IList<City> Cities { get; set; }

    public StudentListViewModel()
    {
        PageSize = 5;
        sort = "ID";
        sortdir = "ASC";
        CurrentPage = 1;
    }

    public void SetUpParams(StudentListViewModel oSVm)
    {
        if (oSVm.page == 0)
            oSVm.page = 1;

        StartIndex = ((oSVm.page * oSVm.PageSize) - oSVm.PageSize) + 1;
        EndIndex = (oSVm.page * oSVm.PageSize);
        CurrentPage = (StartIndex - 1) / oSVm.PageSize;

        if (string.IsNullOrEmpty(oSVm.sort))
            oSVm.sort = "ID";

        if (string.IsNullOrEmpty(oSVm.sortdir))
            oSVm.sortdir = "ASC";
    }
}

Model classes
   public class Student
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsActive { get; set; }
        public int StateID { get; set; }
        public string StateName { get; set; }
        public int CityID { get; set; }
        public string CityName { get; set; }
    }

        public class State
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }

    public class City
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

Student controller
---------------------
  public class StudentController : Controller
    {
        private StudentRepository _Studentdata;
        private StateRepository _Statedata;
        private CityRepository _Citydata;

        public StudentController()
        {

            _Studentdata = new StudentRepository(System.Configuration.ConfigurationManager.ConnectionStrings["StudentDBContext"].ConnectionString);
            _Statedata = new StateRepository(System.Configuration.ConfigurationManager.ConnectionStrings["StudentDBContext"].ConnectionString);
            _Citydata = new CityRepository(System.Configuration.ConfigurationManager.ConnectionStrings["StudentDBContext"].ConnectionString);
        }

        // GET: Stuent
        public ActionResult List(StudentListViewModel oSVm)
        {
            if (Request.IsAjaxRequest())
                System.Threading.Thread.Sleep(1000); // just simulate delay of one second

            StudentListViewModel SVm = new StudentListViewModel();
            SVm.SetUpParams(oSVm);
            SVm.Students = _Studentdata.GetStudents(oSVm.page, oSVm.PageSize, oSVm.sort, oSVm.sortdir).ToList(); // populating student
            SVm.States = _Statedata.GetAll().ToList(); // populating state
            SVm.Cities = _Citydata.GetAll().ToList(); // populating city
            SVm.RowCount = _Studentdata.DataCounter;
            return View("ListStudents",SVm);
        }

}

this is my webgrid code
@{
    WebGrid grid = new WebGrid(null, rowsPerPage: Model.PageSize, canPage: true,
        defaultSort: Model.sort, ajaxUpdateContainerId: "gridContent", ajaxUpdateCallback: "initScripts");
    grid.Bind(Model.Students, autoSortAndPage: false, rowCount: Model.RowCount);
    grid.PageIndex = Model.CurrentPage;
}

@grid.GetHtml(
        tableStyle: "webgrid-table",
        headerStyle: "webgrid-header",
        footerStyle: "webgrid-footer",
        alternatingRowStyle: "webgrid-alternating-row",
        selectedRowStyle: "webgrid-selected-row",
        rowStyle: "webgrid-row-style",
        mode: WebGridPagerModes.All,
        firstText: "<<",
        previousText: "<",
        nextText: ">",
        lastText: ">>",
        numericLinksCount: 5,
        columns:
            grid.Columns
            (
            grid.Column(columnName: "ID", header: "ID", format: @<text>@item.ID <input type="hidden" name="HiddenID" value="@item.ID" id="HiddenID"  /></text>,style:"SmallCols"),
            grid.Column(columnName: "FirstName", header: "First Name", format: @<text>@item.FirstName<input type="text" id="txtFirstName" value="@item.FirstName" class="edit-mode" /></text>,style:"NameColWidth" ),
            grid.Column(columnName: "LastName", header: "Last Name", format: @<text>@item.LastName<input type="text" id="txtLastName" value="@item.LastName" class="edit-mode" /></text>,style:"NameColWidth"),

            grid.Column(columnName: "StateName", header: "State Name", format: @<text>@item.StateName@Html.DropDownListFor(x => x.SelectedStateId, new SelectList(Model.States, "ID", "Name", Model.SelectedStateId= item.StateID), "-- Select States--", new { id = "cboState", @class = "edit-mode" })</text>,style:"NameColWidth"),
            grid.Column(columnName: "CityName", header: "City Name", format: @<text>@item.CityName@Html.DropDownListFor(x => x.SelectedCityId, new SelectList(Model.Cities, "ID", "Name", Model.SelectedCityId = item.CityID), "-- Select City--", new { id = "cboCity", @class = "edit-mode" })
</text>,style:"NameColWidth"),
            grid.Column(header: "IsActive",
            format: @<text><input id="select" class="box" name="select"
                                  type="checkbox" @(item.IsActive ? "checked='checked'" : "") value="@item.IsActive" /></text>
                    , style: "text-center checkbox-width SmallCols"),

             grid.Column("Action", format: @<text>
                        <button class="edit-user display-mode btnGreen">Edit</button>
                        <button class="edit-user display-mode btnRed">Delete</button>
                        <button class="save-user edit-mode btnGreen">Save</button>
                        <button class="cancel-user edit-mode btnSky">Cancel</button>
            </text>, style: "ActionCol", canSort: false)

                        ))

I can put this property public IList<City> Cities { get; set; } from view model to student class but the problem is I do not know how to refer nested list type property in dropdown
this way can my dropdown point to nested Cities property ?
@Html.DropDownListFor(x => x.SelectedCityId, new SelectList(Model.Cities, "ID", "Name", Model.SelectedCityId = item.CityID), "-- Select City--", new { id = "cboCity", @class = "edit-mode" })

how to refer this line Model.Students.Cities i mean
@Html.DropDownListFor(x => x.SelectedCityId, new SelectList(Model.Students.Cities, "ID", "Name", Model.SelectedCityId = item.CityID), "-- Select City--", new { id = "cboCity", @class = "edit-mode" })

I tried Model.Students.Cities but city property is not coming!
where I am making the mistake? looking for guidance and suggestion. thanks


text:
Q: VS2010 devenv.exe.config issue I am unable to open vs2010 .I have windows 7 OS and it is 32 bit machine. Event log says
Activation context generation failed for "C:\Program Files\Microsoft Visual Studio  10.0\Common7\IDE\devenv.exe".Error in manifest or policy file "C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe.Config" on line 13. Invalid Xml syntax.
devenv.exe.config file got corrupted lot of junk characters i do not know how it got corrupted.Reset my config setting will be my last option.I do not have any back up of the file
I tried to fix my self i know it is a bad idea.After fixing the file I am not able to save the file. I tried to find out any process has locked the file using Procmon.exe and using another software called unlockit .There is no process locked this config file.
Is there a way to regenerate the config file with out resetting it ?

A: The only option I can think is to create a copy of your devenv.exe.config, then regenerate the devenv.exe.config and paste the additional settings from your copy into the regenerated devenv.exe.config.
You should consider installing a backup application and regularly backing up your development machine. This will allow you to restore individual files or recover your hard disk in the event of a failure. It really is a time saver when something goes wrong.

A: Try to fix file with a Text Editor running as a Administrator (not windows user account, administrator for program).

A: Open notepad as Administrator.
Open devenv.exe.config in notepad, make changes
And Save it in same location.
It worked for me for machine.config.


text:
Q: Integrate video inside Lottie I'm trying to replace an image with a video by manipulating the Lottie JSON code.
Is it possible to integrate an MP4 inside a Lottie JSON code?

A: As far as I know, this is not possible. Lottie only supports png sequences as "video" format.


text:
Q: PDF header signature not found, iText Hi I am trying to read a PDF file which is being uploaded by the servlet.
Here is the code
//out = byte array
out = readInItem(item);
fileToUpload = new ByteArrayInputStream(out.toByteArray());

Map<String, AcroFields.Item> pdfBoxNames = new HashMap<String, AcroFields.Item>();
PdfReader reader = new PdfReader(fileToUpload);
ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, os);
AcroFields acroFields = stamper.getAcroFields();
pdfBoxNames = acroFields.getFields();

My pdf starts like this %PDF-1.6
Error message is
java.io.IOException: PDF header signature not found.

A: Faced the same exception! Make sure you have included the TableHeader and a writer PageEvent set for that. I just added them up and this exception was gone! Hope it helps you
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
TableHeader includeHeader = new TableHeader();
writer.setPageEvent(includeHeader);


text:
Q: What are your best practices for looping timed jquery function As I work on looping with jQuery I'm really puzzled how to pass the values and start over.
My project is a "simple" testimonial rotator.

You're great!

Thanks a lot!

Rock on!

Now, I'm stuck. Pointers to get over the hump?

A: The best way is to use setInterval()
var i = 0, // index of element to show
    t = $('.testimonial'), // elements
    max = t.length; // max elements
function fade() {
    t.eq(i).show('slow'); // we show current element
    t.not(':eq('+i+')').hide('slow'); // we hide others
    if(++i >= max) i=0; // we increment index and if we go over max, we reset index
}
window.setInterval(fade,3000); // we call fade every 3 seconds

http://jsfiddle.net/zf5Wb/

A: As Shikiryu suggested.
Change the code from $('.testimonial.nth-child[' + i + ']')  to $('.testimonial:nth-child(' + i + ')')


text:
Q: Using original pointer after realloc? I was reading Richard Reese's new (May 2013) O'Reilly book "Understanding and Using C Pointers", and I have a question about some code therein, on page 87.
if (++length > maximumLength) {
    char *newBuffer = realloc (buffer, maximumLength += sizeIncrement);

    if (newBuffer == NULL) {
        free (buffer);
        return NULL;
    }

    currentPosition = newBuffer + (currentPosition - buffer);
    buffer = newBuffer;
}

I hope the names of the variables are self-explanatory; if context is needed, I will edit to provide the entire chunk of code and not just this excerpt.
My question is about the line currentPosition = newBuffer + (currentPosition - buffer);. My understanding of realloc() is that when the new allocation succeeds, the originally allocated memory is freed. If that is correct, then the line in question is using dangling pointers, innit? Both buffer and currentPosition on the RHS of that expression are pointers to memory that has been freed.
My instinct would be to rewrite this to avoid using the dangling pointers by using length, which after all is already around. I want to replace those last two lines with:
buffer = newBuffer;
currentPosition = buffer + length;

However, presumably the code as written works because the two pointers still hold addresses (albeit of garbage), and the offset between those two addresses can still be calculated as a way of reassigning currentPosition. So am I being merely persnickety in feeling uneasy about this?
To generalize the question: once a pointer is dangling, is it safe to use the address contained in the pointer for any purpose, such as calculating offsets? Thanks.

A:
once a pointer is dangling, is it safe to use the address contained in the pointer for any purpose, such as calculating offsets?

No, it is not safe. After free the pointer value is an invalid address and an invalid address cannot be used for pointer arithmetic without invoking undefined behavior.

A: It is safe to use the dangling pointer (e.g. for "pointer arithmetic") as long as you don't try to dereference the pointer (i.e. apply the operator *).


text:
Q: iOS7 HTML5 Video Poster Not Working I am using the correct VIDEO Tag for displaying HTML5 Video. The Poster appears fine for earlier iOS versions. However, for iOS7, The poster is not being picked up.
Here is my code
<video onclick="this.play();" width="100%" height="100%"  preload="none"  poster="[My Poster URL]" src="[My Video URL]"  controls ></video>
Has anyone tried this? Any help is appreicated.

A: Do you use a jpg-file as poster? We had the same problem and fixed it by using a png-file. Hope that helps.


text:
Q: Using Webpack with d3, jQuery, and Bootstrap

Hey guys,
Total Webpack (and es6/modern frontend practices) newbie here, so sorry if this is a dumb question.
I'm trying to build a d3 dataviz project using modern web dev standards and am having a lot of trouble getting it up and running -- specifically, I'm getting a weird Uncaught (in promise) TypeError when I launch the local webpack dev server, and none of my d3 elements are displaying. I'm sure it's something very dumb that I'm overlooking but I've been scouring the internet for what feels like forever and unfortunately haven't made any progress. Any guidance would be so, so appreciated.
Full disclosure: this is for a college course, but my teacher knows nothing about modern webdev standards, so I am fully on my own in choosing to develop it this way. I just wanted to give myself a trial by fire in the world of modern JS and now I'm regretting it, lol...
The work-in-progress project is up on GitHub if you need to see any of the other moving parts, and please don't hesitate to let me know if you have questions! Thanks so much.
package.json
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --progress -p",
    "watch": "webpack --progress --watch",
    "start": "webpack-dev-server --open"
},

"dependencies": {
    "bootstrap": "^4.0.0",
    "d3": "^5.0.0",
    "d3pie": "^0.2.1",
    "jquery": "^3.3.1",
    "popper.js": "^1.14.1"
},

"devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "css-loader": "^0.28.11",
    "style-loader": "^0.20.3",
    "webpack": "^4.2.0",
    "webpack-cli": "^2.0.13",
    "webpack-dev-server": "^3.1.1"
}

webpack.config.js
var webpack = require('webpack');

module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle.js'
  },
  plugins: [
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery",
                "window.jQuery": "jquery",
                d3: 'd3'
            })
        ],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }
    ]
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
};

index.js (imports only)
import 'bootstrap/dist/js/bootstrap.min.js';
import 'bootstrap/dist/css/bootstrap.min.css';
import $ from 'jquery';
import * as d3 from "d3";
import 'd3pie';

.babelrc
{
"presets": [ "env" ]
}

A: The problem is that the d3.csv function in version 5 of d3 (which you're using in the project) uses promises rather than callbacks in order to get the final data. This is how the function should be called:
d3.csv("thanksgiving-2015-poll-data.csv").then((data) => {
  var thanksCSV = data;
  // ...

When you were calling it as
d3.csv("thanksgiving-2015-poll-data.csv", (data) => {

that was only a mapping function over each row - the argument is meant to be a row, not the whole array of rows.
But you have another problem - your import 'd3pie'; does not give you a d3pie constructor to work with. Your import statement should look like this instead:
import d3pie from 'd3pie';
But then there's yet another problem - d3pie requires window.d3 to be defined, which you haven't done. So, below your imports, add:
window.d3 = d3;
Then, the pie graph will load properly.


text:
Q: Invoke initializer for swift class using type I have an array like such:
static var handlers: [MyProtocol.Type] = [Handler1.self, Handler2.self]

Handler 1, 2, etc.. are Objects that inherit from BaseHandler. Now Im having some trouble returning an instance of the object. For instance, i want to do this:
func getHandler(_ idx: Int) -> MyProtocol.Type? {
    let handler: BaseHandler.Type = handlers[0] as! BaseHandler.Type
    return handler()
}

I get a compiler error saying "cannot invoke 'handler' with no arguments". But BaseHandler has an init function without arguments. Any ideas?

A: Short answer: You can just use init, but you probably want to formalize it in the protocol.
Example
protocol MyProtocol {
  init()
  func f() -> Int
}

struct MyStruct: MyProtocol {
  // This struct gets an automatic no-arg constructor
  func f() -> Int { return 12 }
}

let ps: [MyProtocol.Type] = [ MyStruct.self ]
ps[0].init().f() // 12


text:
Q: Is GitHub id an unchangeable identifier? Where can I find the GitHub ID in my account?
GitHub username is changeable. is GitHub id unchangeable?
Not mentioned in https://docs.github.com/en/rest/reference/users#get-contextual-information-for-a-user

A: Done some digging, here's what I've found:
Tried to change my user name: user id was unchanged.
In this and this documentations it looks like you no-replay email (which is contracted from your id) does not change.
This answer supports this as well.
As does this api call doc ("since" query parameter explenation).
So, no direct quote in documentation, but close.
If you've found something since then I'd like to hear it.


text:
Q: Adding a class to some javascript buttons I'm trying to make some edits to a form written in javascript, however I'm really just getting acquainted with this language.  I'm trying to format a couple of buttons; to do this, I would like to add a class to them.  The buttons in question are "Add" and "Cancel" and they are rendered with the following function:
    showAddDialog: function() {
        $("#dialog").data("product",upsmart.products.pcounter);
        $("#dialog").html(upsmart.products.createForm(upsmart.products.pcounter));
        $("#photo_button").click(open_media_library);
        upsmart.products.pcounter++;
        $("#dialog").dialog({
            width: 600,
            modal: true,
            buttons: {
                "Add": upsmart.products.addProduct,
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        });
    },

How might I accomplish this?
Thanks for any help.

A: Try this:
$("#dialog").dialog({
            width: 600,
            modal: true,
            buttons: [
        {
            text: "Cancel",
            "class": 'cancelButtonClass',
            click: function() {
                // Cancel code here
            }
        },
        {
            text: "Save",
            "class": 'saveButtonClass',
            click: function() {
                // Save code here
            }
        }
    ],
    close: function() {
        // Close code here (incidentally, same as Cancel code)
    }
});

Source:Apply CSS to jQuery Dialog Buttons

A: you can add class to any element using jQuery -
$(element).addClass("class-name")

if button id is abc you can use -
$("#abc").addClass("class-name")

More about add classes using jQuery
And in your specific case of jQuery dialog use -
   $("#dialog").dialog({
        width: 600,
        modal: true,
        dialogClass
       buttons: [
    {
        text: "Add",
        "class": 'addButtonClass',
        click: function() {
            // Cancel code here
        }
    },
    {
        text: "Cancel",
        "class": 'CancelButtonClass',
        click: function() {
            // Save code here
        }
    }
]
        }
    });