text:
Q: Getting NullPointerException for method Invocation in TestNG I am new to Selenium and have written below Code to take parameters from ITestContext group.
Code :
 import java.util.concurrent.TimeUnit;
 import org.openqa.selenium.By;
 import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.WebElement;
 import org.openqa.selenium.chrome.ChromeDriver;
 import org.openqa.selenium.interactions.Actions;
 import org.testng.ITestContext;
 import org.testng.annotations.BeforeTest;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;

public class ITestGroupism {
WebDriver driver;

  @BeforeTest(groups={"A","B"})
  public void setup()
  {
      System.setProperty("webdriver.chrome.driver", "E:\\Automation Jars\\chromedriver_win32\\chromedriver.exe");
      driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.get("https://www.google.co.in");
  }

  @Test(dataProvider="SearchProvider", groups="A")
  public void testMethodA(String author, String searchKey) throws InterruptedException
  {
      WebElement searchText = driver.findElement(By.id("sb_ifc0"));
      Actions actions = new Actions(driver);
      actions.moveToElement(searchText);
      actions.click();
      actions.sendKeys(searchKey);
      actions.build().perform();
      System.out.println("Welcome ->"+author+" Your search key is "+searchKey);
      driver.navigate().back();
      driver.navigate().forward();
      System.out.println("thread will sleep now");
      Thread.sleep(2000);
      }

     @Test(dataProvider="SearchProvider", groups="B")
     public void testMethodB(String searchKey) throws InterruptedException
     {
         WebElement searchText = driver.findElement(By.id("sb_ifc0"));
          Actions actions = new Actions(driver);
          actions.moveToElement(searchText);
          actions.click();
          actions.sendKeys(searchKey);
          actions.build().perform();
          //searchText.sendKeys(searchKey);
          System.out.println("Welcome Professor"+"Your search key is "+searchKey);
          driver.navigate().back();
          driver.navigate().forward();
          System.out.println("thread will sleep now");
          Thread.sleep(2000);
     }

     @DataProvider(name="SearchProvider")
     public Object[][] ff(ITestContext c)
     {
     Object[][] groupArray =null;
     for(String group : c.getIncludedGroups())
     {
        if(group.equalsIgnoreCase("A"))
        {
            groupArray = new Object[][]
            {
            {"Aakash", "India"},
             {"Aayush", "US"},
             {"Raveena", "UK"}
            };
            break;
         }else if(group.equalsIgnoreCase("B"))
         {
            groupArray= new Object[][]
               {
                 {"Canada"},
                 {"New Zealand"},
                 {"Russia"}
               };
             }break;
     }
     return groupArray;
    }
}

But I am getting Below exceptions:

SKIPPED: testMethodA java.lang.NullPointerException   at
  org.testng.internal.MethodInvocationHelper.invokeDataProvider(MethodInvocationHelper.java:151)
    at
  org.testng.internal.Parameters.handleParameters(Parameters.java:430)
    at org.testng.internal.Invoker.handleParameters(Invoker.java:1243)
    at org.testng.internal.Invoker.createParameters(Invoker.java:992)   at
  org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1082)  at
  org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
    at
  org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
    at org.testng.TestRunner.privateRun(TestRunner.java:778)    at
  org.testng.TestRunner.run(TestRunner.java:632)    at
  org.testng.SuiteRunner.runTest(SuiteRunner.java:366)  at
  org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)  at
  org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)   at
  org.testng.SuiteRunner.run(SuiteRunner.java:268)  at
  org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)  at
  org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)   at
  org.testng.TestNG.runSuitesSequentially(TestNG.java:1225)     at
  org.testng.TestNG.runSuitesLocally(TestNG.java:1150)  at
  org.testng.TestNG.runSuites(TestNG.java:1075)     at
  org.testng.TestNG.run(TestNG.java:1047)   at
  org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:137)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:58)
SKIPPED: testMethodB java.lang.NullPointerException   at ....

A: When you are using groups, you need to define those groups in XML file.
<suite name="Group Suite" verbose="1">
<test name="Test">
<groups>
  <run>
    <include name="A" />
    <include name="B" />
  </run>
</groups>
<classes>
  <class name="fully.qualied.package.ITestGroupism" />
 </classes>
 </test>
</suite>

Updated Code:
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.interactions.Actions;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.DataProvider;
    import org.testng.annotations.Test;

    import java.io.File;
    import java.lang.reflect.Method;
    import java.util.concurrent.TimeUnit;

    public class ITestGroupism {
        WebDriver driver;

        @BeforeTest(groups = {"A", "B"})
        public void setup() {
            System.setProperty("webdriver.chrome.driver", new File("src/test/resources/driver/chromedriver")
                    .getAbsolutePath());
            driver = new ChromeDriver();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            driver.get("https://www.google.co.in");
        }

        @Test(dataProvider = "SearchProvider", alwaysRun = true, groups = "A")
        public void testMethodA(String author, String searchKey) throws InterruptedException {
            WebElement searchText = driver.findElement(By.id("sb_ifc0"));
            Actions actions = new Actions(driver);
            actions.moveToElement(searchText);
            actions.click();
            actions.sendKeys(searchKey);
            actions.build().perform();
            System.out.println("Welcome ->" + author + " Your search key is " + searchKey);
            driver.navigate().back();
            driver.navigate().forward();
            System.out.println("thread will sleep now");
            Thread.sleep(2000);
        }

        @Test(dataProvider = "SearchProvider", alwaysRun = true, groups = "A")
        public void testMethodB(String searchKey) throws InterruptedException {
            WebElement searchText = driver.findElement(By.id("sb_ifc0"));
            Actions actions = new Actions(driver);
            actions.moveToElement(searchText);
            actions.click();
            actions.sendKeys(searchKey);
            actions.build().perform();
            //searchText.sendKeys(searchKey);
            System.out.println("Welcome Professor" + "Your search key is " + searchKey);
            driver.navigate().back();
            driver.navigate().forward();
            System.out.println("thread will sleep now");
            Thread.sleep(2000);
        }

        @DataProvider(name = "SearchProvider")
        public Object[][] ff(Method method) {
            Object[][] groupArray = null;
            if (method.getName().equalsIgnoreCase("testMethodA")) {
                groupArray = new Object[][]
                        {
                                {"Aakash", "India"},
                                {"Aayush", "US"},
                                {"Raveena", "UK"}
                        };
            } else if (method.getName().equalsIgnoreCase("testMethodB")) {
                groupArray = new Object[][]
                        {
                                {"Canada"},
                                {"New Zealand"},
                                {"Russia"}
                        };
            }
            return groupArray;
        }
    }


text:
Q: Is it possible to convert svg path with stroke to svg path without any styles and properties? I use svg path with
style="stroke: rgb(0,0,0); stroke-width: 10; stroke-linecap: round; fill: none;"

that allows me not to close svg path and it will have particular stroke width and shape.
But I need to use pure svg path without any properties or styles and get the same result.
Is there're any algorithms to achieve it?
Here is an input svg.
An output should looks like
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="500" height="500" xml:space="preserve">
<path d="path-data"/>
</svg>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) on line 10 So i get the error

"Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in
  /Applications/MAMP/htdocs/classes/class.ManageUsers.php on line 10",

does anyone know what part of the syntax is wrong? Below is the relevant class.
5    class ManageUsers {
6   public $link;
7
8   function __construct(){
9       $db_connection = new dbConnection();
10      $this->link = db_connection->connect();
11      return $this->link;
12  }

A: db_connection->connect(); should be $db_connection->connect(); notice the missing $


text:
Q: $5^a - 5^b$ is divisible by $n$ (prove) Prove that for every n natural number exist natural numbers $a,b \leq 4n, a\not= b $, which accomplish, that number $ 5^a - 5^b  $ is divisible by n. How many of these pairs exist?
Help please, I'm stuck with this problem. Any help is appreciated.

A: Let $n=5^km$ with $gcd(5,m)=1$.
Now, the pair $(a,b)$ is a solution if and only if $(b,a)$ is a solution. So it suffices to look for the solutions where $a>b$. Don't forget at the end to double the number of solutions.
Then
$$n|5^a-5^b =5^b(5^{a-b}-1)) \Leftrightarrow k \leq b \mbox{ and } m | 5^{a-b}-1$$
The existence is easy then, pick $b =k $ and $a-b =\phi(m) \leq m  \leq n$.
For the number of solutions, you need
$$k \leq b \leq 4n$$
Thus you have $4n-k$ choices for $b$.
Morever, for each $b$, if $j$ is the order of $5$ modulo $m$, you must have
$$j |a-b \,.$$
Thus, $a-b$ has to be a multiple of $j$ between $1$ and $4n-b$. From here you figure out how many choices of $a$ you have for each $b$. Add them, double and you are done.


