text:
Q: Android: Listview inside ScrollView I want to have a layout that can scroll and a listview inside it.
The listview will expand it's height base on how many items in it. Only the ScrollView outside is scrollable.
This is my code:
<ScrollView
            android:id="@+id/layout_box"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/layout_height_small"
                    android:gravity="center_vertical" >

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginLeft="@dimen/layout_margin_medium"
                        android:layout_marginTop="@dimen/layout_margin_medium"
                        android:gravity="center"
                        android:text="@string/list_regist_box_content"
                        android:textSize="@dimen/text_size_medium"
                        android:textStyle="bold" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:background="#ffffff" >

                    <ListView
                        android:id="@+id/list_registed_box"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content" >
                    </ListView>
                </RelativeLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical"
                    android:orientation="vertical" >

                    <TextView
                        android:id="@+id/btn_add_regist_box"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginTop="3dp"
                        android:gravity="center"
                        android:paddingBottom="@dimen/layout_margin_medium"
                        android:paddingTop="@dimen/layout_margin_medium"
                        android:text="@string/add_regist_box"
                        android:textColor="#0F88FF"
                        android:textSize="@dimen/text_size_medium" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginLeft="@dimen/layout_margin_medium"
                        android:layout_marginTop="@dimen/layout_margin_large"
                        android:gravity="center"
                        android:text="@string/amount"
                        android:textSize="@dimen/text_size_medium"
                        android:textStyle="bold" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/common_row_height"
                    android:background="@drawable/white_bg_grey_border_bottom"
                    android:gravity="center_vertical"
                    android:orientation="vertical" >

                    <TextView
                        android:id="@+id/list_regist_description"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:layout_marginLeft="@dimen/layout_margin_medium"
                        android:layout_marginRight="@dimen/layout_width_medium"
                        android:gravity="center_vertical"
                        android:text="@string/total"
                        android:textSize="@dimen/text_size_medium" />
                </LinearLayout>
</ScrollView>

But the listview is neither expanded nor scrollable.
Please help!

A: Don't put ListView inside ScrollView - first rule of android clud :)
Instead you can use simple LinearLayout and manage you ListView items inside it.
Or you can add Header/Footer Views to the ListView and using it without scrollview.

A: Actually, it is possible to put a ListView inside of an ScrollView. In some use cases (e.g. dynamic menus/submenus it's a reasonable solution). However, two caveats apply:

*

*The ListView won't have scroll. In general, nested scrolling is not possible in Android. There are some hacks to make it work (mostly by using requestDisallowInterceptTouchEvent()) but it's hard to make them work correctly in all cases.

*As a consequence, you must indicate the exact height the ListView needs to show all items (via its appropriate LayoutParams). Setting WRAP_CONTENT will not work.

A: I used below lines of code to scroll list item inside scroll view. It's working fine for my requirement, i hope it will help you.
Thanks,
Murali.M
public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            //pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }


text:
Q: nuget pack produces unwanted content folder out of nowhere I have a .NET Framework class library project that I'm turning into a nuget package and uploading to my own nuget server.
This is how the project looks:

Really simple, just a single .cs file with a few classes.
I'm compiling the code with Debug configuration and Any CPU platform.
Produced files are the following: Synteco.ScriptInterpreter.dll and a .pdb file with the same name
In the directory of my .csproj file I also have a .nuspec file, which looks like this:

I'm only copying the Synteco-Icon.png file in the images folder in the final .nupkg in order to set the icon for my nuget package.
Upon running nuget pack I'm getting the following output

As we can see, everything seems to be in order.
However, if we look into the produced .nupkg file, its contents are:

Somehow the folder content has been created. In the past this folder was not created at all.
I am able to push this nuget package to my server, but when I download it via Nuget Package Manager in other projects, everything from the content folder is being copied into the project that is trying to use that nuget package. For larger packages this becomes a real issue and unwanted files are being copied to projects.
What is the issue and how can I stop the content folder from being created?
I've tried running nuget pack [NAME_OF_MY_NUSPEC_FILE] but that would produce something even more strange. Take a look:

Am I doing something wrong?
P.S.
As far as I'm concerned, this is how a proper nuget package should look like. This is Newtonsoft.Json:

A: Problem was solved!
Silly me, I actually had some files with build action set to Content in my C# project for my nuget packages!
Upon removing all items with that build action the content folder is gone!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Install web sharing on OS X server without disk? On a new mac Mini which came with 10.6, I deselected the Web Sharing and a few other options on the initial setup, so now in System Preferences-->Sharing I have no option for Web Sharing, File Sharing, etc.
Now I want those items. I've since upgraded from 10.6 to 10.6.6 through the update manager, so now when I use my 10.6 to install over the network to the Mini, it says it can't proceed because a newer version of OS X is installed. How do I get the Web Sharing feature installed / enabled now? Do I need a 10.6.6 CD? I really don't have time to get a CD I just want the quickest path to getting this normal OS X feature installed...

A: I think you'll find that if you're talking about Mac OS X Server, you don't control file sharing or web sharing through the standard "System Preferences" application, but either through "Server Preferences" (for simpler setups), or "Server Admin" (for more advanced configurations).


text:
Q: Converting a SQLite file to .csv or .xml and vice-versa I am working on a Windows machine. Is there any application or other way to convert a whole SQLite database (.sqlite file) to .csv or .xml and vice-versa? i.e. I should be able to convert the converted .xml or .csv back to a .sqlite file.

A: you can export out of SQLite to multiple formats (eight different formats: "csv", "column", "html", "insert", "line", "list", "tabs", and "tcl"), here's how to export to list format
sqlite> .mode list
sqlite> .separator |
sqlite> .output test_file_1.txt
sqlite> select * from tbl1;
sqlite> .exit
$ cat test_file_1.txt
hello|10
goodbye|20
$

For importing back in
sqlite> .mode csv
sqlite> .import C:/work/somedata.csv tab1

There are 2 cases to consider: (1) Table "tab1" does not exist or (2) table "tab1" does exist.
for (1), the first row of the CSV file is interpreted to be column names and the actual data starts on the second row of the CSV file.
For (2), when the table exists, every row of the CSV file, including the 1st, is assumed to be actual content. If the CSV file contains an initial row of column labels, that row will be read as data and inserted into the table.
Make sure you try it on a test system first though ;)


text:
Q: display custom product options in product list Is it possible to display custom product options into the list.phtml?
It is a text field, i'm using magento 1.6.1
Greetz,
Fluxxi

A: It's not programming feature. Goto Admin -> Catalog -> Attributes -> Manage Attributes then select the attribute that you want to show product page. Then change "Visible on Product View Page on Front-end" properties to "Yes".


text:
Q: Is there a way watch multiple issues and reviews in a single place? I am wondering if anyone builded a tool that can watch things like:

*

*github bugs (multiple projects)

*gerrit reviews (multiple gerrit instances, I already have patches in 3)

*jira bugs (multiple instances)

Clearly such a tool would have to be able to talk with different API for github, gerrit and jira.
Few notes:
* Email doesn't really work (just ignore it)
* A hosted service would not work because some of these are on intranet
* A browser extension may work

A: If you are a GitHub organizations user, you can have all the issues and pull request and the projects for organizations tab. See the link: https://github.com/blog/2272-introducing-projects-for-organizations
You must manually add the issues and PRs to the projects. AFAIK there is no tool to do it right now. You can still track all your PR's and issues at your git dashboard.


text:
Q: Backup and Restore realm.io database I need to backup my default realm.io database and restore it from Dropbox. I'm using the Dropbox-iOS-SDK to upload and download it. When I tried to replace the current database file (Ex. default.realm) with the backup, the RLMRealm object was on the cache and I'm not able to clear that cache so I can't create a new instance of the Database.
Can I reload the RLMRealm object?
Here is the code:
    func reloadDB(fromPath: String) {
        let defaultParentPath = RLMRealm.defaultRealmPath().stringByDeletingLastPathComponent
        let dbPath = defaultParentPath.stringByAppendingPathComponent("db.realm")
        let dbLockPath = defaultParentPath.stringByAppendingPathComponent("db.realm.lock")

        NSFileManager.defaultManager().removeItemAtPath(dbPath, error: nil)
        NSFileManager.defaultManager().removeItemAtPath(dbLockPath, error: nil)

        NSFileManager.defaultManager().copyItemAtPath(fromPath, toPath: dbPath, error: nil)

        self.db = RLMRealm(path: dbPath, readOnly: false, error: nil)

        NSFileManager.defaultManager().removeItemAtPath(fromPath, error: nil)
    }

What is the best way to backup a Realm.io database?

A: Backing up and restoring a Realm file from dropbox should work just fine, since the database is just a file. However, you must make sure you don't have any references to the existing realm before deleting it.


text:
Q: Has GTS been shutdown for 4th and 5th generation? I've been trying to use GTS on my Pokemon Diamond, but it never works anymore. It says that the software isn't compatible or something like that and some of my friends have been telling me that GTS has been removed from 4th and 5th gen.
So is it removed or am I doing something wrong?

A: Yep, all WiFi things (so inluding GTS) from 4th and 5th gen are removed. Official announcement by Nintendo said:

As of May 20, 2014, certain online functionality offered through Nintendo Wi-Fi Connection is no longer accessible. The discontinued services include online play, matchmaking and leaderboards for many Wii, Nintendo DS and Nintendo DSi games. For a comprehensive list of games and services that are affected, please check http://support.nintendo.com/servicesupdate. Users can still play the games in offline mode, which continues to offer a rich game-play experience.

In the list below with affected games there are the following Pokemon games:

*

*Pokémon Black Version

*Pokémon Black Version 2

*Pokémon Diamond Version

*Pokémon HeartGold Version

*Pokémon Mystery Dungeon: Explorers of Darkness

*Pokémon Mystery Dungeon: Explorers of Sky

*Pokémon Mystery Dungeon: Explorers of Time

*Pokémon Pearl Version

*Pokémon Platinum Version

*Pokémon Ranger: Guardian Signs

*Pokémon Ranger: Shadows of Almia

*Pokémon SoulSilver Version

*Pokémon White Version

*Pokémon White Version 2

A: Actually, following an exciting change (I have no idea how this happened) GTS appears to be back for (all?) previous games. Just posted through SoulSilver a global trade offering a Beedrill (name: HelloThere holding a message for anyone still out there) for any old Rattata just to see if anyone else can see it. Was able to access it using the following video:

Hope to see some more folks soon.


text:
Q: Proving that in a homeomorphism, the number of components are same and the components are homeomorphic Our professor of Topology gave the following theorem to prove:

Let $f: X \rightarrow Y$ be continuous. Then the image of each component of $X$ must lie in a component of $Y$.
Further if $h: X \rightarrow Y$ is a homeomorphism then $h$ induces a $1-1$ correspondence between the components of $X$ and those of $Y$, corresponding ones being homeomorphic.

He gave the proof as follows:
Proof::
Let $C_x$ be a component of $X$ containing $x \in X$. Then $C_{x}$ is connected and so $f\left(C_{x}\right)$ is a connected set containing $f(x)=y \in Y$. So $f\left(C_{x}\right) \subset C_{y}$ as $C_{y}$ is a connected component of $y \in Y$ which is a maximal connected set containing $y$.
Next, let $h: X \rightarrow Y$ be a homeomorphism. Let $C_{x}$ and $C_{y}$ be component of $x \in X$ and $y \in Y$ resp.
As $h$ is bijective for $y \in Y$ ,$ \exists x \in X$ s.t. $h(x)=y$
Now $h\left(C_{x}\right) \subset C_{y}$
and $\quad{h}^{-1}\left(C_{y}\right) \subset C_{x}$ so that $h\left(C_{x}\right) =C_{y}$
Thew $\left.h\right|_{C_{x}}: C_{x} \rightarrow C_{y}$ is a homeomorphism
and $\quad C_{x} \rightarrow C_{h(x)}$ gives $1-1$ correspondence between the components of $X$ and those of $Y$.
This is the end of the proof.
But I was wondering whether for showing the second part i.e. to show the 1-1 correspondence between the components of X and Y, it is sufficient to show that under a homeomorphism, component of X is mapped to a component of Y?
Don't I need to show a bijection between the set of all components of X and set of all components of Y?
And what should I do for the homeomorphic part i.e. components are homeomorphic?
My attempt:
I tried by defining and map
$\phi: S_X \rightarrow S_Y$ by $\phi(C_x)=h(C_x)$, where,
$S_X$ and $S_Y$  are the set of all components of X and Y respectively.
Then I showed that $h(C_x)$ is indeed a component of Y by showing $h(C_x)=C_y$, where $y=h(x)$.
I am stuck at showing one one and onto.
Thanks for any help!


text:
Q: Irreducibility of a cubic in $\mathbb{Q}[X]$
Problem
Show that $$X^3-2008X^2+2010X-2009$$ is irreducible in $\mathbb{Q}[X]$.

Progress
I considered applying Eisenstein's Theorem, but there are no primes $p$ such that $p|2008$, $p|2009$ and $p|2010$. (This is quite clear as $\nexists p$ prime such that p divides consecutive integers for any choice of p.)
I think this may require an application of Gauss's Lemma, but I'm yet to successfully show it. Any help would be appreciated.
Regards.

A: Since the polynomial is a cubic, if it can be nontrivially factored, then one of the factors must be linear. So it suffices to show that the polynomial does not have rational roots. From the rational root theorem, any rational root must also be an integer. Moreover, it must be a divisor of $2009$, i.e., one of $\{ 1,  7,  41, 49, 287, 2009 \}$. [We can rule out the negative numbers because the polynomial is strictly negative for $X < 0$.] Therefore, to prove that the polynomial is irreducible, it suffices to check none of these $6$ numbers is a root of the polynomial.

A: HINT $\ $ By Gauss's lemma if $\rm\:f(x)\:$ splits over $\rm\:\mathbb Q\:$ then it splits over $\rm\:\mathbb Z\:,\:$ hence it splits over $\rm\:\mathbb Z/3\:,\:$ contra $\rm\ f(x)\ \equiv\ x^3-x^2+1\ $ has no roots $\rm\ mod\ 3\:.$
REMARK $\ $ Gauss's Lemma is a bit overkill here. But it's trivial to prove the simple monic case:
LEMMA $\rm\ \ f\ g\in \mathbb Z[x]\ \Rightarrow\ g \in \mathbb Z[x]\ \ \ if\ \ \ g\in \mathbb Q[x],\ \ monic\ f\in \mathbb Z[x]$
Proof $\ $ Write $\rm\ g = c\ x^n + g'\:,\  \ deg\ g' < deg\ g = n\:.\ $ Since $\rm\:f\:g \in \mathbb Z[x]\:$ its lead coeff $\rm\:c\in\mathbb Z\:.\:$ Thus $\rm\:f\ g' =\: f\ g - c\ x^n\:f\: \in\: \mathbb Z[x]\:,\:$ so $\rm\:g'\in \mathbb Z[x]\:$ by induction on deg $\rm\:g\:,\:$ so $\rm\ g = c\ x^n + g'\in \mathbb Z[x]\:.\:  $ QED


text:
Q: Cloudflare minify html and gzip Hi I have a Drupal 6 site with Cloudflare as cdn. I also have gzip enabled via apache server setting.
I want to know if I can enable gzip along with Cloudflare html minify? Thanks

A: Cloudflare dynamically GZips content on supported browsers, and presents this to the end user. This works regardless of whether HTML minify is turned on or off.
Related:

*

*What will Cloudflare gzip?

*Does Cloudflare gzip resources?


text:
Q: CSS Animation Directional Issue We are trying to animate a div as follows:
1- Stretch from 0 to 100% (from left to right)
2- Then shrink from 100% to 0 (also from left to right)
3- then repeat.
We have the following div:

div {
  position: absolute;
  height: 2px;
  background: #c60000;
  left: 0;
  top: 0;
  color: #789;
  width: 0;
  animation-duration: 5s;
  animation-name: progress;
  animation-iteration-count: infinite;
}

@keyframes progress {
  50% {
    // transform-origin: right top;
    width: 100%;
  }
}

But no matter what we do using transform-origin and floats, positioning etc, the second part shrinks from right to left. i.e. the left side is always the anchor, whereas we want the right side to be the anchor when shrinking is taking place.
Would appreciate any help.

A:

div {
  position: absolute;
  height: 2px;
  background: #c60000;
  top: 0;
  color: #789;
  animation-duration: 5s;
  animation-name: progress;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}

@keyframes progress {
  0% {
    left: 0;
    width: 0;
  }
  50% {
    right: 0;
    width: 100%;
  }
  100% {
    right: 0;
    width: 0;
  }
}


text:
Q: Variation of the Chinese Postman Problem_ In order to be well prepared for my spring quarter exams right now I'm studying and experimenting with graph problems.
I already got familiar to typical problems like the "Traveling Salesman" but when I took a deeper look into the "chinese postman problem" and its variations I immediately felt like an important aspect of the problem was missing: The aspect of having a limited capacity, thus the need to return to the office station after a certain number n of letters is successfully delivered (in order to get new ones). What about finding the shortest path then?
I was very intrigued with the CPP because of its relevancy and easy applicability for real  life but I think adding this aspect would make it even more real life applicable.
I would be thankful for any help on how to find the shortest path in an undirected graph that visits every edge at least once (CPP) the the constraint of having to return to the starting point (post station) after a certain number of letters is delivered.

EDIT (description of originial CPP):
"The chinese postman problem or route inspection problem is to find a shortest closed path or circuit that visits every edge of a (connected) undirected graph. When the graph has an
Eulerian circuit (a closed walk that covers every edge once), that circuit is an optimal solution.
If the graph is not Eulerian, it must contain vertices of odd degree. By the handshaking lemma, there must be an even number of these vertices. To solve the postman problem we first find a smallest T-join. We make the graph Eulerian by doubling of the T-join. The solution to the postman problem in the original graph is obtained by finding an Eulerian circuit for the new graph."
Src: wikipedia.org

A: Your variant is NP-hard by a reduction from, e.g., the 3-partition problem where all values are strictly between B/4 and B/2. It might be "solved" using some of the same methods as capacitated vehicle routing. You have to understand, though, that CPP is less a real problem than an excuse to study T-joins.


text:
Q: Get dynamic substring in c# I have a string like this:

D:\ClickSitePlayer\ClickSitePlayer\ClickSitePlayer\bin\Debug\sad_3.mp4

At the end of the string there is a file name (video name). the file name is not fixed and will change each time.
1 - How can i get file name (sad_3.mp4) in this string?
2 - After getting file name, how can i get file id? (file id comes after '_' and is 3 here)

A: *

*Path.GetFileName (MyPath)

*You want to probably use Regex to get a good match and extract the number.
Stackoverflow already has numerous similar questions and very good answers.
I encourage youe to expand ur search before asking.


text:
Q: Factory method for Fragment: Setting the class variables vs putting the Bundle as arguments in the Fragment I have been reading about the use of a factory method to get hold of an object of a custom Fragment class. Let say I have a custom Fragment class as follows:
public class CustomFragment extends Fragment {

    ..........

    public static CustomFragment getInstance(String message) {
        CustomFragment fragment = new CustomFragment();
        Bundle bundle = new Bundle();
        bundle.putString(MESSAGE, message);
        fragment.setArguments(bundle);
        return fragment;
    }
   ..............
}

What if I have a class variable named MESSAGE and I set its value using the setter on the instantiated object like:
public class CustomFragment extends Fragment {

    ..........
    private String MESSAGE;

    private void setMessage(String msg) {
        this.MESSAGE = msg;
    }

    public static CustomFragment getInstance(String message) {
        CustomFragment fragment = new CustomFragment();
        fragment.setMessage(message);
        return fragment;
    }
   ..............
}

Which of the above two is preferred and why?

A:
Which of the above two is preferred

The first one.

why?

Users will rotate the screen or otherwise trigger your app to undergo a configuration change. Your foreground activity, and its fragments, are destroyed and recreated by default. In your first scenario, the message will be part of the saved instance state Bundle and will not be lost. In your second scenario, the message will be lost, unless you add extra code somewhere to specifically hold onto it.


text:
Q: Why does attempted file redirection break this code? This is basically supposed to execute linux shell commands entered by the user and call execvp
For my test function, why is it that when ever a command is entered like '
   ls -l > sample.txt
Not only does the command not execute but the file is not created either.
However if I run the command without the redirection it works fine.
Also after a failed run with a file name attached the shell is completely broken and even a normal command that worked previously will not work.
It also seems as if ls -l will sometimes break the next input command.Then it becomes unable to find ls or any other command.
Edit: After any failed command it will unable to fin any previously working command.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <vector>
#include <algorithm>
#include <limits>

void testFunction(int num, char **argv, char **fname)
{
   std::cout << "vvv testFunctionBegin vvv" << std::endl;
   int status;
   int fd;

   if (fork() != 0)
   {
      std::cout << "fork() != 0" << std::endl;
      waitpid(-1, &status, 0);
   }
   else
   {
      std::cout << "fork() == 0" << std::endl;
      /*
      if (isalnum(*fname[0]) || ispunct(*fname[0]))
      {
          std::cout << "File has "<< *fname[0] << std::endl;
          fd = open(fname[0], O_WRONLY, O_APPEND, O_CREAT);
          std::cout << "fd = " << fd << std::endl;
          std::cout << "fname = " << fname[1] << std::endl;
          perror("open");
          dup2(fd, 1);
          close(fd);

      }
      */
      std::cout << "argv[0] = " << *argv[0] << std::endl;
      execvp(argv[0], argv);
   }

}