text:
Q: Hanging Indents / Text Wrapping I'm trying to implement a command to be used in place of the itemize/enumerate environments. The idea is that I want to have a command (\detail), which can be used to construct an itemized list without being contained in an environment. The problem I'm having is that when a line is longer than the page width and consequently wraps to the next line, I don't seem to have any control over the indentation of the wrapped text. I've tried the hanging package and \hangindent, but haven't had much luck.
I've included a minimum example below and the output that I get when compiled. Ideally, I would like the wrapped text to be indented such that the first word on the second line aligns with the first word of the first line.
\documentclass{article}
\newcommand{\detail}[1]{-- {#1}}

\begin{document}
    \noindent\textbf{This is a header}\\
    \detail{This is a detail.}\\
    \detail{This is a detail that has too many words in it and consequently runs onto the next line of the page, and I want it to have a hanging indent.}
\end{document}

A: \documentclass{article}
\newcommand{\detail}[1]{\par\noindent\hangindent=\mylen\hangafter1-- #1}
\newlength{\mylen}
\settowidth{\mylen}{-- }

\begin{document}
    \noindent\textbf{This is a header}
    \detail{This is a detail.}
    \detail{This is a detail that has too many words in it and consequently runs onto the next line of the page, and I want it to have a hanging indent.}
\end{document}

A: A simplification of the already answered:
\documentclass{article}
\def\D{\par\noindent\makebox[1em][l]{-- }\hangindent1em}
\begin{document}
\subsubsection*{This is a header}
\D This is a detail
\D This is a detail that has too many words in it and consequently runs onto The next line of the page, and I want it to have a hanging indent.
\end{document}

A: \documentclass{article}
\newcommand{\detail}[1]{\par\noindent\hangindent=\mylen\hangafter1--\,\,#1}
\newlength{\mylen}
\settowidth{\mylen}{--\,\,}

\begin{document}
    \noindent\textbf{This is a header}
    \detail{This is a detail.}
    \detail{This is a detail that has too many words in it and consequently runs onto the next line of the page, and I want it to have a hanging indent.}
\end{document}

Wanted to put this as comment to Harish Kumar's answer but I have not enough rep for that. Anyway, since space is rubber it's better to use a fixed length. Since \, seems a bit narrow I used it twice, you can adjust to taste.


text:
Q: LOG4J2: how to configure JSON layout in properties file Does anyone know, how to write a log4j2 properties file, which outputs the logs to the console as JSON ?
i saw this link, https://logging.apache.org/log4j/2.x/manual/layouts.html#JSONLayout, but it is not clear for me, how do the configuration in a properties file.
thanks,
Eran

A: Furthermore, some options can be set in the log4j2.properties:
appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=myLog.json
appender.file.layout.type=JsonLayout
appender.file.layout.compact=true
appender.file.layout.eventEol=true
appender.file.layout.complete=true
appender.file.layout.properties=false
appender.file.layout.propertiesAsList=false
appender.file.layout.locationInfo=true
appender.file.layout.includeStacktrace=true
appender.file.layout.stacktraceAsString=true
appender.file.layout.includeNullDelimiter=false
appender.file.layout.objectMessageAsJsonObject=true

Please refer to the log4j2 documentation for the properties definition:
https://logging.apache.org/log4j/2.x/manual/layouts.html#JSONLayout

A: I found this Tutorial from the Springframework guru. My log4j2.properties file looks as follows;
name=JsonConfig

appenders = file

appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=myLog.json
appender.file.layout.type=JsonLayout

loggers=file
logger.file.name=your.logger.package.location
logger.file.level = debug
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

Hope this helps.


text:
Q: Java/Cassandra throwing error with making Frozen attribute I have a Java class that is using the datastax cassandra driver to write a pojo to a cassandra table. Everything works fine, until it comes to having to write a class object to the cassandra table. It throws this error:
Caused by: com.datastax.driver.core.exceptions.CodecNotFoundException: Codec not found for requested operation: [frozen< projKeySpace.smi > <-> code.generic.common.data.MyCustomSmiObject]
So I have tried a lot of different things to try and make the attribute "Frozen", but nothing works and I keep getting the same error. Here is an example of the class object.
@Table(keyspace="projkeyspace", name="summarytable")
public class DataGroupingObject implements Serializable {

    @Column(name = "objid")
    private String objId;
    @Column(name = "timeofjob")
    private Date timeOfJob;

    @Column(name = "smiobjectinput")
    @Frozen
    //Have also tried:
    //@Frozen("frozen<projKeySpace.smi>")
    //@Frozen("frozen<smi>")
    //@Frozen("frozen<MyCustomSmiObject>")
    //And all other permutations I can think of...
    private MyCustomSmiObject myCustomSmiObject; //The problem attribute

    @Column(name = "column5")
    private String dataForColumn5;

    //Getters and setters....
}

So what am I overlooking? Digging into the datastax documentation didn't show much beyond this, http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Frozen.html , which I tried.
I also have tried having the MyCustomSmiObject be mapped to the frozen 'projkeyspace.smi' and that didn't work (of course I didn't think it would since there isn't actually a table in cassandra called smi, its just a type) but here is an example of it:
@Table(keyspace="projkeyspace", name="smi")
public class MyCustomSmiObject implements Serializable {

    @Column(name = "idstring")
    private String idString;
    @Column(name = "valuenum")
    private Double valueNum;

    //Getters and Setters....
}

So like I said, I am at a loss. Any help would be greatly appreciated and thanks in advance!

A: smi is a UDT isn't it?  In that case MyCustomSmiObject should be annotated with @UDT(keyspace="projkeyspace", name="smi") instead of @Table.  By doing that, the driver should detect that this is a UDT and it will register a custom codec for it which will allow it to be able to properly serialize and deserialize it.
On another note the @Frozen annotation currently has no impact on the mapper, it is only informational at this time until the mapper has support for schema generation.


text:
Q: SVProgressHUD code executes out of order I'm building a bus predictions app using the NextBus API that will help users get prediction times and bus information. I've implemented a function that takes the user's current location and a chosen address and returns a list of 10 bus routes that minimize travel distance and time.
Here's the @IBAction that triggers the aforementioned function:
@IBAction func findAWayPressed(_ sender: UIButton) {
    // Hide confirm button.
    confirmButton.isHidden = true

    // Setup loading HUD.
    let blue = UIColor(red: 153/255, green: 186/255, blue: 221/255, alpha: 1.0)
    SVProgressHUD.setBackgroundColor(blue)
    SVProgressHUD.setStatus("Finding a way for you...")
    SVProgressHUD.setBorderColor(UIColor.black)
    SVProgressHUD.show()

    // Finds a list of ten bus routes that minimizes the distance from the user and their destination.
    WayFinder.shared.findAWay(startCoordinate: origin!, endCoordinate: destination!)

    SVProgressHUD.dismiss()
}

The problem is that confirmButton.isHidden = true and the SVProgressHUD lines only seem to do anything after the WayFinder.shared.findAWay() executes. The HUD displays for a brief moment before being immediately dismissed by SVProgressHUD.dismiss().
Here's the findAWay function:
func findAWay(startCoordinate: CLLocationCoordinate2D, endCoordinate: CLLocationCoordinate2D) {
    // Get list of bus routes from NextBus API.
    getRoutes()

    guard !self.routes.isEmpty else {return}

    // Initialize the the lists of destination and origin stops.
    closestDestinations = DistanceData(shortestDistance: 1000000, stops: [])
    closestOrigins = DistanceData(shortestDistance: 1000000, stops: [])

    // Fetch route info for every route in NextBus API.
    var routeConfigsDownloaded: Int = 0
    for route in routes {
        // Counter is always one whether the request fails
        // or succeeds to prevent app crash.
        getRouteInfo(route: route) { (counter) in
            routeConfigsDownloaded += counter
        }
    }

    while routeConfigsDownloaded != routes.count {}

    // Iterate through every stop and retrieve a list
    // of 10 possible destination stops sorted by distance.
    getClosestDestinations(endCoordinate: endCoordinate)
    // Use destination stop routes to find stops near
    // user's current location that end at destination stops.
    getOriginStops(startCoordinate: startCoordinate)

    // Sort routes by adding their orign distance and destination
    // distance and sorting by total distance.
    getFoundWays()
}

private func getRouteInfo(route: Route, completion: @escaping (Int) -> Void) {
    APIWrapper.routeFetcher.fetchRouteInfo(routeTag: route.tag) { (config) in
        if let config = config {
            self.routeConfigs[route.tag] = config
        } else {
            print("Error retrieving route config for Route \(route.tag).")
        }
        completion(1)
    }
}

Why would the code in @IBAction not execute in order? How could the hud not show on screen before findAWay was called? Any ideas?

A: So, you're going to want to do some reading about the "main thread" and how it works. Maybe UNDERSTANDING THE IOS MAIN THREAD
Basically, you're asking the system to show the HUD, then performing, what I assume is a long running and blocking operation, and then dismiss the HUD all within the main thread.
It's impossible for the system to show the HUD until the method exists, as it will part of the next cycle (paint/layout/other important stuff).  In cases like this, I would lean towards some kind of "promise" API, like PromiseKit or Hydra as it will greatly simply the thread hoping.
The basic intent is - While on the main thread, present the HUD, using a background thread, execute the query, when it's complete, dismiss the HUD, but do so on the main thread.
Which might look something like this..
SVProgressHUD.show()
DispatchQueue.global(qos: .userInitiated).async {
    WayFinder.shared.findAWay(startCoordinate: origin!, endCoordinate: destination!)
    DispatchQueue.main.async {
        SVProgressHUD.dismiss()
    }
}

Now remember, never modify the UI from outside the main thread context, if the OS detects this, it will crash your App!
I might also consider using a DispatchSemaphore instead of a "wild running" while-loop, so instead of..
// Fetch route info for every route in NextBus API.
var routeConfigsDownloaded: Int = 0
for route in routes {
    // Counter is always one whether the request fails
    // or succeeds to prevent app crash.
    getRouteInfo(route: route) { (counter) in
        routeConfigsDownloaded += counter
    }
}

while routeConfigsDownloaded != routes.count {}

You might use something like...
let semaphore = DispatchSemaphore(value: routes.count)
// Fetch route info for every route in NextBus API.
var routeConfigsDownloaded: Int = 0
for route in routes {
    // Counter is always one whether the request fails
    // or succeeds to prevent app crash.
    getRouteInfo(route: route) { (counter) in
        semaphore.signal()
    }
}

semaphore.wait()

which will do the same thing, but more efficiently


text:
Q: Как заставить EditText заполнить всё свободное пространство в строке? Всем доброго времени суток. Хочу чтобы editText заполняло всё свободное пространство в строке. Не знаю как это правильно реализовать. Подскажите кто-нибудь как это сделать

A: Попробуйте выставить ему ширину match_parent
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/main"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <EditText android:id="@+id/edit_text"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"/>

</LinearLayout>

A: Если хотите чтобы кнопка была под EditText
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <EditText
              android:layout_width="match_parent"
              android:layout_height="wrap_content"/>

    <Button
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Отправить"/>

</LinearLayout>

Если хотите чтобы кнопка была была вместе с EditText
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="horizontal">

    <EditText
              android:layout_height="wrap_content"
              android:layout_width="0dp"
              android:layout_weight="1"/>

    <Button
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Отправить"/>

</LinearLayout>


text:
Q: FFMpeg - How to copy codec ( video and audio ) from 'mp4' container to 'ts' container i have this ffmpeg command

ffmpeg -i c:\input.mp4 -vcodec copy -acodec copy -vbsf h264_mp4toannexb c:\output.ts.

The above command successfully converts input.mp4 to output.ts.
I need to implement the same functionality via code (using the ffmpeg library).
Does anybody know how to copy from one container to another without decoding and encoding?

A: If you are looking just for stream copy you can do this quite easily.
You can refer following steps.
//1. Do initialization using

    av_register_all();

// 2. Open input file using

    avformat_open_input( &m_informat, filename.c_str(), 0, 0));

//3. Find input stream info.

     if ((ret = avformat_find_stream_info(m_informat, 0))< 0)
        {
           av_strerror(ret,errbuf,sizeof(errbuf));
           PRINT_VAL("Not Able to find stream info:: ", errbuf)
           ret = -1;
           return ret;
        }

        for (unsigned int i = 0; i<m_informat->nb_streams; i++)
        {
           if(m_informat->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
           {
              PRINT_MSG("Found Video Stream ")
              m_in_vid_strm_idx = i;
              m_in_vid_strm = m_informat->streams[i];
           }

        if(m_informat->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
        {
            m_in_aud_strm_idx = i;
            m_in_aud_strm = m_informat->streams[i];
         }

// 4. Create ouputfile  and allocate output format.

   AVOutputFormat *outfmt = NULL;
   std::string outfile = std::string(filename) + "clip_out.ts";
        outfmt = av_guess_format(NULL,outfile.c_str(),NULL);
     if(outfmt == NULL)
        {
            ret = -1;
            return ret;
        }
        else
        {
            m_outformat = avformat_alloc_context();
            if(m_outformat)
            {
                m_outformat->oformat = outfmt;
                _snprintf(m_outformat->filename,
                 sizeof(m_outformat->filename), "%s", outfile.c_str());
            }
            else
            {
                ret = -1;
                return ret;
            }
        }

//5. Add audio and video stream to output format.

        AVCodec *out_vid_codec,*out_aud_codec;
        out_vid_codec = out_aud_codec = NULL;

        if(outfmt->video_codec != AV_CODEC_ID_NONE && m_in_vid_strm != NULL)
        {
            out_vid_codec = avcodec_find_encoder(outfmt->video_codec);
            if(NULL == out_vid_codec)
            {
                PRINT_MSG("Could Not Find Vid Encoder")
                ret = -1;
                return ret;
            }
            else
            {
                PRINT_MSG("Found Out Vid Encoder ")
                m_out_vid_strm = avformat_new_stream(m_outformat, out_vid_codec);
                if(NULL == m_out_vid_strm)
                {
                     PRINT_MSG("Failed to Allocate Output Vid Strm ")
                     ret = -1;
                     return ret;
                }
                else
                {
                     PRINT_MSG("Allocated Video Stream ")
                     if(avcodec_copy_context(m_out_vid_strm->codec,
                        m_informat->streams[m_in_vid_strm_idx]->codec) != 0)
                     {
                        PRINT_MSG("Failed to Copy Context ")
                        ret = -1;
                        return ret;
                     }
                     else
                     {
                        m_out_vid_strm->sample_aspect_ratio.den =
                        m_out_vid_strm->codec->sample_aspect_ratio.den;

                        m_out_vid_strm->sample_aspect_ratio.num =
                        m_in_vid_strm->codec->sample_aspect_ratio.num;
                        PRINT_MSG("Copied Context ")
                        m_out_vid_strm->codec->codec_id = m_in_vid_strm->codec->codec_id;
                        m_out_vid_strm->codec->time_base.num = 1;
                        m_out_vid_strm->codec->time_base.den =
                        m_fps*(m_in_vid_strm->codec->ticks_per_frame);
                        m_out_vid_strm->time_base.num = 1;
                        m_out_vid_strm->time_base.den = 1000;
                        m_out_vid_strm->r_frame_rate.num = m_fps;
                        m_out_vid_strm->r_frame_rate.den = 1;
                        m_out_vid_strm->avg_frame_rate.den = 1;
                        m_out_vid_strm->avg_frame_rate.num = m_fps;
                        m_out_vid_strm->duration = (m_out_end_time - m_out_start_time)*1000;
                     }
                   }
                }
          }

        if(outfmt->audio_codec != AV_CODEC_ID_NONE && m_in_aud_strm != NULL)
        {
            out_aud_codec = avcodec_find_encoder(outfmt->audio_codec);
            if(NULL == out_aud_codec)
            {
                PRINT_MSG("Could Not Find Out Aud Encoder ")
                ret = -1;
                return ret;
            }
            else
            {
                PRINT_MSG("Found Out Aud Encoder ")
                m_out_aud_strm = avformat_new_stream(m_outformat, out_aud_codec);
                if(NULL == m_out_aud_strm)
                {
                    PRINT_MSG("Failed to Allocate Out Vid Strm ")
                    ret = -1;
                    return ret;
                }
                else
                {
                    if(avcodec_copy_context(m_out_aud_strm->codec,
                       m_informat->streams[m_in_aud_strm_idx]->codec) != 0)
                    {
                        PRINT_MSG("Failed to Copy Context ")
                        ret = -1;
                        return ret;
                    }
                    else
                     {
                        PRINT_MSG("Copied Context ")
                        m_out_aud_strm->codec->codec_id = m_in_aud_strm->codec->codec_id;
                        m_out_aud_strm->codec->codec_tag = 0;
                        m_out_aud_strm->pts = m_in_aud_strm->pts;
                        m_out_aud_strm->duration = m_in_aud_strm->duration;
                        m_out_aud_strm->time_base.num = m_in_aud_strm->time_base.num;
                        m_out_aud_strm->time_base.den = m_in_aud_strm->time_base.den;

                    }
                }
             }
          }
 // 6. Finally output header.
      if (!(outfmt->flags & AVFMT_NOFILE))
          {
            if (avio_open2(&m_outformat->pb, outfile.c_str(), AVIO_FLAG_WRITE,NULL, NULL) < 0)
            {
                    PRINT_VAL("Could Not Open File ", outfile)
                    ret = -1;
                    return ret;
            }
          }
            /* Write the stream header, if any. */
          if (avformat_write_header(m_outformat, NULL) < 0)
          {
                PRINT_VAL("Error Occurred While Writing Header ", outfile)
                ret = -1;
                return ret;
          }
          else
          {
                PRINT_MSG("Written Output header ")
                m_init_done = true;
          }

// 7. Now in while loop read frame using av_read_frame and write to output format using
//  av_interleaved_write_frame(). You can use following loop

      while(av_read_frame(m_informat, &pkt) >= 0 && (m_num_frames-- > 0))
            {
                if(pkt.stream_index == m_in_vid_strm_idx)
                {
                    PRINT_VAL("ACTUAL VID Pkt PTS ",av_rescale_q(pkt.pts,m_in_vid_strm->time_base, m_in_vid_strm->codec->time_base))
                    PRINT_VAL("ACTUAL VID Pkt DTS ", av_rescale_q(pkt.dts, m_in_vid_strm->time_base, m_in_vid_strm->codec->time_base ))
                    av_init_packet(&outpkt);
                    if(pkt.pts != AV_NOPTS_VALUE)
                    {
                        if(last_vid_pts == vid_pts)
                        {
                            vid_pts++;
                            last_vid_pts = vid_pts;
                        }
                        outpkt.pts = vid_pts;
                        PRINT_VAL("ReScaled VID Pts ", outpkt.pts)
                    }
                    else
                    {
                        outpkt.pts = AV_NOPTS_VALUE;
                    }

                    if(pkt.dts == AV_NOPTS_VALUE)
                    {
                        outpkt.dts = AV_NOPTS_VALUE;
                    }
                    else
                    {
                        outpkt.dts = vid_pts;
                        PRINT_VAL("ReScaled VID Dts ", outpkt.dts)
                        PRINT_MSG("=======================================")
                    }

                    outpkt.data = pkt.data;
                    outpkt.size = pkt.size;
                    outpkt.stream_index = pkt.stream_index;
                    outpkt.flags |= AV_PKT_FLAG_KEY;
                    last_vid_pts = vid_pts;
                    if(av_interleaved_write_frame(m_outformat, &outpkt) < 0)
                    {
                        PRINT_MSG("Failed Video Write ")
                    }
                    else
                    {
                        m_out_vid_strm->codec->frame_number++;
                    }
                    av_free_packet(&outpkt);
                    av_free_packet(&pkt);
                }
                else if(pkt.stream_index == m_in_aud_strm_idx)
                {
                    PRINT_VAL("ACTUAL AUD Pkt PTS ", av_rescale_q(pkt.pts, m_in_aud_strm->time_base, m_in_aud_strm->codec->time_base))
                    PRINT_VAL("ACTUAL AUD Pkt DTS ", av_rescale_q(pkt.dts, m_in_aud_strm->time_base, m_in_aud_strm->codec->time_base))
                    //num_aud_pkt++;
                    av_init_packet(&outpkt);
                    if(pkt.pts != AV_NOPTS_VALUE)
                    {
                        outpkt.pts = aud_pts;
                        PRINT_VAL("ReScaled AUD PTS ", outpkt.pts)
                    }
                    else
                    {
                        outpkt.pts = AV_NOPTS_VALUE;
                    }

                    if(pkt.dts == AV_NOPTS_VALUE)
                    {
                        outpkt.dts = AV_NOPTS_VALUE;
                    }
                    else
                    {
                        outpkt.dts = aud_pts;
                        PRINT_VAL("ReScaled AUD DTS ", outpkt.dts)
                        PRINT_MSG("====================================")
                        if( outpkt.pts >= outpkt.dts)
                        {
                            outpkt.dts = outpkt.pts;
                        }
                        if(outpkt.dts == aud_dts)
                        {
                            outpkt.dts++;
                        }
                        if(outpkt.pts < outpkt.dts)
                        {
                            outpkt.pts = outpkt.dts;
                            aud_pts = outpkt.pts;
                        }
                    }

                    outpkt.data = pkt.data;
                    outpkt.size = pkt.size;
                    outpkt.stream_index = pkt.stream_index;
                    outpkt.flags |= AV_PKT_FLAG_KEY;
                    vid_pts = aud_pts;
                    aud_pts++;
                    if(av_interleaved_write_frame(m_outformat, &outpkt) < 0)
                    {
                        PRINT_MSG("Faile Audio Write ")
                    }
                    else
                    {
                        m_out_aud_strm->codec->frame_number++;
                    }
                    av_free_packet(&outpkt);
                    av_free_packet(&pkt);
            }
            else
            {
                PRINT_MSG("Got Unknown Pkt ")
                //num_unkwn_pkt++;
            }
            //num_total_pkt++;
        }

//8. Finally write trailer and clean up everything

     av_write_trailer(m_outformat);
        av_free_packet(&outpkt);
        av_free_packet(&pkt);


text:
Q: 8086 assembly mov instruction not error Im write this code in 8086 emulator and emulate but not give any error why?
org 100h

mov 1ah,dh

ret

edit:
this is the emulate output

A: emu8086 changed mov 1ah,dh to mov [1ah],dh. With square brackets it means: store DH to the memory at address DS:001A (not 0001A). I'd like to say that this behavior is a bug.


text:
Q: Telerik RadGrid.MasterTableView.ExportToExcel() Error: The query results enumerated more than once I have a RadGrid which is populated with some data.  I have a button which will Export to Excel via a serverside callback.  The server side code is below.  And the error below that.  Any suggestions?
RadGrid1.Rebind();
   RadGrid1.ExportSettings.IgnorePaging = true;
   RadGrid1.MasterTableView.ExportToExcel();

The error is:

The query results cannot be enumerated more than once.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The query results cannot be enumerated more than once.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The query results cannot be enumerated more than once.]
     System.Data.Linq.SqlClient.OneTimeEnumerable1.GetEnumerator() +884205
     System.Data.Linq.SqlClient.SingleResult1.GetEnumerator() +76
     System.Linq.Buffer1..ctor(IEnumerable1 source) +302
     System.Linq.d__0.MoveNext() +164
     System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +163
     Telerik.Web.UI.GridResolveEnumerable.GetCollectionItemType(Boolean noItemsInEnumerator, Type& collectionItemType, Object& collectionFirstObject) +330
     Telerik.Web.UI.GridResolveEnumerable.ParseProperties() +120
     Telerik.Web.UI.GridResolveEnumerable.Initialize() +16
     Telerik.Web.UI.GridResolveEnumerable.EnsureInitialized() +28
     Telerik.Web.UI.GridEnumerableFromDataView..ctor(GridTableView owner, IEnumerable enumerable, Boolean CaseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +242
     Telerik.Web.UI.GridDataSourceHelper.CreateGridEnumerable(GridTableView owner, IEnumerable enumerable, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +223
     Telerik.Web.UI.GridDataSourceHelper.GetResolvedDataSource(GridTableView owner, Object dataSource, String dataMember, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +595
     Telerik.Web.UI.GridTableView.get_ResolvedDataSource() +243
     Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource) +42
     System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +72
     System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +147
     System.Web.UI.WebControls.DataBoundControl.PerformSelect() +261
     Telerik.Web.UI.GridTableView.PerformSelect() +9
     Telerik.Web.UI.GridTableView.DataBind() +363
     Telerik.Web.UI.RadGrid.DataBind() +73
     Telerik.Web.UI.RadGrid.AutoDataBind(GridRebindReason rebindReason) +2488
     Telerik.Web.UI.RadGrid.RebindForExport() +119
     Telerik.Web.UI.Grid.Export.TableViewExporter.PrepareForExport() +315
     System.EventHandler.Invoke(Object sender, EventArgs e) +0
     System.Web.UI.Control.OnPreRender(EventArgs e) +11056782
     System.Web.UI.Control.PreRenderRecursiveInternal() +108
     System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3394

A: You don't want to call Rebind() before the export.  Is there a reason for that?  Are you changing/manipulating the data right before the export?
If not, there is no need to call Rebind(), since that is really only meant to refresh the data source.


text:
Q: document.querySelectorAll([classname]) not working in IE9
Possible Duplicate:
IE9 equivalent of querySelectorAll

I'm trying to get all elements with the classname "video" in some JS running in IE9.  I'm using var videopanels = document.querySelectorAll(".video"); which is working great in Chrome.
Unfortunately I'm getting this error when I watch document.querySelectorAll(".video") in the debugger:
document.querySelectorAll(".video")
Object doesn't support property or method 'querySelectorAll'
Error

However, when I watch document in the debugger (it shows up as a DispHTMLDocument) and open up the [Methods] list, I see
querySelectorAll()
querySelectorAll(v)
IHTMLDOMChildrenCollection

What's going on?  How come I can see it in the debugger, but not (apparently) actually call or use it?

A: Change your doctype to html5 standards.
<!DOCTYPE html>

Also check IE9 isn't operating in compatibility mode as this may cause it to ignore some methods it supports.


text:
Q: Can't figure out why a table element is mis-positioning I am working on a webpage, that I didn't build but am modifying. I am rather new to HTML coding. My problem is that I have a table with three columns and one row. Each column contains one or two pictures over some text. For some reason, the first column (the left column) drops down lower than the rest and I can't figure out why. Sorry, I'm not allowed to post a picture, so you can't see what I'm talking about. I hope I've described the problem well enough.
Here is the code:

            Emerald ash borer hides here

         The emerald ash borer is not always visible as the adults are small enough to fit on the head of a penny. The larvae burrow under the bark and through the wood, often going unseen until the ash tree begins to die. Because larvae and pupae can survive for long periods even in cut wood, a primary way to ensure that you don't spread emerald ash borers is to not move firewood from areas with a known infestation, particularly across state lines.

                         adults

                         1/2 inch long and 1/8 inch wide, metallic emerald green in coloration. Can be distinguished from other similar boring beetles by the disinctive reddish top surface of their abdomen (under the wings). Females lay 50-100 eggs in bark crevices. (Photo: David Cappaert [top], Howard Russell, both Bugwood.org)

                         Canopy

                         As the emerald ash borer larvae feed, the canopy leaves die from the top down. The feeding larvae also trigger new branches and shoots on trunk and branches. (Photo: Daniel Herms, Bugwood.org)

                         girdling

                         Larvae burow into the phloem (bark) and sapwood, creating S-shaped galeries under the bark and blocking nutrient flow. This eventually kills the tree. (Photo: James W. Smith, USDA APHIS PPQ, Bugwood.org)

A: The issue seems to be related to the br line here:

The
 will create a gap even if that image isn't displayed. Remove the line and the titles should line up.
I would also suggest adding to the styles: vertical-align:top;
style="vertical-align:top;width:220px;padding:30px;"

to ensure they align at the top.
Additionally to improve the code there are issues such as:

which should be

*Note the removed semi-colon and style semi-colon moved inside the quotes.
Most of the image tags appear to have this issue.


text:
Q: In React, using TypeScript, how can I forward props to component passed as prop? I have a TS problem where the JS-version of the code works, but I can't get the types to compile.
I've tried to simplify it for this question. Hopefully I didn't remove too much that'll have an effect on the answer.
So, simplified, I'm trying to write a component, <Set> that takes another component as a prop, and wraps that around the children of <Set>. Additionally I want all props passed to <Set> to be passed along to the component passed as a prop.
This is the code
import React, { ReactElement, ReactNode } from "react";

interface WtProps {
  children: ReactNode;
}

type WrapperType<WTProps extends WtProps> = (
  props: WTProps
) => ReactElement | null;

interface SetProps
 {
  wrap: WrapperType
;
  children: ReactNode;
  [x: string]: unknown;
}
export function Set<WProps extends WtProps>(props: SetProps<WProps>) {
  const { wrap, children, ...rest } = props;

  return React.createElement(wrap, rest, children);
}

interface WrapperProps {
  children: ReactNode;
  foo: string;
}
const ChildWrapper: React.FC<WrapperProps> = ({ foo, children }) => {
  return (

ChildWrapper

{foo}

      {children}

  );
};

export default function App() {
  return (
    <Set<WrapperProps> wrap={ChildWrapper} foo="value">

Hello CodeSandbox

Start editing to see some happen!

    </Set>
  );
}

Here's a codesandbox link: https://codesandbox.io/s/musing-feynman-3euuu?file=/src/App.tsx
I've tried a bunch of different solutions, but this is what I have now. And the error I'm getting is on, the rest parameter
  return React.createElement(wrap, rest, children);

It says
No overload matches this call.
  The last overload gave the following error.
    Argument of type '{ [x: string]: unknown; }' is not assignable to parameter of type 'Attributes & WProps'.
      Type '{ [x: string]: unknown; }' is not assignable to type 'WProps'.
        'WProps' could be instantiated with an arbitrary type which could be unrelated to '{ [x: string]: unknown; }'.ts(2769)
index.d.ts(292, 14): The last overload is declared here.

I've read this question+answer How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"? so I think I know why I'm getting the error, but I don't know what to do about it.
What do I need to change to make it compile?
EDIT: I can "fix" it by making the wrap prop have type any, but I don't want to do that. I want stricter types. But anyway, here it is with any https://codesandbox.io/s/pedantic-nobel-x790n

A: I haven't used TS with react but have a lot of experience in React by itself.
So i think you could try this:
export function Set<WProps extends WtProps>(props: SetProps<WProps>) {
  const { wrap, children, ...rest } = props;
  return (
    <>
      <wrap {...rest} />
      {children}
    </>
  );
}

I hope this helps, let me know if this works!


text:
Q: How can I sum these Javascript values? I have the following array of objects. Each object has a pair of objects within it for two people. It's holding scores, e.g. game 1 for Bob has 10 points, then game 2, 9 points etc.
var arr = [{
  "bob": {
    "1": "10",
    "2": "9",
    "3": "9",
    "4": "10",
    "5": "9",
    "6": "7",
    "7": "10",
    "8": "10",
    "9": "10",
    "10": "9",
    "11": "10",
    "12": "8"
  },
  "max": {
    "1": "9",
    "2": "10",
    "3": "10",
    "4": "8",
    "5": "10",
    "6": "10",
    "7": "8",
    "8": "9",
    "9": "9",
    "10": "10",
    "11": "9",
    "12": "10"
  }
},

{
  "bob": {
    "1": "10",
    "2": "9",
    "3": "9",
    "4": "10",
    "5": "9",
    "6": "7",
    "7": "10",
    "8": "10",
    "9": "10",
    "10": "9",
    "11": "10",
    "12": "8"
  },
  "max": {
    "1": "9",
    "2": "10",
    "3": "10",
    "4": "8",
    "5": "10",
    "6": "10",
    "7": "8",
    "8": "9",
    "9": "9",
    "10": "10",
    "11": "9",
    "12": "10"
  }
},
{
  "bob": {
    "1": "10",
    "2": "9",
    "3": "9",
    "4": "10",
    "5": "9",
    "6": "7",
    "7": "10",
    "8": "10",
    "9": "10",
    "10": "9",
    "11": "10",
    "12": "8"
  },
  "max": {
    "1": "9",
    "2": "10",
    "3": "10",
    "4": "8",
    "5": "10",
    "6": "10",
    "7": "8",
    "8": "9",
    "9": "9",
    "10": "10",
    "11": "9",
    "12": "10"
  }
}
]

How can I loop through each pair of objects (bob & max) and create an average out all of it? I find looping within loops really confusing... I'm struggling how to write the question.
The end goal is to have one pair of objects of which the values would be averaged from all of the previous ones in the array. E.G for each person, I need to add up each up the scores (scores 1 - 12) and then create a final average score. I hope this makes sense? In terms of what I have tried, I've tried to manipulate a lot of other SO answers to fit my needs but I kept running into error after error and thus isn't worth posting with this...
 // Final averaged scores for each person based on the total data available
[{
  "bob": {
    "1": "10",
    "2": "9",
    "3": "9",
    "4": "10",
    "5": "9",
    "6": "7",
    "7": "10",
    "8": "10",
    "9": "10",
    "10": "9",
    "11": "10",
    "12": "8"
  },
  "max": {
    "1": "9",
    "2": "10",
    "3": "10",
    "4": "8",
    "5": "10",
    "6": "10",
    "7": "8",
    "8": "9",
    "9": "9",
    "10": "10",
    "11": "9",
    "12": "10"
  }
}]

A: You could take a single loop approach for calculating the wanted avarage. This proposal feature ES5.
Variables:

*

*r: temporary result in Array#reduce,

*o: object, an item of the array,

*a: the reference to he calling array, needed for the length,

*k, l: keys of the nested object.

Patterns:

*

*||: logical OR as default operator.

var array = [{ bob: { 1: "10", 2: "9", 3: "9", 4: "10", 5: "9", 6: "7", 7: "10", 8: "10", 9: "10", 10: "9", 11: "10", 12: "8" }, max: { 1: "9", 2: "10", 3: "10", 4: "8", 5: "10", 6: "10", 7: "8", 8: "9", 9: "9", 10: "10", 11: "9", 12: "10" } }, { bob: { 1: "10", 2: "9", 3: "9", 4: "10", 5: "9", 6: "7", 7: "10", 8: "10", 9: "10", 10: "9", 11: "10", 12: "8" }, max: { 1: "9", 2: "10", 3: "10", 4: "8", 5: "10", 6: "10", 7: "8", 8: "9", 9: "9", 10: "10", 11: "9", 12: "10" } }, { bob: { 1: "10", 2: "9", 3: "9", 4: "10", 5: "9", 6: "7", 7: "10", 8: "10", 9: "10", 10: "9", 11: "10", 12: "8" }, max: { 1: "9", 2: "10", 3: "10", 4: "8", 5: "10", 6: "10", 7: "8", 8: "9", 9: "9", 10: "10", 11: "9", 12: "10" } }],
    result = array.reduce(function (r, o, _, a) {
        Object.keys(o).forEach(function (k) {
            r[k] = r[k] || {};
            Object.keys(o[k]).forEach(function (l) {
                r[k][l] = (r[k][l] || 0) + o[k][l] / a.length;
            });
        });
        return r;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: arr.reduce(function(res, obj, index, array) {
    Object.keys(obj).forEach(function(player) {
        res[player] = res[player] || {};
        Object.keys(obj[player]).forEach(function(game) {
            res[player][game] = res[player][game] || 0;
            res[player][game] += parseFloat(obj[player][game] / array.length);
        });
    });
    return res;
}, {});

A: You could use a combination of array.map and array.reduce to return a sum of the scores.

console.clear();

var games = [
  {
    "bob": { "1": "10", "2": "9", "3": "9", "4": "10" },
    "max": { "1": "9", "2": "10", "3": "10", "4": "8" }
  },
  {
    "bob": { "1": "10", "2": "9", "3": "9", "4": "10" },
    "max": { "1": "9", "2": "10", "3": "10", "4": "8" }
  },
  {
    "bob": { "1": "10", "2": "9", "3": "9", "4": "10" },
    "max": { "1": "9", "2": "10", "3": "10", "4": "8" }
  }
];

let scores = {};
games.forEach( game => {
  Object.keys(game).forEach( player => {
    scores[player] = scores[player] || {};
    Object.keys(game[player]).forEach(gameNumber => {
      scores[player][gameNumber] = scores[player][gameNumber] || [];
      scores[player][gameNumber].push(parseInt(game[player][gameNumber]));
    });
  });
});

Object.keys(scores).forEach( player => {
  Object.keys(scores[player]).forEach(game => {
    let total = scores[player][game].reduce((a, b) => { return a+b; });
    let length = scores[player][game].length;

    scores[player][game] = total / length;
  });
});

console.info( scores );

A: I used basic loops for this :
var gameCount = arr.length;

var outPutArr = {"bob":{},"max":{}};

// Initialize the output array
for(var i=1;i<=Object.keys(arr[0].bob).length;i++)
{
    outPutArr["bob"][i+""] = "0";
    outPutArr["max"][i+""] = "0";
}

// Loop through all games and add score of bob and max
arr.forEach(function(item){
    for(var i=1;i<=Object.keys(arr[0].bob).length;i++)
    {
        outPutArr["bob"][i+""] = (parseInt(item["bob"][i+""]) + parseInt(outPutArr["bob"][i+""]))+"";
        outPutArr["max"][i+""] = (parseInt(item["max"][i+""]) + parseInt(outPutArr["max"][i+""]))+"";
    }
});

for(var i=1;i<=Object.keys(arr[0].bob).length;i++)
{
    outPutArr["bob"][i+""] = (parseInt(outPutArr["bob"] [i+""])/gameCount)+"";
    outPutArr["max"][i+""] = (parseInt(outPutArr["max"] [i+""])/gameCount)+"";
}

console.log(JSON.stringify(outPutArr));

A: Would this be what you wanted?
It sums for however users you have scores from how much games you have (as long as it's not 100+ per single object) and stores results in summs object
You can observe results in console from this fiddle
var arr = [{
  "bob": {
    "1": "10",
    "2": "9",
    "3": "9",
    "4": "10",
    "5": "9",
    "6": "7",
    "7": "10",
    "8": "10",
    "9": "10",
    "10": "9",
    "11": "10",
    "12": "8"
  },
  "max": {
    "1": "9",
    "2": "10",
    "3": "10",
    "4": "8",
    "5": "10",
    "6": "10",
    "7": "8",
    "8": "9",
    "9": "9",
    "10": "10",
    "11": "9",
    "12": "10"
  }
},

{
  "bob": {
    "1": "10",
    "2": "9",
    "3": "9",
    "4": "10",
    "5": "9",
    "6": "7",
    "7": "10",
    "8": "10",
    "9": "10",
    "10": "9",
    "11": "10",
    "12": "8"
  },
  "max": {
    "1": "9",
    "2": "10",
    "3": "10",
    "4": "8",
    "5": "10",
    "6": "10",
    "7": "8",
    "8": "9",
    "9": "9",
    "10": "10",
    "11": "9",
    "12": "10"
  }
},
{
  "bob": {
    "1": "10",
    "2": "9",
    "3": "9",
    "4": "10",
    "5": "9",
    "6": "7",
    "7": "10",
    "8": "10",
    "9": "10",
    "10": "9",
    "11": "10",
    "12": "8"
  },
  "max": {
    "1": "9",
    "2": "10",
    "3": "10",
    "4": "8",
    "5": "10",
    "6": "10",
    "7": "8",
    "8": "9",
    "9": "9",
    "10": "10",
    "11": "9",
    "12": "10"
  }
}
]

var summs = {};

arr.forEach(function(users, ind, arr){
    for (var user in users) {
    if (users.hasOwnProperty(user)) {
      if (!summs.hasOwnProperty(user)) summs[user] = 0;
      console.log(users[user]);
        for (var i = 0; i < 100; i++){
            if (users[user].hasOwnProperty(i+'')){
                summs[user] += parseInt(users[user][i]);
            }
      }
    }
  }
});
console.log(summs);


text:
Q: Type for icon in React Component's Interface Using Radix-UI's Accordion, the reusable component is changed in order to accept as props an icon.
The interface:
interface AccordionTriggerProps {
  trigger: string;
  icon?: StyledComponent<
    React.FunctionComponent<
      React.SVGProps<SVGSVGElement> & {
        title?: string | undefined;
      }
    >,
    never
  >;
}

The component that uses the above interface:
const AccordionTrigger = ({ trigger, icon }: AccordionTriggerProps) => (
  <header>
    {icon}
    {trigger}
  </header>
);

The component reused in other place like following:
<AccordionTrigger trigger="Learn" icon={<StyledLearnIcon />} />

It works fine, it renders the component but it still says there is an error for the icon:

Type 'Element' is not assignable to type
'StyledComponent<FunctionComponent<SVGProps & { title?:
string | undefined; }>, never, {}, never>'

Any idea why and how to fix it?
How the icon is defined:
import { ReactComponent as LearnIcon } from 'svgs/learn.svg';

export const StyledLearnIcon = styled(LearnIcon)`
  width: 20px;
  fill: white;
`;


text:
Q: How to generate random key for HMACSHA256 signature calculation I need to calculate a signature of some strings and was planning on doing this like this:
using (HMACSHA256 hmacSha256 = new HMACSHA256( <randombytes>))
{
         Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
         signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}

I am going to store the key together with my user data, but i am not sure if the randombytes can just be random or how to generate them in c#.
What is the proper way to generate random keys?

A: If you want your random bytes to be securely random, then you could use the RNGCryptoServiceProvider.


text:
Q: (Python) Try and Except within a User-Defined Function I have worked on many projects (school projects, I'm not too advanced), and have found that in many programs where I require the user to input a value that is an integer, or decimal(float), I need to use a "try-except" statement, within a while loop, in order to make certain that the user inputs the required value type.
For example:
def main():

    userValue = input("Please enter an integer: ")

    while(True):

        try:
            userValue = int(userValue)
            break
        except:
            userValue = input("That is not an integer, try again: ")

    print("The integer you entered is: " + str(userValue))

main()

# Input: SADASD (A non-integer value)
# Output: "That is not an integer, try again: "
# Second-Input: 3
# Second-Output: "The integer you entered is: 3"

Understandably, typing out this entire section of code repeatedly, in a program that requires user input multiple times, is not really efficient. So understanding, that user-defined functions help when I need to perform one action, multiple times. With this in mind, I defined my own function with that same try-except statement in a while loop. However, now, when I use the function, instead of printing the same output previously, rather, it prints out the first value the user had input.
For example:
def valueCheck_Integer(userInput):
    while(True):

        try:
            userInput= int(userInput)
            break
        except:
            userInput = input("That is not an integer, try again: ")

def main():

    userValue = input("Please enter an integer: ")

    valueCheck_Integer(userValue)

    print("The integer you entered is: " + str(userValue))

main()

# Input: SADASD (A non-integer value)
# Output: "That is not an integer, try again: "
# Second-Input: SASASD
# Second-Output: "That is not an integer, try again: "
# Third-Input: 3
# Third-Output: SADASD (The first value that the user Input, instead of 3)

Can someone please explain to me why this happens, and some suggestions on how to fix it?
Thank you!

A: It is because of you are printing userValue instead of userInput.
I used return make it easier. So the code will be like this
def valueCheck_Integer(userInput):
    while(True):

        try:
            userInput= int(userInput)
            break
        except:
            userInput = input("That is not an integer, try again: ")
    return userInput

def main():

    userValue = input("Please enter an integer: ")

    print("The integer you entered is: " + str(valueCheck_Integer(userValue)))

main()

You can make your code smaller like this:
def valueCheck_Integer(userInput):

    while not(userInput.isdigit()):
        userInput = input("That is not an integer, try again: ")

    return userInput

def main():

    userValue = input("Please enter an integer: ")

    print("The integer you entered is: " + str(valueCheck_Integer(userValue)))

main()

A: It's probably going to be easier to expect the function to get/check/return the integer rather than check input you already have. You can pass it the string to use for asking for the value (you could also pass the error string). It will keep asking until it's successful and then return the number you want:
def get_integer(question):
    while(True):
        try:
            return int(input(question))
        except ValueError:
            question = "That is not an integer, try again:"

def main():
    userValue = get_integer("Please enter an integer: ")
    print("The integer you entered is: " + str(userValue))

main()

A: First off, Good Question.
To understand what is going on, we first have to talk about scope of a variable.
When you define a variable outside a function, it becomes something called a global variable. This basically means that you can access it from anywhere in your code. When you define the variable within a function, it becomes a local variable. This means that it is only accessible from within your function. Finally, when a function gets passed in a variable, it gets its own local copy of the variable to work with.
Now let's look at your code.
when you call valueCheck_Integer(userInput): the function gets its own copy of userInput to work with. thus all the changes that the function does modifies the local userInput while the global userInput stays the same. As such, when the user enters a correct answer, the global userInput is the one that gets printed and the changes the function makes to local userInput is lost.
So, how can we fix this?
There are two main methods:
1)Using the global keyword
def valueCheck_Integer(userInput):
global userInput
    while(True):

        try:
            userInput= int(userInput)
            break
        except:
            userInput = input("That is not an integer, try again: ")

This keyword asks the function to modify the global userInput
2)Returning a value
def valueCheck_Integer(userInput):
    while(True):

        try:
            userInput= int(userInput)
            break
        except:
            userInput = input("That is not an integer, try again: ")
    return userInput

def main():

    userValue = input("Please enter an integer: ")

    print("The integer you entered is: " + str(valueCheck_Integer(userValue)))

main()

This works by returning the local copy of userInput and modifying global userInput to equal local userInput
The second code I used was from
Osadhi Virochana Jayasinghe Si's answer.

A: It's because, if you see your line of code where you print the final output -:
print("The integer you entered is: " + str(userValue))

you will realise that the value you are printing is the one you take the first time from the input function. But this is not the value you have been working on to achieve in your other function.
So for you to rather get that value, the function in some way has to return it back to you.
For this you should allow the function to return the value in the last line.
like so -:
return userInput

and then change the line where you call function so it saves the value returned.
like so -:
userValue = valueCheck_Integer(userValue)

Also as mentioned by others using the global keyword you can define the variable in global scope.
But this is really not a good practice until really needed as it can increase the amount of space that the var is taking, before the variable only took the space for a limited time for when the function is called, but now the variable takes space throughout the time the program runs.
While return will not do so as it will only return the value and once assigned to the already defined variable it will remove the returned value from space.
This should hopefully fix your problem.
I hope this helps.
And also hope that you're safe during the time of this ongoing pandemic.


text:
Q: range() column in Pandas I have DataFrame which looks like:
data_df = pd.DataFrame({
  'col1': ['a', 'b', 'c'],
  'col2': [2, 1, 3]
})

The goal is to apply range on col2 and get new DataFrame which will represent this data:
a 1
a 2
b 1
c 1
c 2
c 3

So far I got to the point having 2 DataFrames:
requests_series = pd.Series([np.arange(0, col2, 1) + 1 for col1, col2 in zip(data_df.col1, data_df.col2)], data_df.index, name='requests')
requests_df = requests_series.to_frame()
data_df.pop('col2')

and now stuck how to merge them desired way.
I rather looking for an efficient way, because on production it will end up dealing with 10M rows.

A: Let's try repeat and then groupby().cumcount():
(data_df.loc[data_df.index.repeat(data_df['col2'])]
        .assign(col2=lambda x: x.groupby(level=0).cumcount()+1)
    )

Output:
  col1  col2
0    a     1
0    a     2
1    b     1
2    c     1
2    c     2
2    c     3


text:
Q: How to forward constructor arguments to boost::optional I have the following simple struct:
struct X
{
    X(std::string name, int value): name_(name), value_(value){}

    std::string name_;
    int value_;
};

I would like to use it with boost optional without copying. Here is one option:
boost::optional<X> op;
op.emplace("abc", 5);

Is it possible without using emplace function ? (I mean one line expression)

A: Yeah, just construct it with the "in place" tag which forwards ctor args!
boost::optional<X> op(boost::optional::in_place_init, "abc", 5);

(ref)
FWIW if you don't mind a move then this works too:
boost::optional<X> op(X("abc", 5));

Scan down that reference page; there are loads of ways to construct or fill a boost::optional.


text:
Q: How to change image on button? I have two bottom left (<) side button and right (>) button. I have to change the images from array with left and right button action?
Code :
- (IBAction)onClickRightLeft:(id)sender {

    switch ([sender tag]) {
        case 10:
            indexValueL++;
            if(indexValueL >= 3)
            {
                indexValueL = 2;
            }
            if(indexValueL < 0)
            {
                indexValueL=0;
            }
            [imgViewStory setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[[[arrGlobal objectAtIndex:indexValueL] valueForKey:@"FeaturedStoryImage"]]]];
            break;
        case 20:
            indexValueR++;
            if(indexValueR >= 3)
            {
                indexValueR = 2;
            }
            if(indexValueR < 0)
            {
                indexValueR=0;
            }
            [imgViewStory setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[[[arrGlobal objectAtIndex:indexValueR] valueForKey:@"FeaturedStoryImage"]]]];
            break;

        default:
            break;
    }

How do I manage an array index?

A: I think this should do.. (not tested)
- (IBAction)onClickRightLeft:(id)sender {

    switch ([sender tag]) {
        case 10: // considering right clicked
            indexValue++;
            break;
        case 20: // considering left clicked
            indexValue--;
            break;
    }

    if(indexValue >= 3)
    {
        indexValue = 0;
    }
    if(indexValue < 0)
    {
        indexValue=2;
    }
    [imgViewStory setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[[[arrGlobal objectAtIndex:indexValue] valueForKey:@"FeaturedStoryImage"]]]];

Also while showing image, you should consider it caching & asynch loading. Check this for more info


text:
Q: How to extract only multiple field from JSON into Google Sheets using Google Sheets app script function import_inventory_test(e) {
  var options = {
    "method": "GET",
    "headers": {
      'Content-Type': 'application/json',
      'Prefer': 'code=200',
      'Prefer': 'dynamic=true',
      "clientId": "1",
      "key": "1",
    }
  }
  var text = UrlFetchApp.fetch("https://stoplight.io/mocks/flowhub/public-developer-portal/24055485/v0/inventory?max=100", options).getContentText();
  var json = JSON.parse(text);

  // I added the below script.
  var values = json.data.map(({ sku }) => [sku]);
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set your sheet name.
  sheet.getRange(1, 1, values.length).setValues(values);
}

How can I populate a-d columns with the following fields (by that order): sku (A) quantity (B) productName (C) brand (D)

A: In your script, when your script is modified, how about the following modification?
From:
var values = json.data.map(({ sku }) => [sku]);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set your sheet name.
sheet.getRange(1, 1, values.length).setValues(values);

To:
var values = json.data.map(({ sku, quantity, productName, brand }) => [sku, quantity, productName, brand]);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set your sheet name.
sheet.getRange(1, 1, values.length, values[0].length).setValues(values);

Note:

*

*If you want to add and modify the values you need, in this case, please modify json.data.map(({ sku, quantity, productName, brand }) => [sku, quantity, productName, brand]).

Reference:

*

*Destructuring assignment


text:
Q: using libusb with embeded system linux based i'm using libusb in intel edison board
lsusb command shows the usb device but when i try to run the code I get this error:
root@admin:/root# ./out
Error finding USB device

here is lsusb command output:
root@admin:/root# lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 0483:3748 STMicroelectronics ST-LINK/V2
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

i'm using this example
Do you have any idea?


text:
Q: How to respond to button clicks in SetInterval for Pebble? I've been trying to implement in an app, stopwatch functionality on Pebble using Pebble.JS via SetInterval. I know that it's not recommended but I don't need that high precision right now.
The stopwatch will start, but I can't stop the stopwatch. I set it up so that by pressing select it should move to a new screen.
wind.on('click', 'select', function(e){
    var wind2 = new UI.Window();
    var textfield = new UI.Text({
      position: new Vector2(0, 0),
      size: new Vector2(144, 30),
      font: 'gothic-24-bold',
      text: 'Timer Started!',
      textAlign: 'center'
    });
    wind2.add(textfield);
    var textfield2 = new UI.Text({
       position: new Vector2(0, 60),
       size: new Vector2(144, 30),
       font: 'gothic-24-bold',
       text: 'PlaceHolder',
       textAlign: 'center'
     });
    wind2.add(textfield2);
    wind2.show();
    var timerID = 0;
    window.clearInterval(timerID);
    timerID = window.setInterval(function(){clockt(textfield2)},1000);

    wind2.on('click', 'select', function(e){
        timerID.clearInterval();
        var finaltime = convert(time1);
        seconds = pad(finaltime[0], 2);
        minutes = pad(finaltime[1], 2);
        var strfinaltime = "Total Time: \n" + hours + ":" + minutes + ":" + seconds +"\n" + time1
        var wind3 = new UI.Window();
        var textfield3 = new UI.Text({
            position: new Vector2(0, 50),
            size: new Vector2(144, 30),
            font: 'gothic-24-bold',
            text: strfinaltime,
            textAlign: 'center'
        });
        wind3.add(textfield3);
        wind3.show();
        time1 = 0;
    });
  });

A: I think I found the problem, even though you were not clear what you meant by it not stopping. You called clearInterval two different ways. Try changing the second one to how you did the first one. Your code should look like this now for that section:
var timerID = 0;
window.clearInterval(timerID);
timerID = window.setInterval(function(){clockt(textfield2)},1000);

wind2.on('click', 'select', function(e){
    window.clearInterval(timerID);  // was previously timerID.clearInterval();
    var finaltime = convert(time1);


text:
Q: Js - detect if was page called from history
Possible Duplicate:
Can you detect/redirect a back button press through javascript?

I am developing a small web application. In my application I must know when the user clicks the "back" button, so I can run some javascript code. Is there any such way to detect it?
thank you

A: Ok, so I discovered that the JS API cannot access the history object's next property without elevated permissions, which got me thinking in another direction.
Form fields are automatically fetched from the browser's cache, thus holding historic data. while this is true, javascript code is run independently each time.
So I created a small hidden field to hold a timestamp and compare it against the javascript's generated datatime.
Here is the code, I am sure it can be much better implemented, though time is short:
$(document).ready(function () {
     var date = new Date();
     var clientMiliseconds = date.getTime();
     clientMiliseconds = roundTime(clientMiliseconds);
     var serverTimeStamp = $('#' + '<%= hfTimeStamp.ClientID %>').val();
     serverTimeStamp = roundTime(serverTimeStamp);
     alert(serverTimeStamp == clientMiliseconds);
});

function roundTime(time) {
    time = Math.floor(time);
     //since the server renders the time components a few seconds before the page is downloaded
     //which also depends on where you assign the date on the serverside
     //we've got a small inaccuracy of few seconds. we neglect these seconds, assuming that it would take the user
     //a few seconds to click the back button

     time = time / 10000;
     time = Math.floor(time);
     return time;
}

A: You can't do that. you can bind an event so that something happens when your user navigates away from the page (use onbeforeunload or unload() to do that) but there is no way to know where he has gone


text:
Q: Take the Supersets of Arrays i have a column in a Snowflake table that returns arrays.
Eg-
['A','U']
['A','P','U']
['A','P']
['P','U']
['M','S']
['S']

i need to remove the subsets and just take the supersets, so only
['A','P','U']
['M','S']

is there an easy way to do this?

A: not the best solution but if you can't find better try something like this:
SELECT *
FROM (
     SELECT a, b, c,
            ROW_NUMBER() OVER (PARTITION BY a ORDER BY b) AS row_num
        FROM (
           SELECT a, b, c,
            ROW_NUMBER() OVER (PARTITION BY a ORDER BY c) AS row_num
        FROM (
            SELECT a, b, c,
            ROW_NUMBER() OVER (PARTITION BY c ORDER BY b) AS row_num
            FROM (
           SELECT a, b, c,
            ROW_NUMBER() OVER (PARTITION BY b ORDER BY b) AS row_num
            from supertset
            ) where row_num = 1
        )
        )
    )
QUALIFY row_num = 1

for reference:
https://docs.snowflake.com/en/sql-reference/constructs/qualify.html

A: For each array we are going to look what array contains it, by looking with a cross join for one with the largest intersection, and then choose the one that's the largest between those:
select distinct x
from (
    select b.x
    from data a
    cross join data b
    qualify 1 = row_number() over(
        partition by a.id
        order by array_size(array_intersection(a.x, b.x)) desc
        , array_size(b.x) desc
    )
)

This might not work with a different sample dataset, but the rules that the question includes are not enough to determine the right solution in other situations.
Data setup:
with data as (
select row_number() over(order by 1) id, parse_json(value) x
from table(split_to_table($$['A','U']
['A','P','U']
['A','P']
['P','U']
['M','S']
['S']$$, '\n'))
)


text:
Q: On finding an inequality utilizing the norm of projections. I was looking at this paper where a Schauder basis for $L_1(0, \infty)$ is found and I could not understand how an inequality was derived.
To facilitate the curious reader I will upload the definition of Haar functions and the full proposition where I do not understand how the inequality was derived. Still I advise answerers to skip down to my problems that involve only the last inequality.

Here are my problems:

*

*How do I find the conditional expectation projection onto the closed span of $\{ 1_{(i-1,i)}  \}^{\infty}_{i = 1}$ and how do I obtain its norm?

*What is the complementary projection on $\{ h_i\}^{\infty}_{i =1}$ and how do I find its norm?


text:
Q: Why do some operators create a different type of Dataset like RelationalGroupedDataset? Some operators of Dataset create a new Dataset and update the logical plan, like 'filter' as below:
def filter(condition: Column): Dataset[T] = withTypedPlan {
  Filter(condition.expr, logicalPlan)
}

But there are operators, like groupBy, that create a different type of Dataset, i.e. RelationalGroupedDataset.
Why doesn't Spark create a new Dataset with a LogicalPlan which can express groupBy?
@scala.annotation.varargs
def groupBy(cols: Column*): RelationalGroupedDataset = {
  RelationalGroupedDataset(toDF(), cols.map(_.expr), RelationalGroupedDataset.GroupByType)
}

A: *

*Because groupBy and groupByKey are not transformations. They are only a component of bigger transformations which consist of:

*

*Grouping expression.

*Aggregating expression.

*Operations which can be executed on a "grouped data" are not the same as the ones which can be executed on "ungrouped data" and the other way around. For example:

*

*You cannot select from grouped data because it is not its final state (doesn't correspond to a complete physical RDD).

*You can aggregate or map groups if there are no groups.

A: My understanding is that the high-level Dataset API tries to be as close to SQL as possible so reading one should easily "show" the other and vice versa.
In SQL when you use "GROUP BY" clause it represents no results, but logical groupings of data within a dataset. It's similar to partitions in RDD API that are simply a way to logically partition (and distribute) parts of dataset.
SQL's "GROUP BY" alone means nothing and you have to do something on the grouping and hence SELECT that gives the "environment" to execute actions on the groupings.
That corresponds nicely to Dataset API's RelationalGroupedDataset where you have the concept of groupings specified. It only serves the purpose of defining the groupings on which you can execute aggregations and hence the generic agg operator.
What's interesting is that the entire dataset is one single group and so you can execute agg operator on a Dataset directly (without groupBy which is equivalent to calling groupBy.agg with the empty discriminator function).


text:
Q: C malloc and free does not work I am new to C and I have some troubles with malloc and free. I can not figure it out where is the problem. I have a program with prime.c and main.c
I use malloc allocation for my array and when I call free in main.c valgrind shows me this error
==13518==     in use at exit: 0 bytes in 0 blocks
==13518==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==13518==
==13518== All heap blocks were freed -- no leaks are possible
==13518==
==13518== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
==13518==
==13518== 1 errors in context 1 of 1:
==13518== Invalid read of size 1
==13518==    at 0x40D2DFB: ____strtol_l_internal (in /usr/lib/libc-2.23.so)
==13518==    by 0x40D2C68: strtol (in /usr/lib/libc-2.23.so)
==13518==    by 0x40CFAFF: atoi (in /usr/lib/libc-2.23.so)
==13518==    by 0x80487B0: main (in /media/test/prime)
==13518==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==13518==
==13518== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

here are my two classes
prime.c
    #include <stdio.h>
#include <stdlib.h>
#include "prime.h"
#include <stdint.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
#include <unistd.h>

uint64_t* findPrime(uint64_t max ,size_t* primeCount)
{

    int cnt=0;
    uint64_t *array;
    array = (uint64_t *) malloc(max * sizeof(uint64_t));

    if(array ==NULL)
    {

    return (uint64_t*) 1;
    }

for(int i =2; i < max;i++)
    {
    array[i] = i;
    }

for(int i = 2;i <= sqrt(max);i++)
    {

    if(array[i] != 0)
    {

for(int j = (i*i); j< max; j =j+i)
        {
    array[j] = 0;
        }
    }
    }

for(int i =2; i <max; i++)
    {
        if(array[i])
        {
        cnt++;
        }
    }

    *primeCount = cnt;
return array;
}

main.c
#include <stdio.h>
#include <stdlib.h>
#include "prime.h"
#include <string.h>

int main(int argc, char* argv[]){

    int len = argc-1;
    int limit = atoi(argv[1]);
    int ret =1;
    size_t pc =0;

    if(len == 1)
    {
    limit = atoi(argv[1]);
    }
    else if(len == 2)
    {
    limit = atoi(argv[2]);
    ret = strcmp(argv[1],"-p");

    if(ret != 0)
    {
    printf("Invalid input!\n");
    return 1;
    }
    }
    else
    {
    printf("Wrong number of arguments!!!\n");
    return 1;
    }

    uint64_t* primes  = findPrime(limit, &pc);
       printf("Total number of primes %zu \n", pc);

    if(ret == 0)
    {
        for(int i =2; i < limit;i++)
        {
        if(primes[i] != 0)
        {
            printf("primess: %lld \n", primes[i]);
        }
        }
    }
    free(primes);
    }

A: The stack trace in the valgrind output attributes the error to one of the three calls to atoi() by main().  The specific problem appears to be that a null pointer was passed to that function.  The argument to each atoi() call is an element of the argv array, so your (immediate) problem is with program argument handling, not with dynamic memory allocation.
It looks like the problem must be here:
int limit = atoi(argv[1]);

You perform that atoi() call unconditionally, but when argc is less than 2, it exhibits undefined behavior.


text:
Q: program written in dafny, implementing the Merge Sorted Arrays in-Place algorithm Here is the program that given to me in dafny:
method Main() {
    var a, b := new int[3] [3,5,8], new int[2] [4,7];
    print "Before merging the following two sorted arrays:\n";
    print a[..];
    print "\n";
    print b[..];
    ghost var AB := multiset(a[..]+b[..]);
    assert Sorted(a[..]) && Sorted(b[..]);
    MergeSortedArraysInPlace(a, b, AB);
    assert multiset(a[..]+b[..]) == AB;
    assert Sorted(a[..]+b[..]);
    print "\nAfter merging:\n";
    print a[..]; // [3,4,5]
    print "\n";
    print b[..]; // [7,8]
}

predicate Sorted(q: seq<int>)
{
    forall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j]
}

method MergeSortedArraysInPlace(a: array<int>, b: array<int>, ghost AB: multiset<int>)
    requires Sorted(a[..]) && Sorted(b[..])
    requires multiset(a[..]+b[..]) == AB
    requires a != b
    ensures Sorted(a[..]+b[..])
    ensures multiset(a[..]+b[..]) == AB
    modifies a, b

now i need to Implement iteratively, correctly, efficiently and clearly the MergeSortedArraysInPlace method.
Restriction: Merge the arrays in place, using constant additional space only.
so the implementation that i wrote is the following:
method MergeSortedArraysInPlace(a: array<int>, b: array<int>, ghost AB: multiset<int>)
    requires Sorted(a[..]) && Sorted(b[..])
    requires multiset(a[..]+b[..]) == AB
    requires a != b
    ensures Sorted(a[..]+b[..])
    ensures multiset(a[..]+b[..]) == AB
    modifies a, b
{
    var i := 0;
    var j := 0;
    while (i < a.Length && j < b.Length)
    decreases a.Length - i, if i < a.Length then b.Length - j else 0 - 1
    {
         // if a[i] <= b[j] then both array is
        // already sorted
        if (a[i] <= b[j]) {
            i := i + 1;
        }
        // if a[i]>b[j] then first we swap
        // both element so that a[i] become
        // smaller means a[] become sorted then
        // we check that b[j] is smaller than all
        // other element in right side of b[j] if
        // b[] is not sorted then we linearly do
        // sorting means while adjacent element are
        // less than new b[j] we do sorting like
        // by changing position of element by
        // shifting one position toward left
         else if (a[i] > b[j]) {
            var t := a[i];
                a[i] := b[j];
                b[j] := t;
                i := i +1;
            if (j < b.Length - 1 && b[j + 1] < b[j]) {
             var temp := b[j];
             var tempj := j + 1;
                    while (tempj < b.Length && b[tempj] < temp)
                    decreases b.Length - tempj, if tempj < b.Length then temp - b[tempj] else 0 - 1
                     invariant   0 <= tempj < b.Length
                    {
                        b[tempj - 1] := b[tempj];
                        tempj := tempj+1;
                        if(tempj == b.Length){
                            break;
                        }
                    }
                    b[tempj - 1] := temp;
                }
         }
    }
}

But for some reason I still get "A postcondition might not hold on this return path."
on the following post conditions:
ensures Sorted(a[..]+b\[..])
ensures multiset(a[..]+b\[..]) == AB

I don't know what the problem could be, I would appreciate your help :)

A: If you need to sort each array in place, you can use an algorithm like Insertion Sort, which can sort an array in place with constant additional space.
Here is an implementation of Insertion Sort that sorts the given arrays a and b in place:
method SortInPlace(a: array<int>)
    modifies a
{
    var i := 1;
    while (i < a.Length)
        invariant 1 <= i <= a.Length
        decreases a.Length - i
    {
        var j := i;
        while (j > 0 && a[j - 1] > a[j])
            invariant 0 <= j < i
            decreases j
        {
            var temp := a[j];
            a[j] := a[j - 1];
            a[j - 1] := temp;
            j := j - 1;
        }
        i := i + 1;
    }
}

method Main() {
    var a := new int[3] [3,5,8];
    var b := new int[2] [4,7];

    print "Before sorting the following two arrays:\n";
    print a[..];
    print "\n";
    print b[..];

    SortInPlace(a);
    SortInPlace(b);

    print "\nAfter sorting in place:\n";
    print a[..];
    print "\n";
    print b[..];
}

In this implementation, the SortInPlace method takes an array a as input and sorts it in place using Insertion Sort. The Main method creates two arrays a and b, prints their contents, sorts them in place using SortInPlace, and then prints their contents again to verify that they are sorted.
Note that if you need to sort multiple arrays, you can simply call the SortInPlace method on each array.


text:
Q: Show activity on top of other activity I have an app that produces a notification when a process completes. Upon clicking on the notification, a popup is created. The popup is essentially an activity that isn't full screen.
My issue is that if this popup is created on top of an open application, when the screen orientation changes, the background application is killed.
I have attempted to circumvent this by forcing portrait mode (in the manifest and code) but that kills the background app as well when closing out of the popup.
Does anyone know how to accomplish this without killing the background app when the configuration changes?

A: Add these lines in your manifest
 <activity android:name=".Activity"
                 android:configChanges="keyboardHidden|orientation"
                  android:label="@string/app_name">

then implement in your java code this override method
public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);}

With this you are telling your application to do nothing when config changes occur (orientation changes let's say) I had the same problem. The whole activity was restarted, adding this, solved this issue. I hope it does work for you too.


text: Q: How to create JavaFX project in Netbeans? I click on New Project-->Java FX --> Manage Platforms -- > Add Platforms ---> Then I select java-8-openjdk-amd64 --> next--> then the platform sources is not filling out automatically then click on finish button after there is no table for JavaFX, I kinda confused what can be the problem what am I doing wrong?


text:
Q: Creating a vector of size n based on an inputted matrix So, I'm writing a function.  In order to begin the computation, I need to create a vector of 1s.  This is going to be multiplied by an inputted matrix A.
So if a matrix is 6x6, it becomes a vector of length 6, made up of 1s.  If it's 4x4, it becomes a vector of length 4 with all values at 1.
How do I make the vector the right size for any given matrix A?

A: Suppose you have the following matrix A:
julia> A=reshape(1:9,3,3)
3×3 reshape(::UnitRange{Int64}, 3, 3) with eltype Int64:
 1  4  7
 2  5  8
 3  6  9

Than you can do:
julia> A*ones(size(A,1))
3-element Vector{Float64}:
 12.0
 15.0
 18.0

(If you rather meant a horizontal vector of ones you could do ones(1,size(A,1))*A)
Note that the same effect can be simply achieved with the dims parameter of the sum function:
julia> sum(A,dims=2)
3×1 Matrix{Int64}:
 12
 15
 18

or if you want a Vector:
julia> vec(sum(A,dims=2))
3-element Vector{Int64}:
 12
 15
 18


text:
Q: R equivalent of excel exponential trendline (including equation) The attached picture shows the exponential curve fitting and the exponential equation for this set of data I have. However, I have 219 samples just like the picture that I would like to code in r & get the value for the exponential parameters (the power and the constant).
I have tried lm() and nls(). With lm(), I realized in doesn't give me the same exponential format as excel. By that I mean exponential function including e (refer to the equation in the attached image). With nls() the values seem so small to me & don't match what excel gives me.

A: Difficult to say without a reproducible example, but your code could be something like this:
library(ggplot2)

mod <- nls(y ~ a * exp(b * x), data = df, start = list(a = 8, b = 0.1))

a <- round(coef(mod)["a"], 2)
b <- round(coef(mod)["b"], 4)
Formula <- bquote(y == .(a) * e^{.(b)*x})

ggplot(df, aes(as.numeric(bins) * 10, y)) +
  geom_point(stat = "summary", fun = "mean", col = "orange",
             shape = 15, size = 5) +
  theme_minimal(base_size = 20) +
  geom_smooth(aes(group = 1), method = nls,
              formula = y ~ a * exp(b * x),
              method.args = list(start = list(a = 8, b = 0.1)),
              se = FALSE, color = "black", linetype = 2) +
  annotate(geom = "text", label = Formula, x = 20, y = 70, size = 6) +
  scale_x_continuous(breaks = 0:10 * 10, name = "x") +
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank(),
        axis.ticks = element_line())

Created on 2022-09-28 with reprex v2.0.2

Data used
We have no idea what your data frame or variables are called, but here is an example data frame with 219 values that approximately match your own data. This is the data used in the above example:
set.seed(1)

x <- sample(100, 219, TRUE)
y <- exp(rnorm(219, log(8.49) + 0.018 * x))
bins <- cut(x, breaks = 0:10 * 10)

df <- data.frame(x, y, bins)

A: Using the data in the picture, there is no discrepancy between Excel and R. First create the data and plot:
X <- 1:10
Y <- c(15, 10, 21, 28, 14, 12, 27, 12, 147, 83)
plot(X, Y, pch=16)

Now we can add a linear regression:
fit.linear <- lm(Y~X)
coef(fit.linear)
# (Intercept)           X
# -13.800000    9.218182
p.linear <- predict(fit.linear)
lines(X, p.linear)

Now the log transform equation:
fit.log <- lm(log(Y)~X)
coef(fit.log)
# (Intercept)           X
#   2.1317772   0.1887922
exp(coef(fit.log)[1])
    (Intercept)
       8.429835
p.log <- exp(predict(fit.log))
lines(X, p.log, col="blue")

Note that the slope value agrees with your Excel example. The intercept also agrees after we change the scale. Finally the nls() equation:
fit.nls <- nls(Y~a*exp(b*X), start=c(a=5, b=0.2))
coef(fit.nls)
#         a         b
# 3.4643870 0.3430626
p.nls <- predict(fit.nls)
lines(X, p.nls, col="red")

The nls regression does not match the log-transform regression because the two measure the residuals differently. The log-transform minimizes the log(Y) residuals whereas the nonlinear regression minimizes the Y residuals.


text:
Q: How can you use Javascript to duplicate a JSON object based on the value of a key in the object? Considering the following JSON object example as input, how would you use Javascript to duplicate each object based on the number of times found in the "Count" key/value pair?
Example Input:
[
  { "name":"David", "Count":2 },
  { "name":"John", "Count":3 },
]

Expected Output:
[
  { "name": "David" },
  { "name": "David" },
  { "name": "John" },
  { "name": "John" },
  { "name": "John" },
]

A: You can iterate on the Count property and push into another array.

var data = [{
    "name": "David",
    "Count": 2
  },
  {
    "name": "John",
    "Count": 3
  }
];

const output = [];

data.forEach(({ name, Count}) => {
  for(let i = 0; i < Count; i++) {
    output.push({ name });
  }
});

console.log(output);

A: You can do it easily with reduce() function:

let data = [
  { "name": "David", "Count": 2 },
  { "name": "John", "Count": 3 },
]

let new_data = data.reduce((sum, current) => {
  for (let index = 0; index < current.Count; index++) {
    sum.push({ name: current.name })
  };
  return sum
}, []);

console.log(new_data)

A: I would do something like that
const output = input.reduce((acc, cur) => [
    ...acc,
    ...Array.from({length: cur.Count}).map(() => ({ name: cur.name })
], [])


text:
Q: Running newer version of R from terminal when older version is invoked by default I'm trying to run R from iTerm on an OSX computer (OSX 10.11.6). When I enter R, it opens up an older version of R, from the path /Users/***/miniconda2/bin/R. I would like it to run, by default, an R version found at /usr/local/bin/R, without having to enter the full path every time. How would one go about changing the location of the default R?
Thanks for your help

A: This is likely due to the PATH variable preferring ~/miniconda2/bin before /usr/local/bin. I'm giving you a few options here to help understand why it is happening.
Let's assume your PATH looks like this:
/Users/me/bin:/Users/me/miniconda2/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
Modify PATH
You could  modify PATH to move /Users/me/miniconda2/bin after /usr/local/bin or remove it from PATH completely. The downside is that if you rely on other binaries in ~/miniconda2/bin they will no longer be found when executing them by name.
Move R out of the way
Another option would be to move ~/miniconda/bin/R out of the way, for example using
mv ~/miniconda/bin/R ~/miniconda/bin/R-miniconda

Afterwards R will be run from the next location in $PATH, but if you update miniconda2 it may return.
Link to R further up in the PATH (easiest/best)
Finally, you could make sure that there is an R executable in something that is further up the $PATH. This is probably the easiest and most effective option.
First, make sure you have a bin folder in your home directory. If this is not the case, create it using mkdir ~/bin and then restart the terminal. The restart should cause the code in ~/.profile to add that folder to your $PATH. You can verify by doing echo $PATH. If this is not the case, add the following line to your ~/.profile or ~/.bash_profile:
export PATH=$HOME/bin:$PATH

In the example at the top, the PATH already contains /Users/me/bin at the beginning of the line (highest priority).
Next, create a soft link to the R binary in the newly created folder:
ln -s /usr/local/bin/R ~/bin/R

You should now be able to execute R, which will prefer the softlink created, which will execute the one you like. If it does not work right away execute hash -r or restart the terminal.

A: Just in case you happen to be using RStudio Server (open source) or someone is looking for how to change the RStudio Server default version of R, here is what I found when trying to answer the same question:
Starting in RStudio Server 1.3 (the newest version is 1.4.1106, released February 22, 2021), a user's preferred version of R can be specified in the rstudio-prefs.json file in the global-level /etc/rstudio folder or in the user-level ~/.config/rstudio folder.
See https://blog.rstudio.com/2020/02/18/rstudio-1-3-preview-configuration/ and https://docs.rstudio.com/ide/server-pro/session-user-settings.html for user setting options in newer versions of RStudio Server.
See https://support.rstudio.com/hc/en-us/articles/200716783-RStudio-Release-History for RStudio release history and https://www.rstudio.com/products/rstudio/download-server/redhat-centos/ for Red Hat downloads of the newest version of RStudio Server.


text:
Q: How to make default owner for all files and directories in folder I want all new files created in one folder to have an owner called user1
How can I do that?

A: In FreeBSD exist suiddir(http://www.freebsd.org/cgi/man.cgi?query=mount&sektion=8). You may mount partitions with suiddir option and add 4000 permissions.
In linux GFS2 support suiddir. Also you may use cron or inotify, to change file owner.

A: You can have "all files belong to a group", by chmod g+s dir
If this doesn`t fit your needs, you have to deal with ACL and a default mask.

A: Hai
Linux always associates a file or directory with a user and a group. For example, assume I have a file named webmaster.txt in my home directory. If I run the command ls -l webmaster.txt, I get the following result:
-rw-rw-r- 1 root root 1024 Feb 21 15:10 example.txt
Here I think your
directory is /root/test
file is example.txt
user is user1 & group is user1
If you want to change permission, gust follow the instruction
chown -R user1.user1 /root/test/
Best wishes

A: Although all the documentation seems to say otherwise, the sticky bit seems to do it to an extent.
e.g.  to preserve the parent directory group.
chmod g+s [directory name]

Now any files or directories created within this directory inherit the parent group.
Not sure if this will be enough.  Usually it's the owner/group of the current user or process that sets these.