std::vector<std::string> processString(std::string userInput)
{
   int j = 0;
   std::vector<std::string> subStrs;
   for (int i = 0; i < userInput.size(); i++)
   {
      bool sameSeq = false;
      if (isalnum(userInput[i]) || ispunct(userInput[i]))
      {
         subStrs.resize(subStrs.size() + 1);
         while (isalnum(userInput[i]) || ispunct(userInput[i]))
         {
            subStrs[j].push_back(userInput[i]);
            sameSeq = true;
            //std::cout << "userInput[" << i << "] = " << userInput[i]
            //          << " --> " << "subStrs[" << j << "] = "
            //          <<  subStrs[j] << std::endl;
            i++;
         }
         if (sameSeq)
         {
            subStrs[j].push_back('\0');
            j++;
         }
      }

   }
   return subStrs;
}

int main(int argc, char **argv)
{
   std::string userInput;
   std::string readySym = "$ ";
   std::vector<std::string> subStrs(1, "");
   std::vector<char*> cmdFlgs;
   std::vector<char*> fileName;

   while (true)
   {
      std::cout << readySym;
      getline(std::cin, userInput, '\n');

      int j = 0;
      bool fileDirect = false;

      if(!userInput.empty())
      {
         // Put user input into vecotr of strings
         subStrs = processString(userInput);
         int i = 0;
         while ((i < subStrs.size()) && (subStrs[i] != ">") )
         {
            cmdFlgs.push_back(const_cast<char*>(subStrs[i].c_str()));
            i++;
         }

         /*for (int i = 0; i < cmdFlgs.size(); i++)
         {
            std::cout << "cmdFlgs[" << i << "] = " << cmdFlgs[i] << std::endl;
            std::cout << "It is: " << isspace(*cmdFlgs[i]) << std::endl;
         }
         */
         int j = 0;
         if ( ++i < subStrs.size())
         {
            fileName.push_back(const_cast<char*>(subStrs[i].c_str()));
            std::cout << "fileName[" << i << "] = " << fileName[i] << std::endl;
         }

         testFunction(cmdFlgs.size(), cmdFlgs.data(), fileName.data());
         fileName.clear();
         cmdFlgs.clear();
      }

   subStrs.clear();
   subStrs.resize(1);
   }

return 0;
}

A: Your expectation of what execvp and how the shell works is wrong. execvp will execute the program given and pass the remainder of the commands line parameters to the program as arguments.  When you run it on the command line the shell does some work to understand that '>' symbol is not to be passed to the program being called, and is to be interpreted as a redirect.

A: If an output redirection operator is not entered, the fileName array will be empty.
     if ( ++i < subStrs.size())
     {
        fileName.push_back(const_cast<char*>(subStrs[i].c_str()));

If this if branch is not taken, fileName will remain a completely empty vector. P.S.: this const_cast made my eyes bleed.
testFunction(cmdFlgs.size(), cmdFlgs.data(), fileName.data());

fileName.data() will be a null pointer in this case.
Your question was the fact that with the commented portion in place, your code does not work.
if (isalnum(*fname[0]) || ispunct(*fname[0]))

Since the fname parameter is a null pointer, you will have a null pointer dereference here.
Additionally, this code is suffering from a severe case of C-itis. This is a condition that mostly afflicts C++ code that thinks it's not C++ code, but rather C code.
For example:
subStrs[j].push_back('\0');

This is completely unnecessary. std::string automatically takes care of details like always appending a \0 at the end of the string for you. This is no longer C, this is C++. And, in C++, we don't deal with silliness like appending \0s to strings. That's what std::string is for.
     if (sameSeq)
     {
        subStrs[j].push_back('\0');
        j++;
     }

Same thing. None of this is needed. Additionally, here's a homework assignment for you. Try to figure out why sameSeq will always be true here. No exceptions (free clue, look at the immediately preceding if and while conditions). Just more unneeded code to remove, here.
PS. All of the above was determined quickly with a help of a debugger, namely gdb, that is the same gdb that's on your linux box. That's another thing you should look into: learning how to use gdb.


text:
Q: I have tried this regex expression: (0\9)[0-9]{8\9} which doesn't meet the validation requirement that I want I have tried the regex expression of the following condition for both HTML form validation as well as server side validation in Laravel but the expression that I have tried (i.e (0\9)[0-9]{8\9}) couldn't meet the requirement for the validation:
The number should start with either 0 or 9 and the number should be exactly 9 or 10 digits.
Note: The number should be in the form like 9849384748 (beginning with 9 and exactly of 10 digits) or 016563434(beginning with 0 and exactly of 9 digits).

A: You can use following regular expression:
^(0\d{8}|9\d{9})$

Description:

*

*^ asserts position at start of line while $ at end of line.

*\d matches a digit.

*{8} and {9} matches eight and nine times respectively.


text:
Q: Why does my background image disappear sometimes? I'm really stressed about this, it's all of a sudden started to happen. It's a WordPress site, so excuse the logo of the site not working and so on... this is just one page saved as HTML.
Link: http://bit.ly/1n7maKZ
For some reason, if I leave a page open for a certain amount of time, or click on a link and then go back to it, the backup background color will kick in suddenly and the background image will disappear! I have no idea why. I'm using Chrome.
My code in the header looks like this:

Here is the CSS:
#background {
    background: url("[WORKING LINK HERE]") no-repeat center center fixed #e1e1e1;
    background-size: cover;
}

And...
.bg , #supersized {
    top:0;
    width:100%;
    height:100%;
    position:fixed;
    z-index:-20;
}

Is there a way to prevent this? The annoying thing is, you probably won't get to see the issue because I have no idea what triggers it to suddenly drop the background image and resort to the alternate color. If I have a page open long enough in Chrome at least, it does it. Thank you for any help!

A: Your "WORKING LINK HERE" is not working at all. I tried to load the background.png file, but it doesn't exist and, after a while, the server gives you back the website's homepage.
Probably you sometime see the background because it is cached in your browser.
Fix the path/filename of you background image in your css and it will work.


text:
Q: i have the kml and csv file and want to load file in the React Native I am converting the kml file into the json format and then i am loading in to the google Map but its not working yet. is there any other way to load the file?

A: Have you tried react-native-geojson library? I able to load my local geojson and display it.
For now, I don't see any support for KML with react native maps. issue #967


text:
Q: Haskell Persistent insert rows if not already in database I'm trying to use Yesod and persistent to create a website. I'm a bit confused about how to use the persistent API.
Here's two of my tables
Feed
    url Text
    UniqueFeed url

Subscription
    feed FeedId
    title Text
    UniqueSubscription feed

I'm trying to create a Feed if a feed with that URL does not exists, and then add a subscription to that feed, if a subscription does not already exist.
postFeedR :: Handler RepHtml
postFeedR = do
    url <- runInputPost $ ireq urlField "url"
    title <- runInputPost $ ireq textField "title"

    runDB $ do
        feedId <- insertFeed $ UniqueFeed url
        subscriptionId <- insertSubscription feedId title
        return

    defaultLayout [whamlet| <p>done|]

insertFeed url = do
    f <- insertBy $ UniqueFeed url
    case f of
        Left (Entity uid _) -> uid
        Right (Key uid) -> do
            (Key uid) <- insert $ Feed url
            return uid

insertSubscription feedId title = do
    s <- insertBy $ UniqueSubscription feedId
    case s of
        Left (Entity uid _) -> uid
        Right (Key uid) -> do
            (Key uid) <- insert $ Subscription feedId title
            return uid

I get the errors below. I don't understand why ghc thinks that the return value of insertFeed and insertSubscription should be UniqueFeed and UniqueSubscription. I would like those functions to return the keys of the newly created records.
Also, it seems like I'm throwing away the Key that I get back in each of the Right clauses of the case. Why does persistent return those keys. In the case where the UniqueSubscription is not in the database, persistent does not have enough information to create a new Subscription record, because it is missing the title, which is not on the UniqueSubscription.
If someone could give me some pointers on how to use the persistent API, I would really appreciate it.
Handler/Home.hs:62:9:
    Kind incompatibility when matching types:
      a0 :: *
      GHandler App App :: * -> *
    Expected type: (a0 -> t0)
                   -> (t0 -> a0 -> m0 a0) -> YesodDB App App (m0 a0)
      Actual type: (a0 -> t0) -> (t0 -> a0 -> m0 a0) -> a0 -> m0 a0
    In a stmt of a 'do' block: feedId <- insertFeed $ UniqueFeed url
    In the second argument of `($)', namely
      `do { feedId <- insertFeed $ UniqueFeed url;
            subscriptionId <- insertSubscription feedId title;
            return }'

Handler/Home.hs:62:9:
    Couldn't match type `YesodPersistBackend App' with `(->)'
    Expected type: (a0 -> t0)
                   -> (t0 -> a0 -> m0 a0) -> YesodDB App App (m0 a0)
      Actual type: (a0 -> t0) -> (t0 -> a0 -> m0 a0) -> a0 -> m0 a0
    In a stmt of a 'do' block: feedId <- insertFeed $ UniqueFeed url
    In the second argument of `($)', namely
      `do { feedId <- insertFeed $ UniqueFeed url;
            subscriptionId <- insertSubscription feedId title;
            return }'

Handler/Home.hs:74:20:
    Couldn't match expected type `Unique Feed'
                with actual type `Database.Persist.Store.PersistValue'
    In the first argument of `return', namely `uid'
    In a stmt of a 'do' block: return uid
    In the expression:
      do { (Key uid) <- insert $ Feed url;
           return uid }

Handler/Home.hs:83:20:
    Couldn't match expected type `Unique Subscription'
                with actual type `Database.Persist.Store.PersistValue'
    In the first argument of `return', namely `uid'
    In a stmt of a 'do' block: return uid
    In the expression:
      do { (Key uid) <- insert $ Subscription feedId title;
           return uid }

A: insertBy doesn't take a Unique constraint as parameter, getBy is more appropriate.
But insertUnique is a short possibility with Maybe result.
postFeedR :: Handler RepHtml
postFeedR = do
    url <- runInputPost $ ireq urlField "url"
    title <- runInputPost $ ireq textField "title"

    runDB $ do
        feedId <- insertFeed url
        _mbSubscriptionId <- insertUnique $ Subscription feedId title
        return ()

    defaultLayout ...

insertFeed url = do
    f <- insertBy $ Feed url
    case f of
        Left (Entity uid _) -> return uid
        Right uid -> return uid


text:
Q: Vi group independent commands in normal mode I want to execute a set of independent(by this I mean which don't take each other as arguments) commands n times in vi (vim to be more precise).
How can I group the commands?
An example would be (I know it's a stupid command but I just want to illustrate my point):
80jl
How can I make vim execute both j and l commands 80 times?
Is there a composition operator?

A: You can record those commands using q and execute them using @, so:
qajlq

saves in register a the two movements, and:
80@a

execute 80 times the content of register a.


text:
Q: bytearray.fromhex doesn't convert when no letters in number I am trying to convert a number (of arbitrary size, possibly very long) to its corresponding string of bytes. For example, inputting the number 1094795585 (base 10), which is 0x41414141 (base 16), should return "\x41\x41\x41\x41".
Currently I have:
def number_to_bytes(number):
    hex_string = hex(number).rstrip("L").lstrip("0x")
    return bytearray.fromhex(hex_string.decode("hex"))

When I input the number 1094795585 (0x41414141), I get the error "odd-length string".
When I input the number 1094795584 (0x41414140), I get the error "non-hexadecimal number found in fromhex() arg at position 2".
This makes me think that Python is adding some sort of invisible character in the hex_string. Is this the case?
How can I achieve the correct conversion?

A: You should not decode the string from hex; drop the .decode('hex') call. You need to pass in actual hex digits, not a bytestring with codepoints based on those digits.
Compare the difference:
>>> hex(1094795584)[2:]
'41414140'
>>> hex(1094795584)[2:].decode('hex')
'AAA@'

By decoding you are already producing the very bytes you wanted bytesarray.fromhex() to produce; you could just use bytesarray(hex_string.decode('hex')) in that case.
You can use format() to produce a hex format for your number that doesn't include the 0x prefix, nor a L postfix for long integers:
import math

def number_to_bytes(number):
    byte_count = int(math.log(number, 256)) + 1
    hex_string = '{:0{}x}'.format(number, byte_count * 2)
    return bytearray.fromhex(hex_string)

Demo:
>>> import math
>>> def number_to_bytes(number):
...     nibble_count = int(math.log(number, 256)) + 1
...     hex_string = '{:0{}x}'.format(number, nibble_count * 2)
...     return bytearray.fromhex(hex_string)
...
>>> number_to_bytes(1094795585)
bytearray(b'AAAA')
>>> number_to_bytes(1094795584)
bytearray(b'AAA@')

A: This should work:
import math
def number_to_bytes(num):
    hex_str = format(num, 'x')
    hex_len = (int(math.log2(num)/8)+1)*2
    return bytearray.fromhex(hex_str.zfill(hex_len))


text:
Q: SQL - Create number of categories based on pre-defined number of splits I am using BigQuery, and trying to assign categorical values to each of my records, based on the number of 'splits' assigned to it.
The table has a cumulative count of records, grouped at the STR level - i.e., if there are 4 SKUs at 2 STR, the SKUs will be labeled 1,2,3,4. Each STR is assigned a SPLIT value, so if the STR has a SPLIT value of 2, I want it to split its SKUs into 2 categories. I want to create another column that would assign SKUs labeled 1-2 as '1', and SKUs labeled 3-4 as '2'. (The actual data is on a much larger scale, but thought this would be easier.)
+-----+------+---------------+--------+
| STR | SKU  | SKU_ROW_COUNT | SPLITS |
+-----+------+---------------+--------+
|   1 | 1230 |             1 |      3 |
|   1 | 1231 |             2 |      3 |
|   1 | 1232 |             3 |      3 |
|   1 | 1233 |             4 |      3 |
|   1 | 1234 |             5 |      3 |
|   1 | 1235 |             6 |      3 |
|   2 | 1310 |             1 |      2 |
|   2 | 1311 |             2 |      2 |
|   2 | 1312 |             3 |      2 |
|   2 | 1313 |             4 |      2 |
|   3 | 2345 |             1 |      1 |
|   3 | 2346 |             2 |      1 |
|   3 | 2347 |             3 |      1 |
+-----+------+---------------+--------+

The SPLITS column is dynamic, ranging from 1 to 3. The number of SKUs in each category should be relatively equal, but that's not a priority as much as just the number of groups that are created. Ideally, the final table with the new column (HOST_NUMBER) would look something like this:
+-----+------+---------------+--------+-------------+
| STR | SKU  | SKU_ROW_COUNT | SPLITS | HOST_NUMBER |
+-----+------+---------------+--------+-------------+
|   1 | 1230 |             1 |      3 |           1 |
|   1 | 1231 |             2 |      3 |           1 |
|   1 | 1232 |             3 |      3 |           2 |
|   1 | 1233 |             4 |      3 |           2 |
|   1 | 1234 |             5 |      3 |           3 |
|   1 | 1235 |             6 |      3 |           3 |
|   2 | 1310 |             1 |      2 |           1 |
|   2 | 1311 |             2 |      2 |           1 |
|   2 | 1312 |             3 |      2 |           2 |
|   2 | 1313 |             4 |      2 |           2 |
|   3 | 2345 |             1 |      1 |           1 |
|   3 | 2346 |             2 |      1 |           1 |
|   3 | 2347 |             3 |      1 |           1 |
+-----+------+---------------+--------+-------------+

A: You can use window functions and arithmetics:
select
    t.*,
    1 + floor((sku_row_count - 1) * splits / count(*) over(partition by str)) host_number
from mytable t
order by sku

Actually, ntile() seems to do exactly what you want - and you don't even need the sku_row_count column (which basically mimics row_number() anyway):
select
    t.*,
    ntile(splits) over(partition by str order by sku) host_number
from mytable t
order by sku

A: If the ordering of the values in the groups doesn't matter, just use modulo arithmetic:
select t.*, (SKU_ROW_COUNT % SPLITS) as split_group
from t

A: Below is for BigQuery Standard SQL
#standardSQL
SELECT *, 1 + MOD(SKU_ROW_COUNT, SPLITS) AS HOST_NUMBER
FROM `project.dataset.table`


text:
Q: What can I do to ensure fields longer than column width go to the BAD File? When creating Oracle external tables, how should I phrase the reject rows clause to ensure that any field which exceeds its column width rejects and goes in the BADFILE?
This is my current design and I don't want records greater than 20 characters. I do want them to go BADFILE instead. Yet, they still appear when I select * from foobar
DROP TABLE FOOBAR CASCADE CONSTRAINTS;

CREATE TABLE FOOBAR
(
 FOO_MAX20  VARCHAR2(20 CHAR)
 )
ORGANIZATION EXTERNAL
 (  TYPE ORACLE_LOADER
 DEFAULT DIRECTORY FOOBAR
 ACCESS PARAMETERS
   ( RECORDS DELIMITED BY NEWLINE
     BADFILE     'foobar_bad_rec.txt'
     DISCARDFILE 'foobar_discard_rec.txt'
     LOGFILE     'foobar_logfile.txt'
     FIELDS
     MISSING FIELD VALUES ARE NULL
     REJECT ROWS WITH ALL NULL FIELDS
            (
            FOO_MAX20 POSITION(1:20)
            )
      )
 LOCATION (foobar:'foobar.txt') )
REJECT LIMIT UNLIMITED
PARALLEL ( DEGREE DEFAULT INSTANCES DEFAULT )
NOMONITORING;

Here is my external file foobar.txt
1234567
1234567890123456
126464843750476074218751012345678901234567890
7135009765625
048669433593
7
527

A: You can't do this with the reject rows clause, as it only accepts one form.
You have a variable-length (delimited) record, but a fixed-length field. Everything after the last position you specify, which is 20 in this case, is seen as filler that you want to ignore. That isn't an error condition; you might have rubbish at the end that isn't relevant to your table. There is nothing that says chars 21-45 in your third record shouldn't be there - just that you aren't interested in them.
It would be nice if you could discard them with the load when clause, but you don't seem to be able to compare , say, (21:21) to null or an empty string - the former isn't recognised and the latter causes an internal error, which isn't good.
You can make the longer records be sent to the bad file by forcing an SQL error when it tries to put a longer parsed value from the file into the field, by changing:
FOO_MAX20 POSITION(1:20)

to
FOO_MAX20 POSITION(1:21)

Values that are up to 20 characters are still loaded:
select * from foobar;

FOO_MAX20
--------------------
1234567
1234567890123456
7135009765625
048669433593
7
527

 6 rows selected

but for anything longer than 20 characters it'll try to put 21 chars in to the database's 20-char field, which gets this in the log:
error processing column FOO_MAX20 in row 3 for datafile /path/to/dir/foobar.txt
ORA-12899: value too large for column FOO_MAX20 (actual: 21, maximum: 20)

And the bad file gets that record:
126464843750476074218751012345678901234567890

A: Have a CHECK CONSTRAINT on the column to not allow any value exceeding the `LENGTH'.


text:
Q: Non-interactive "git clean -fdx" I'm building a thing that processes incoming file packages, but I have the rather serious problem that I can't sanitize the incoming data until it's in a position to break the processing, and it breaks it such a way that simply restarting the process doesn't fix it.
My current best solution is to git clean -fdx and git checkout . the project directory the process uses, which works like a charm, except that sometimes git clean asks for user input ("cannot unlink file. Retry?"), which causes a problem for automation.
Is there a way to put Git into a non-interactive mode? I need to do this from inside Ruby on a Windows machine.

A: For Windows, this is what worked for me (sets the GIT_ASK_YESNO environment variable to false, stopping git from asking yes-no questions):
set GIT_ASK_YESNO=false

Then when I get those same messages as warnings but it continues as if I said no.
So git clean -fdx works for me as expected without blocking.

A: yes no | git clean -fdx

yes no outputs no forever and piping that into git clean causes every prompt to be answered with no.

A: This generally is because of other processes keeping an handle to those files which "cannot be unliked" (as mentioned in "Cannot unlink a file in PHP/Windows").
That means your automated job has to make sure that all running processes are stopped/killed first, before updating the working directory.

A: Disclaimer, I don't know Ruby.
Per the documentation, and short of coding up a way to kill all the services that are still running (which may be the best route, depending on your solution and what you need to clean in order to test it) the best it seems we can hope for with this command is to make a shortlist of the files that always result in a [Y/n] prompt.
So, when I see the following: Unlink of file 'packages/RavenDB.Server.2.5.2851/tools/blahblahblah failed.
I add the following to my command:
git clean -fdx --exclude=/packages/RavenDB.Server.2.5.2851**

And, it seems to work.


text:
Q: How do I save a recorded video with a .3gp extension in asterisk? I am working on Ubuntu.
I would like to record on asterisk video files with the extension .3gp inside the voice mail file. How can I do that?
Till now the recorded video files have been saved in the voicemail folder under the .h263 format, but I would like to play the files on my android phone, so I need a .3gp or mp4 format. How do I solve this? I need some help. I've tried using ffmpeg in order to convert the asterisk h263 file into an mp4 file but without success. I have input format not detected error.
Need help. Appreciate.
in sip.conf I have:
videosupport=yes
allow=h263

extensions.conf
exten => 1001,1,Dial(SIP/1001)
exten => 1002,2,Voicemail(1001)
exten => 1001,3,HangUp()

A: I would like to know more about these .h263 files that this software produces. If you are on a Unix machine (like Mac OS X or Linux), run the 'file' command against one of the .h263 to see if the utility can automatically determine its type.


text:
Q: winforms read from text file using arrays c# I am doing winforms, and i am trying to read some lines from a text file so after that i can display it at a listbox. In my winforms i am recording activities and it is writing to a text file.

When i restart the program it is not displaying the lines. Here's my code to write activities to the text file shown:
` private void btnOK_Click(object sender, EventArgs e)
        {
            using (StreamWriter sw = new StreamWriter(User.ID + "activity.txt", true))
            {
                sw.Write(Environment.NewLine + txtName.Text + Environment.NewLine + "Type: " + txtType.Text + Environment.NewLine + "People: " + Convert.ToInt32(txtPeople.Text) + Environment.NewLine + dateTimePicker1.Value + Environment.NewLine);
                sw.Close();
            }
        }`

I am trying to display these lines when i open the program in the left listbox and details of it in the right listbox.

I tried something like that, but it is not displaying the info when the program restarts.
 using (StreamReader sr = new StreamReader(User.ID + "activity.txt"))
            {
                while (sr.Peek() != -1)
                {
                    evName = sr.ReadLine();
                    evType = sr.ReadLine();
                    evPeople = Convert.ToInt32(sr.ReadLine());
                    evDay = DateTime.Parse(sr.ReadLine());

                }
            }

A: How about this?
string[] Lines = System.IO.File.ReadAllLines(path);


text:
Q: How to import ScriptableObject asset file into Unity 3d project. I have created ScriptableObject derived Quests.asset file in one of my project and then just copied it into my other project Assets folder. When I click on this file in  project inspector view, I see "the associated script can no be loaded" message. When i create public Quests quests; field in my script, there is: "type not found" error. What have I done wrong?

A: Ok, got it. There was C# script with the same name I was missing. When copied to the new project all started to work.


text:
Q: Function stops executing once the player wins I am trying to build a simple game based on which player clicks the button to 100% faster. Each of the players have a button allocated for them and depending on who clicks faster the player wins. I want to make a logic where if the COUNT or COUNT_PLAYER2 exceed 100 the player one or two wins and all the functions stop executing. Can you please help me with the logic behind that?
let count = 0;
let maxCount = 50;
let player1_progress = document.getElementsByClassName("player1-progress__progressbar")[0];
console.log(player1_progress);
window.addEventListener("keypress", function(e) {
  console.log(e.keyCode);
  //if the button is "d"
  if (e.keyCode === 100) {
    console.log(count)
    // increase count if it's less than 100
    count = count === 100 ? 100 : count + 4;
    //target progressbar width and increase it
    let newWidth = (count / maxCount) * 50 + "%";
    player1_progress.style.width = newWidth;
    player1_progress.innerHTML = count + "%";
    if (count === 100) {
      console.log("player 1 is the winner!");
    }
  }
});

//player2 count

let count_player2 = 0;
let player2_progress = document.getElementsByClassName("player2-progress__progressbar")[0];
window.addEventListener("keypress", function(e) {
  //if the button is "d"
  if (e.keyCode === 47) {
    // increase count if it's less than 100
    count_player2 = count_player2 === 100 ? 100 : count_player2 + 4;
    //target progressbar width and increase it
    let newWidth_player2 = (count_player2 / maxCount) * 50 + "%";
    player2_progress.style.width = newWidth_player2;
    player2_progress.innerHTML = count + "%";
    if (count_player2 === 100) {
      console.log("player 2 is the winner!");
    }
  }
});

A: have you tried remove all event listeners when one of counts reaches 100?
something like this:
button_a_handler = e => {
// do stuff

if (count >= 100) {
  window.removeEventListener("keypress", button_a_handler);
  window.removeEventListener("keypress", button_b_handler);
}
};

 button_b_handler = e => {
 // do stuff

 if (count >= 100) {
   window.removeEventListener("keypress", button_a_handler);
   window.removeEventListener("keypress", button_b_handler);
 }
};


text:
Q: Menu in appme theme is not synching with hashing id in wordpress I am using appme theme on wordpress and everything is working good except for the active menu.
https://themes.athenadesignstudio.com/?theme=appme_wp
if you click on the link and click on the menu, you can see that it's not syncing with what it is clicked. For ex: if you click on feature, home will be active, if you click on screen shot, feature will be active and behaves different on different browser as well.

A: In the main.js file of appme folder, go to this line and as you can see the scrollTop: h-offset, so for a work around, i have changed it to scrollTop: (h-offset)+10. This will scroll the section a little more and we are set like this untill fix.
//Menu
menu:function() {
        //Slick nav
        jQuery(".main-navigation").slicknav({
                prependTo:"#responsive-menu",
                label:"",
                closeOnClick:true
        });

        //Submenu
        jQuery(".nav li").on("mouseenter", function() {
                jQuery(this).children("ul").stop().slideDown(200);
        });

        jQuery(".nav li").on("mouseleave", function() {
                jQuery(this).children("ul").stop().slideUp(200);
        });

        //Header menu
        jQuery(document).on("click", "#navigation ul li a, #responsive-menu ul li a", function() {
                try {
                        var id = jQuery(this).attr("href");
                        var h = parseFloat(jQuery(id).offset().top);
                        var offset = parseInt(jQuery("body").data("offset"), 10);

                        jQuery("body, html").stop().animate({
                                scrollTop:(h-offset)+10
                        }, 800);

                        return false;
                } catch(err) {}
        });

        //Sticky navigation
        if (AppMeOptions.navigation==="sticky") {
                jQuery(window).scroll(function() {
                        if (jQuery(window).scrollTop()>200) {
                                jQuery(".navbar").addClass("sticky-header");
                        } else {
                                jQuery(".navbar").removeClass("sticky-header");
                        }
                });
        }
},


text:
Q: Checkbox change is being detected twice I would like to use a checkbox to show if a service is running when it's checked, and uncked if is not running, this is my checkbox.
<input id="controller" type="checkbox" class="switch-small" checked > Controller

Then I'm using this JavaScript to capture the event.
In the code below I would like to know if the service is running or not, so I could change its state properly, for example, if is checked, and the user clicked on it, he would like to stop the service, and vice-versa.
var state = false;
if ( $('#controller').prop('checked') ){
  state = true;
}

But something is wrong in my code below, because the change is called twice and I don't know why is that, I would like to be called just once.
$(document).ready(function() {

    $('#controller').change(function () {

        if (!state){
            alert("ON");
        } else {
            alert("OFF");
        }

        if ( $('#controller').prop('checked') ){
            state = true;
        }else{
            state = false;
        }

    });
});

All my component has unique ID's.
Any idea why is that happening ?

A:

var state;
$('#controller').click( function () {
    state = this.checked;
    alert(state ? "ON" : "OFF");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<label>
    <input id="controller" type="checkbox" class="switch-small" checked="checked" />
    Controller
</label>


text:
Q: How can the following covariance of two piece-wise defined random variables be calculated? Let $K_1$  be a random variable defined piece-wise as follows:
$$ K_1
= \begin{cases}
a_1, & X_1 < H_1 \\
m_1 X_1+b_1, & H_1<X_1<H_2 \\
c_1, & X_1 > H_2
\end{cases} $$
$X_1$  is a random variable defined as:
$$X_1=L_1 (1+j_1 )$$
$L_1,H_1,H_2,a_1,m_1,b_1,c_1$  are arbitrary constants.
$$j_1\sim N(μ_1,σ_1^2)$$
Let $K_2$  be a random variable defined piece-wise as follows:
$$ K_2
= \begin{cases}
a_2, & X_2 < H_3 \\
m_2 X_2+b_2, & H_3 < X_2 < H_4 \\
c_2, & X_2 > H_4
\end{cases} $$
$X_2$  is a random variable defined as:
$$X_2=L_2 (1+j_2 )$$
$L_2,H_3,H_4,a_2,m_2,b_2,c_2$  are arbitrary constants.
$$j_2\sim N(μ_2,σ_2^2)$$

Problem. Calculate $\operatorname{Cov}(K_1,K_2)$.

I am able to calculate $E[K_1]$ and $E[K_2]$, but am unsure how to calculate $E[K_1K_2]$. Is there a way to calculate the above covariance without specification of a joint distribution? I'm assuming that $K_1$ and $K_2$ are not independent.


text:
Q: Multiple queries in mongoDB I would like to query multiple collections in mongodb, I have some data like this
Collection stops {
    { stop_id : 1, stop_name: 'a'},
    { stop_id : 2, stop_name: 'b'}, ...

Collection stop_time {
    { stop_id : 1, trip_id: 40},
    { stop_id : 2, trip_id: 41}, ...

Collection trips {
    { trip_id : 40, route_id: 400},
    { trip_id : 41, route_id: 401}, ...

Collection route {
    { route_id : 400, route_name: 'foo'},
    { route_id : 401, route_name: 'bar'}, ...

And for each stop_name, I would like to know the route_name that match with it... (I didn't chose he data-structure by the way, that's GTFS format...)
Is there a way to easily do a queries that respond to my problem?
Thanks

A: Such approach is not good for mongodb.You should create one collection that contains all data, and make only one query.
This is very important because:

*

*There is no transactions

*There is no joins

*There are only atomic operations on one document

*You will be not able to use aggregation framework

If it is inpossible to migrate to one collection schema then probably you should do as below:
    var _ = require("underscore")._;
    function get_all(cb) {
        stops.find({}, function(err, stps, cb) {

            stop_time.find({}, function(err, stptime) {

                var all = _.map(stps, function(e) {
                    e.trip_id = stptime[e.stop_id].trip_id;
                    return e;
                });

                trips.find({}, function(err, trips) {

                    all = _.map(all, function(e) {
                        e.route_id = trips[e.trip_id].route_id;
                        return e;
                    });

                    route.find({}, function(err, routes) {

                        all = _.map(all, function(e) {
                            e.route_name = routes[e.route_id].route_name;
                            return e;
                        });

                        cb(all)
                    });
                });

            });
        });
    }

Be carefully, if there is a large amount of data in DB then you probably should use Cursors. http://mongoosejs.com/docs/api.html#querystream_QueryStream


text:
Q: How to access dynamically generated web content from App? Trying to pull information from a web page for use in a Android app.  It looks like the information (song title) is dynamically added to the source.  In the source there's get a placeholder (using a  tag).  The browser, of course, displays the proper song title.
Looking for direction on how to go about getting my hands on that dynamically generated information in my app.
Thanks,
-- Joel

A: You should first figure out how the information is obtained. I'd say it's most likely fetched using AJAX via Javascript. Take a look at that script.
Once you figure that out, you can reproduce the behavior of the script (requesting the proper address, same method/parameters, etc.) from your Java code.
If that's impossible (or impractical -- the script is obfuscated, for example), you could always (although this is kinda hacky and I would not recommend it) load the URL in a WebView and hook yourself to the appropiate AJAX request using the WebView's java interface; or have it load and retrieve the information after the request is complete.

A: The song data MIGHT be embedded in the audio stream, in which case your decoder/player would have to be able to extract that info.


text:
Q: Inbound routing stops working on Windows 2003 Server x32 behind RRAS and Hyper-V We are having a weird issue with a Windows 2008 DCE Server running a Windows 2003 R2 SP2 x32 Server in a Hyper-V instance behind RRAS.
Essentially, this server stops receiving inbound traffic through RRAS periodically. Connecting to the server via Hyper-V manager and disconnecting and reconnecting the NIC allows inbound traffic to work again.
More details on the setup:
The server is a Windows 2008 Data Center Edition x64 with SP1. This server has a number of external IP's associated with it by our ISP. Because the ISP ties IP's to MAC's, we use RRAS with NAT to map the external IP to an internal IP on a Hyper-V server. For example, we have a Hyper-V Virtual Network on 192.168.1.X, with the server being 192.168.1.1 and a hyper-V instance having an IP of 192.168.1.11. Then in RRAS, we create a reservation through NAT to map the external IP to that internal IP.
Although it may not be relevant, there is also a separate 192.168.0.X network that links this server with another server (a private network through the ISP). We use the 192.168.0.X network for fast communication between the VM's on both Hyper-V servers.
This setup has been working fine for the rest of the VM's (including another Windows 2003 x32 setup), but for some reason this particular Windows 2003 VM likes to stop accepting inbound traffic through RRAS every so often (about every 10 hours, but not regularly).
When this happens, the VM is still pingable from the Hyper-V server using the 192.168.1.X, but it is not pingable from the outside. So I suspect the conflict has something to do with RRAS in this setup.
I've Googled various related keywords, and found some posts referencing issues with Windows 2003 SP2 and RRAS, specifically with security settings in TCP/IP. Supposedly there are some advanced security features in SP2 where it is extra careful with how it treats routed traffic. I have installed the related hotfix and double-check the registry setting, but this does not seem to fix the issue.
Any ideas?

A: This VM subsequently had HD issues, so I will chalk this one up to data corruption wonkiness.


text:
Q: How to keep the initial value a pointer was pointing after a variable is changed? I realize this code is silly, but it is a simplified version of my problem. The code below prints out 10 10's, what I would like it to do is print out the numbers 0 through 9, which were the values j was pointing at when j was added to the vector. How can I keep the pointer stored in the vector pointing to the original integer value it was pointing to when it was stored?
int main()
{
    std::vector<int*> test;
    int *j;
    for (int i = 0; i < 10; i++)
    {
        j = &i;
        test.push_back(j);
    }
    for (int i = 0; i < 10; i++)
    {
        std::cout << *test[i] << std::endl;
    }
        return 0;
}

A: For this simple example pointers aren't even necessary! We can simply do
std::vector<int> test;
for (int i = 0; i < 10; i++)
{
    test.push_back(i);
}

However, if you insist on using pointers like you are...you currently have Undefined Behavior.
After the loop ends, i goes out of scope and your pointers are pointing to memory you no longer own. What you want can be accomplished by using dynamically allocated memory. We can allocate a new integer for each value of the vector:
std::vector<int*> test;
int *j;
for (int i = 0; i < 10; i++)
{
    j = new int(i);
    test.push_back(j);
}

Just remember that you'll have to deallocate the memory yourself after you're done!
for (int i = 0; i < 10; i++)
{
    delete test.at(i);
}

A: I'm pretty sure you're looking for this
int main()
{
    std::vector<int> test;
    int *j;
    for (int i = 0; i < 10; i++)
    {
        j = &i;
        test.push_back(*j);
    }
    for (int i = 0; i < 10; i++)
    {
        std::cout << test[i] << std::endl;
    }
        return 0;
}

So.... I've changed 'test' to be a vector of integer values, not pointers, and I've dereferenced the pointer 'j' before storing it in the vector. And I've adjusted the print routine to print the value

A: You can point to elements of another container:
std::vector<int*> test;  // holding pointers
std::array<int, 10> ray; // holding values
std::iota(ray.begin(), ray.end(), 0) // 0, 1, 2, 3..
for (int i = 0; i < 10; i++)
{
    int *j = &ray[i];
    test.push_back(j);
}


text:
Q: millisecondsSinceEpoch is acting like is dependent to timezone in dart I have found some weird issues while running tests in our CI. The tests are flaky even tho we are mocking our function to return a fixed date. Running the same code returns a different value for millisecondsSinceEpoch
Here you can see the bit of code that causes the issue:
String fileName = "${event.gymName.replaceAll(RegExp(r'\s'), "-")}-${dateUtil.getCurrentDateTime().millisecondsSinceEpoch}.png";
String gymImage = await storageRepository.uploadImage(croppedFile, fileName);

and this is the test that fail in the CI but not in my local (only relevant bit):
group("on UploadGymImage event", () {
      final testDate = DateTime(2021, 1, 11);
      var newImageUrl = "https://gym.img/abc.png";

      setUp(() {
        when(mockStorageRepository.uploadImage(fakeImage, argThat(endsWith(".png"))))
            .thenAnswer((_) => Future.value(newImageUrl));
        when(mockDateUtil.getCurrentDateTime()).thenReturn(testDate);
      });

      tearDown(() async {
        verify(mockStorageRepository.uploadImage(
          fakeImage,
          "a-gym-1610319600000.png",
        ));
        verify(mockDateUtil.getCurrentDateTime());
      });
    });

The documentation for millisecondsSinceEpoch says:
  /// The number of milliseconds since
  /// the "Unix epoch" 1970-01-01T00:00:00Z (UTC).
  ///
  /// This value is independent of the time zone.
  ///
  /// This value is at most
  /// 8,640,000,000,000,000ms (100,000,000 days) from the Unix epoch.
  /// In other words: `millisecondsSinceEpoch.abs() <= 8640000000000000`.

So I thought that by returning a fixed date in my mock, there would not be an issue running this test anywhere.
Can someone explain to me why is so?
note: the CI returns 1610323200000 my local instead 1610319600000


text:
Q: Gatsby V4 getNodesByType I'm currently migrating my Gatsby V3 to Gatsby V4.
I have a createNode using a function that retrieve some data from GraphQL using getNodesByType("myType").
function getSecteur(realisation) {
const secteurs = getNodesByType(`StrapiSecteurs`);
console.log(secteurs)
if (realisation.client && realisation.client.secteur) {
  return secteurs.find(
    (secteur) => secteur.strapiId === realisation.client.secteur
  );
}

exports.onCreateNode = async ({

node,
actions,
getNodesByType,
}) => {
const { createNode } = actions;
if (node.internal.type === "StrapiRealisations") {
createNode({
  ...node,
  id: `${node.id}-markdown`,
  parent: node.id,
  children: [],
  client: {
    ...node.client,
    secteur: getSecteur(node),
  },
  citation: getCitation(node),
  internal: {
    type: "MDRealisation",
    contentDigest: digest(node),
  },
});

}
But in V4 this function does not retrieve any data, but I cannot found an alternative for getNodesByType.
Any idea(s) ?
Thanks

A: Have you tried something like:
exports.sourceNodes = ({ actions, getNodesByType }) => {
  getNodesByType("StrapiSecteurs").forEach(node => actions.touchNode(node))
}


text:
Q: How to start JavaFX scene in a new Thread I am trying to start a new scene from my main scene in a new thread.
Here is my action button:
private void handleButtonAction(ActionEvent event) throws IOException {
        Thread t1 = new Thread(new OpenScene());
        t1.start();

OpenScene Class with implements Runnable
public class OpenConsole implements Runnable {
       @Override
            public void run() {
                  System.out.println("hello from run");
                try {

                    Parent root = FXMLLoader.load(getClass().getResource("FXMLConsole.fxml"));

                    Scene scene = new Scene(root);
                    Stage stage = new Stage();
                    stage.setScene(scene);
                    stage.initModality(Modality.WINDOW_MODAL);
                    stage.showAndWait();
                } catch (IOException ex) {
                    Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

}

I am able to print a statement from run, but I don't see a new scene/stage.


text:
Q: Simple switch with optoisolator - CTR related I would like to use a optoisolator to act as a simple low current switch, however I'm slightly confused about how to apply the CTR.
From this answer, I should be using the minimum value on the CTR chart of the 4N28 optoisolator. So, for my application, I have 18mA going through the input, therefore the minimum CTR of 10% would yield a minimum output of 1.8mA. Does this mean that I can only have 1.8mA flowing through the output transistor? (the worst case scenario)
The device that I want to switch on requires a 0.52mA to flow through in order to turn on.

A: In general, you should set the photodiode current to whatever condition the datasheet guarantees the CTR at. The Vishay version of the part (datasheet added to your question) specifies 10-20% ctr at 10mA, but if another vendor specifies 18mA as you've indicated, go with it.
The 10-20% CTR means that the phototransisistor will be biased to only allow 10-20% of the photodiode current, so yes, if the CTR is 10% and the diode current is 18mA, the transistor will only allow 1.8mA to flow worst-case. (You don't externally limit the current to 1.8mA - the phototransistor does.) Your 0.52mA load should work OK with the 18mA you've specified, just bear in mind that there will be a voltage drop across the collector-emitter of the phototransistor that you will need to factor into your design.


text:
Q: Setting PDF start point with swift PDFkit I want to change the starting position of the first page of the table I created
for the first page created
let pageRect = CGRect(x: 0, y: 150, width: pageWidth, height: pageHeight)

for other created pages
let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)

i want to use how do i do this
for detailed code : Swift 5 - How to create table in PDF with PDFKit
class PDFCreator: NSObject {
let defaultOffset: CGFloat = 20
let tableDataHeaderTitles: [String]
let tableDataItems: [TableDataItem]

init(tableDataItems: [TableDataItem], tableDataHeaderTitles: [String]) {
    self.tableDataItems = tableDataItems
    self.tableDataHeaderTitles = tableDataHeaderTitles

}

func create() -> Data {

    let pageWidth = 8.5 * 72.0
    let pageHeight = 11 * 72.0
    let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
    let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: UIGraphicsPDFRendererFormat())
    let numberOfElementsPerPage = calculateNumberOfElementsPerPage(with: pageRect)
    let tableDataChunked: [[TableDataItem]] = tableDataItems.chunkedElements(into: numberOfElementsPerPage)
    let data = renderer.pdfData { context in
        for tableDataChunk in tableDataChunked {
            context.beginPage()

            if pdfHeaderStatus==false {

                let baslikTasarım = [
                    NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17),
                    NSAttributedString.Key.foregroundColor: UIColor(red: 32.0/255.0, green: 161.0/255.0, blue: 218.0/255.0, alpha: 1.0)
                ]

                let altBaslık = [
                    NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 11),
                    NSAttributedString.Key.foregroundColor: UIColor.black
                ]

                let unvanTarih = [
                    NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11),
                    NSAttributedString.Key.foregroundColor: UIColor.black
                ]

                let image = UIImage(named: "forgotpassword")
                let che = "CARİ   HESAP   EKSTRESİ"
                let text = "TARİH: "
                let alici = "ALICI: "
                let tarih = "\(bastarihTitle) - \(bittarihTitle)"
                let unvans = "\(unvanTitle)"
                che.draw(at: CGPoint(x: 30, y: -120), withAttributes: baslikTasarım)
                alici.draw(at: CGPoint(x: 30, y: -70), withAttributes: altBaslık)
                text.draw(at: CGPoint(x: 30, y: -20), withAttributes: altBaslık)
                image?.draw(at: CGPoint(x: 300, y: -120))
                tarih.draw(at: CGPoint(x: 110, y: -20), withAttributes: unvanTarih)
                unvans.draw(at: CGPoint(x: 110, y: -70), withAttributes: unvanTarih)

                let cgContext = context.cgContext
                print("cgContext", cgContext)
                drawTableHeaderRect(drawContext: cgContext, pageRect: pageRect)
                drawTableHeaderTitles(titles: tableDataHeaderTitles, drawContext: cgContext, pageRect: pageRect)
                drawTableContentInnerBordersAndText(drawContext: cgContext, pageRect: pageRect, tableDataItems: tableDataChunk)

                pdfHeaderStatus=true

            }
                    let cgContext = context.cgContext
                    drawTableHeaderRect(drawContext: cgContext, pageRect: pageRect)
                    drawTableHeaderTitles(titles: tableDataHeaderTitles, drawContext: cgContext, pageRect: pageRect)
                    drawTableContentInnerBordersAndText(drawContext: cgContext, pageRect: pageRect, tableDataItems: tableDataChunk)

        }
    }

    return data
}

func calculateNumberOfElementsPerPage(with pageRect: CGRect) -> Int {
    print("defaultOffset",defaultOffset)
    let rowHeight = (defaultOffset * 3)
    let number = Int((pageRect.height - rowHeight) / rowHeight)
    print("number",number)
    return number
}}

The header and table of the code I wrote works fine. but i can't change xy locations it won't let me
MyPDFTable


text:
Q: How to set cache on windows 10 pro 64bit machine When running Mongod I get the following WARNING: The file system cache of this machine is configured to be greater than 40% of the total memory. This can lead to increased memory pressure and poor performance. This is on a windows 10 pro 64 bit machine.  I have 16 gigs of ram.  I have a 225 gig ssd drive c: and 2 1 terabyte drives d: and e:
I've set the virtual memory as follows:
drive     initial size       max
c:         800               1000
d:         400                800
e:         400                800

it says space available is 134538 MB

The mogod reference says the following:
Check the Windows file system cache limit. Having a too high or unbound
upper limit can impact performance. Specifically, having a file system cache
that uses 40% or more of the total memory can lead to increased memory
pressure and poor performance. Use SetSystemFileCacheSize to limit the
amount of memory that the file system cache can use.

Could someone provide directions on how to do that?  The answer from @Md Haidar Ali Khan does not work

A: I found a free tool that will set SetSystemFileCacheSize here with 16 gigs of RAM I set it to 1024 4096 and the mongod warning went away

A: @DCR, As MongoDB 3.6 officialy released as on dated 5th December 2017. For Testing environment i have deployed MongoDB 3.6 in my environment. There is two new things i got in MongoDB 3.6 , which i have noticed. When we are starting the mongod server
1)The file system cache of this machine is configured to be greater
    than 40% of the total memory
2)Starting in MongoDB 3.6, mongod bind to localhost (127.0.0.1) by
        default. See Default Bind to Localhost.
Even in my Environment the test system setup configuration is
1)windows 10 enterprise with 64-bit
2) HDD is 500 GB
3)MongoDB version is 3.6
4) RAM is 4 GB
Note : The --wiredTigerCacheSizeGB limits the size of the WiredTiger internal cache. The operating system will use the available free memory for filesystem cache, which allows the compressed MongoDB data files to stay in memory. In addition, the operating system will use any free RAM to buffer file system blocks and file system cache.
To accommodate the additional consumers of RAM, you may have to decrease WiredTiger internal cache size.
After Edit
@DCR, Even in my environment i am also getting the same message after running the mongod server. It's nothing but a cache warning message which comes from wiredTiger storage engine.
I am also uploading the screen shot below

As per MongoDB jira Blog  Add warning about Windows SystemFileCacheSize for WiredTiger Some MongoDB users on Windows have switched to enabling direct_io because the file system cache on Windows is greedy by default and can lead to content in allocated memory getting swapped out - which leads to terrible performance.
Windows provides the SetSystemFileCacheSize API that allows limiting the amount of memory that can be used by the file system cache. The setting is global across the computer.
We could add code into MongoDB that calls the API, and limits the amount of memory the file system cache can use to a percentage of available memory.
The call should only be done for storage engines that have a cache management layer. MMAP relies on the file system cache using all available memory - limiting how much memory is available would hurt MMAP users.
As starting in MongoDB 3.0, the WiredTiger storage engine is available in the 64-bit builds. Changed in version 3.2: The WiredTiger storage engine is the default storage engine starting in MongoDB 3.2.
For further your ref Here , Here and WiredTiger storage engine


text:
Q: Mapping Confusion -Implicit Function Theorem- Here is the Implicit Function Theorem statement:
"Let $g : R^k \times R^n \to R^n$ be a continously differentiable function s.t. $g(x_0, y_0) = c$ and $D_yg(x_0,y_0) : R^n \to R^n$ is an isomorphism. Then $\exists_{x_0 \in U}$ and $\exists_{y_0 \in V}$, $\exists_{\phi : U \to V}$ s.t. 1) $\left \{ (x,y) : g(x,y) = c \right \}$, $U \times V = $graph($\phi$) and 2) $\phi$ is differentiable and $D\phi(x) = -\left [ D_yg(x,\phi(x)) \right ]^{-1} \left [ D_xg(x,\phi(x))\right ]$"
I am confused on the meaning of condition $1)$, the mapping $\phi : U \to V$, and how we prove that the functions $g : R^k \times R^n \to R^n$ and $\phi : U \to V$ is differentiable.
Looking at an IFT example in http://bama.ua.edu/~mjvanessen/IFT%20Examples.pdf , I was trying to piece the statement of the theorem to the problem (#1). In the first problem we are looking for a function $\phi(x)$ s.t. $g(x,\phi(x)) = 0$, but how does the mapping $\phi : U \to V$ work in the problem. Can someone show me this mapping in the problem we are working on?
Then, how do we show that $g()$ is continuously differentiable and $\phi()$ is differentiable? If someone could explain in detail this would help me understand this theorem a lot better. Thanks.

A: $\phi$ gives the solution of $g(x,y)=0$. Namely, $y=\phi(x)$.
$g$ continuously differentiable is the hypothesis. Usually $g$ will be some known function and checking that is continuously differentiable will be trivial. The differentiability of $\phi$ is the conclusion. $\phi$ is differentiable because of the theorem and you don't need show it again. And $\phi$ will be "unknown" (no explicit formula except in some cases).
EDIT: try with the example $x^2+y^2=1$. This curve is not the  graph of a function $y=y(x)$, but some chunks are graphs of some function(s).


text:
Q: ReOrder a List to one after another I have a list that has three different types  They are added to a List as groups and not one by one.
These items are added to a list 5 at a time  and look like this:
(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3)
Now I want to reorder the list so it looks like this:
(1,2,3,1,2,3....)
How can I optimize this process?
for (int i = 0; i < list.size(); i++)
     {
            //Reorder the list here
     }

A: As long as all of your groups are of equal size you can use one of these aproaches:
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Sorting {

    public static void main(String[] args) {
        final List<Integer> list = Arrays.asList(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3);
        System.out.println("Input: " + list);
        System.out.println("Solution1 (regroup): " + regroup(list, 3));
        System.out.println("Solution2 (regroup2): " + regroup2(list, 5));
        System.out.println("Solution3 (groupSize constructor): " + new GroupedList<Integer>(list, 5));
        System.out.println("Solution3 (typeCount constructor): " + new GroupedList<Integer>(3, list));
        System.out.println("Demonstration of Solution3 emptyList constructor for groupSize 5");
        final GroupedList<Integer> groupedList = new GroupedList<Integer>(5);
        final List<List<Integer>> oneOfEachType = groupedList.getOneOfEachType();
        System.out.println("Ungrouped: " + groupedList);
        System.out.println("Grouped:" + oneOfEachType);
        // While addAll is shorter code, add also works
        groupedList.addAll(Arrays.asList(11, 12, 13, 14, 15));
        groupedList.addAll(Arrays.asList(21, 22, 23, 24, 25));
        groupedList.add(31);
        groupedList.add(32);
        groupedList.add(33);
        groupedList.add(34);
        groupedList.add(35);
        System.out.println("After adding 3 groups");
        System.out.println("Ungrouped: " + groupedList);
        System.out.println("Grouped:" + oneOfEachType);
        groupedList.addAll(Arrays.asList(41, 42, 43, 44, 45));
        System.out.println("After adding 4th group");
        System.out.println("Ungrouped: " + groupedList);
        System.out.println("Grouped:" + oneOfEachType);
    }

    /**
     * Solution one: returns the reordered list, if you know how many different types are to be handled
     *
     * @param list
     *         input list with equally-sized groups of the same type following each other
     * @param typeCount
     *         count of equally sized groups are in {@code list}
     * @param <T>
     *         type of elements in {@code list}
     * @return new {@link java.util.ArrayList} consisting of the same elements as in {@code list} in the desired order.
     */
    private static <T> List<T> regroup(final List<T> list, final int typeCount) {
        final int groupSize = list.size() / typeCount;
        final ArrayList<T> result = new ArrayList<T>(list.size());
        for (int i = 0; i < groupSize; i++) {
            for (int j = 0; j < typeCount; j++) {
                result.add(list.get(i + j * groupSize));
            }
        }
        return result;
    }

    /**
     * Solution two: returns the reordered list, if you know how many items of each type are added
     *
     * @param list
     *         input list with equally-sized groups of the same type following each other
     * @param groupSize
     *         size of one of the equally sized groups in {@code list}
     * @param <T>
     *         type of elements in {@code list}
     * @return new {@link java.util.ArrayList} consisting of the same elements as in {@code list} in the desired order.
     */
    private static <T> List<T> regroup2(final List<T> list, final int groupSize) {
        final ArrayList<T> result = new ArrayList<T>(list.size());
        for (int i = 0; i < groupSize; i++) {
            for (int j = 0; i + j * groupSize < list.size(); j++) {
                result.add(list.get(i + j * groupSize));
            }
        }
        return result;
    }

    /**
     * Solution three: wrapper class around the original list. This solution reflects changes to the original list
     * immediately and can be used to change the original list if desired
     *
     * @param <T>
     *         type of elements in this list
     */
    public static class GroupedList<T> extends AbstractList<T> {

        private final List<T> list;
        private final int     groupSize;

        /**
         * Empty list, than can be filled with groups of {@code groupSize} elements one group after another.
         */
        public GroupedList(final int groupSize) {
            this.list = new ArrayList<T>();
            this.groupSize = groupSize;
        }

        /**
         * Backed by a list with same-typed groups consisting each of {@code groupSize} elements
         */
        public GroupedList(final List<T> list, final int groupSize) {
            this.list = list;
            this.groupSize = groupSize;
        }

        /**
         * Backed by a list with {@code typeCount} same-typed groups consisting each of the same number of elements
         */
        public GroupedList(final int typeCount, final List<T> list) {
            this.list = list;
            this.groupSize = list.size() / typeCount;
        }

        /**
         * Number of items of the same type. You need to add this many elements at once.
         */
        public int getGroupSize() {
            return groupSize;
        }

        /**
         * Number of different types in each sub-sequence.
         */
        public int getTypeCount() {
            return list.size() / groupSize;
        }

        @Override
        public boolean add(T t) {
            return list.add(t);
        }

        @Override
        public T get(int index) {
            final int realIndex = getRealIndex(index);
            return list.get(realIndex);
        }

        @Override
        public T set(int index, T element) {
            final int realIndex = getRealIndex(index);
            if (realIndex < list.size()) {
                return list.set(realIndex, element);
            } else {
                throw new IndexOutOfBoundsException("Adding to this List-implementation is not possible");
            }
        }

        /**
         * Translate reordered index to index of underlying list
         */
        private int getRealIndex(int index) {
            final int typeCount = getTypeCount();
            if (typeCount * groupSize != list.size()) {
                throw new IllegalStateException("There is an incomplete group. Can't establish list order.");
            }
            final int offsetInGroup = index / typeCount;
            final int groupStart = (index % typeCount) * groupSize;
            return offsetInGroup + groupStart;
        }

        @Override
        public int size() {
            return list.size();
        }

        /**
         * Produce a list of the lists generated by {@link #getOneOfEachType(int)}. The generated list is read-only
         * while the contained lists are writable. Size of this list will always be the same as {@link #getGroupSize()}.
         */
        public List<List<T>> getOneOfEachType() {
            return new AbstractList<List<T>>() {
                @Override
                public List<T> get(int index) {
                    return getOneOfEachType(index);
                }

                @Override
                public int size() {
                    return groupSize;
                }
            };
        }

        /**
         * Get the {@code groupNumber}-th list consisting of on element of each type. You can replace elements of this
         * list and as elements are added to {@link tc.vom.test.with.deps.Sorting.GroupedList} elements will also be
         * visible through the returned list.
         */
        public List<T> getOneOfEachType(final int groupNumber) {
            return new AbstractList<T>() {

                @Override
                public T get(int index) {
                    return list.get(getRealIndex(index));
                }

                @Override
                public T set(int index, T element) {
                    return list.set(getRealIndex(index), element);
                }

                private int getRealIndex(int index) {
                    final int typeCount = getTypeCount();
                    if (index >= typeCount) {
                        throw new IndexOutOfBoundsException();
                    }
                    if (typeCount * groupSize != list.size()) {
                        throw new IllegalStateException("There is an incomplete group. Can't establish list order.");
                    }
                    return index * groupSize + groupNumber;
                }

                @Override
                public int size() {
                    return getTypeCount();
                }
            };
        }
    }
}

With regroup you need to know how many types there are with regroup2 you need to now how many of the same type are inserted.
With GroupedList you can create a wrapper around an existing List. You can iterate over GroupedList in the desired order and it will work as long as the number of elements in the original List does not change during iteration. You can also use getOneOfEachType() to itereate over individual sub-groups without having to utilize an external counter.
I implemented only add(T) and not add(int,T) as shifting the virtual order is a bit tricky (but can be done). Abstract List uses add(T) to implement addAll(Collection<T>) so this also works.
If you don't need to add to the List after wrapping my previous implementation could be a bit faster as the typeCount is fixed. The getOneOfEachType-function can easily be adopted to the old implementation by replacing getTypeCount() with typeCount.
Both functions and the GroupedList only work if the groups are of equal size.


text:
Q: Authorized call of a lambda which does not require authorization to optionally get username I have a lambda function get-profile. It returns a user's profile similiar to an instagram profile. It has a follow button which behaves differently depending if the viewer is signed in or not. If the vieweris signed in and already following the user, the button text instead shows unfollow.
My lambda function has no authorization since I want every visitor of the site the be able to view user profiles. The serverless.yml setups looks like this:
    handler: api/get-profile.handler
    events:
      - http:
          path: users/{id}
          method: get
          cors: true

Now I want receive additional information if a signed in user calls this function, so I can find out if A is already following B. How can I handle authorized and unauthorized cases inside the same function?
I am using aws-iam for authorization.
My best idea is to create another function get-profile-authorized but this way I'd have two different end points to call plus additional case handling inside my react app. Another option is creating a custom authorizer which requires me to write the complete authentication process by myself which might be very error prone. Do you guys have an idea to solve this easily?
If calling the current put-profile which does not require authentication as an signed in user, the lambda function does not receive any information about the callee.

event.requestContext.identity

looks like this.
            "cognitoIdentityPoolId": null,
            "accountId": null,
            "cognitoIdentityId": null,
            "caller": null,
            "sourceIp": "93.104.81.250",
            "principalOrgId": null,
            "accessKey": null,
            "cognitoAuthenticationType": null,
            "cognitoAuthenticationProvider": null,
            "userArn": null,
            "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0",
            "user": null
        }

adding authorization inside serverless.yml would fill in that information but then I cannot be called by unauthorized users.

authorizer: aws_iam

A: You definitely want to add another lamba as you described. Otherwise you can also handle the authentication yourself, manually checking for the authorization token in the headers and authenticating it against cognito but I would advise against it.
You want to do 2 different things. You should write 2 different lambdas.


text:
Q: Return out of a void function I have a read() function with an arrow-function as a parameter.
If I implement the function like this, the value is shown in the console as it should.
function(path: string) {
    this.db.read(path, val => {
      console.log(val.value)
    });
}

My question is, how can I get the value out of this function?
I tried it in several return ways, but nothing was worked.
//This is not working...
function(path: string) {
  newValue = this.db.read(path, val => {
      console.log(val.value)
      return val.value;
    });
  return newValue;
}

//Is working, but not really good...
private newValue;

function(path: string) {
  this.db.read(path, val => {
      console.log(val.value)
      this.newValue = val.value;
    });
  return this.newValue;
}

Maybe someone can give me a hint on how to do that.

A: Try this approach. Return new Promise instead of val that you will get in some future time.:
function readDb(path: string) {
  return new Promise(function(resolve, reject) {
    this.db.read(path, val => {
      resolve(val.value);
    });
  });
}
this.readDb("/path").then(function(val) { console.log(val) });

A: Your case is related Asynchronous calls. So its very important that you play with Observable, Callback and Subscription.
Since read returns the Observable already, you don't need to create new one.
What needs to be changed ?
So that needs to be changed in your code. All is fine except the way you are calling it. Do not return the value instead let it return the Observable.
Solution 1
readData(path){
   new Promise((resolve, reject)=>{
      this.db.read(path, val => {
          let readValue = val.value;  //<-- you can choose what you want to return.
          resolve(readValue);
       });
   });

//usage
readData("/path/of/db").then(value=>{
   console.log(value); //value is here once the DB call is completed.
});

Solution 2
The same thing can be achieved by Observable if you want to notify you every time new data is received.
private _subject: Subject = new Subject();
readData(path){
      this.db.read(path, val => {
          let readValue = val.value;  //<-- you can choose what you want to return.
          subject.next(readValue);
       });
}

usage
this.subject.subscribe((data) => {
    console.log('Data from DB ', data);
  });

A: the 2nd solution you gave is the way to achieve that.
When you do this.newValue = val.value; you affect the value you get from your read function to the variable newValue, which is exactly what you want, therefore the value is already outside of the function.
private newValue;

function(path: string) {
  this.db.read(path, val => {
    this.newValue = val.value;
  });
}

You don't need to return anything here since you already have the value stored on your private variable newValue.


text:
Q: Find out if UNC path is pointing to local machine Is there any simple way to tell if UNC path points to a local machine.
I found the following question SO
Is there any WIN32 API that will do the same?

A: #include <windows.h>
#include <WinSock.h>
#include <string>
#include <algorithm>

#pragma comment(lib, "wsock32.lib")

using namespace std;

std::wstring ExtractHostName( const std::wstring &share )
{
if (share.size() < 3 )
    return L"";
size_t pos = share.find(  L"\\", 2 );
wstring server = ( pos != string::npos ) ? share.substr( 2, pos - 2 ) : share.substr( 2 );
transform( server.begin(),server.end(), server.begin(), tolower);
return server;
}

bool IsIP( const std::wstring &server )
{
size_t invalid = server.find_first_not_of(  L"0123456789." );
bool fIsIP = ( invalid == string::npos );
return fIsIP;
}

bool IsLocalIP( const std::wstring &ipToCheck )
{

if ( ipToCheck == L"127.0.0.1" )
    return true;

WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 1, 1 );
if ( WSAStartup( wVersionRequested, &wsaData ) != 0 )
    return false;

bool fIsLocal = false;

char hostName[255];
if( gethostname ( hostName, sizeof(hostName)) == 0 )
{
    PHOSTENT hostinfo;
    if(( hostinfo = gethostbyname(hostName)) != NULL )
    {
        for (int i = 0; hostinfo->h_addr_list[i]; i++)
        {
            char *ip = inet_ntoa(*( struct in_addr *)hostinfo->h_addr_list[i]);
            wchar_t wcIP[100]={0};
            ::MultiByteToWideChar(CP_ACP, 0, ip, -1, wcIP, _countof(wcIP));
            if (ipToCheck == wcIP)
            {
                fIsLocal = true;
                break;
            }
        }
    }
}
WSACleanup();
return fIsLocal;
}

bool IsLocalHost( const std::wstring &server )
{
if (server == L"localhost")
    return true;

bool fIsLocalHost = false;

wchar_t buffer[MAX_PATH]={0};
DWORD dwSize =  _countof(buffer);
BOOL fRet = GetComputerName( buffer, &dwSize );
transform( buffer, buffer + dwSize, buffer, tolower);
fIsLocalHost = ( server == buffer );
return fIsLocalHost;
}

bool ShareIsLocal( const std::wstring &share )
{
wstring server = ExtractHostName( share );
bool fIsIp = IsIP( server );
if ( fIsIp )
    return IsLocalIP( server );
else
    return IsLocalHost( server );
}