text:
Q: What is the efficient way of dynamically creating and reusing multiple mongodb connections in nodejs? I am using mongodb 2.2.3 and nodejs 0.10.5.
I am creating an app where I am connecting to different mongodb instances on different hosts.
What is the most efficient way of dynamically creating and reusing the different connections ?
For example I have several hosts in an array hostArray and I want to get all the collecions in it.
function getCollectionNames(hostsArray) {
    async.map(hostsArray,function(item,callback){
        uri = "mongodb://" + item['user'] + ":" + item['passw'] + "@" + item['host'] + "/" + item['dbname'];
        var mongoClient = new MongoClient.connect(uri,function(err,db){
            if(!err) {
                 db.collectionNames(function(error,collections){
                    if(!err){
                        callback(null,collections);
                    }else{
                        callback(err,null);
                    }
                });
            } else {
                callback(error,null);
            }
        });
    },function(err,results){
        res.send(results);
    });
}

There are too many open connections I can see when looked at the console of of of the mongodb server, and upon reaching higher numbers, it get crashed.
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44311 #167 (87 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44312 #168 (88 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44313 #169 (89 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44314 #170 (90 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44315 #171 (91 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44316 #172 (92 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44317 #173 (93 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44318 #174 (94 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44319 #175 (95 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44320 #176 (96 connections now open)
Mon Oct 21 16:34:20 [conn167] end connection 127.0.0.1:44311 (95 connections now open)
Mon Oct 21 16:34:20 [conn169] end connection 127.0.0.1:44313 (94 connections now open)
Mon Oct 21 16:34:20 [conn171] end connection 127.0.0.1:44315 (94 connections now open)
Mon Oct 21 16:34:20 [conn173] end connection 127.0.0.1:44317 (92 connections now open)
Mon Oct 21 16:34:20 [conn175] end connection 127.0.0.1:44319 (92 connections now open)
Mon Oct 21 16:34:20 [conn168] end connection 127.0.0.1:44312 (90 connections now open)
Mon Oct 21 16:34:20 [conn170] end connection 127.0.0.1:44314 (89 connections now open)
Mon Oct 21 16:34:20 [conn172] end connection 127.0.0.1:44316 (88 connections now open)
Mon Oct 21 16:34:20 [conn174] end connection 127.0.0.1:44318 (87 connections now open)
Mon Oct 21 16:34:20 [conn176] end connection 127.0.0.1:44320 (86 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44321 #177 (87 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44322 #178 (88 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44323 #179 (89 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44324 #180 (90 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44325 #181 (91 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44326 #182 (92 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44327 #183 (93 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44328 #184 (94 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44329 #185 (95 connections now open)
Mon Oct 21 16:34:20 [initandlisten] connection accepted from 127.0.0.1:44330 #186 (96 connections now open)

A: You can use async.mapLimit to limit the number of parallel requests/connections.
But you're also not closing your connections when you're done with them, which might (also) be the reason why you're running out of connections:
var mongoClient = new MongoClient.connect(uri,function(err,db){
  if (!err) {
    db.collectionNames(function(error,collections){
      // done, close connection
      db.close();

      // call back with results or error
      if (!error){
        callback(null, collections);
      } else {
        callback(error, null);
      }
    });
  } else {
    callback(err, null);
  }
});

(the code above should also fix your mixing of the err and error variables)


text:
Q: Replace output file extension in linux shell command Say I have a command, convertImage, which takes some input jpeg, and spits out a new png in the same directory:
convertImage --format png photo.jpg -o photo.png

I want to make an alias "convertToPng" which takes only one arg, the file:
convertToPng photo.jpg

My current solution is this:
alias convertToPng "convertImage --format png \!:1 -o \!:1.png"

However this will name the output file to "photo.jpg.png" and I want it to be named "photo.png". Is there any way to parse the filename first, and then pass that to the convertImage executable?

A: If your input is always jpg then
convertToPng photo
alias convertToPng "convertImage --format png \!:1.jpg -o \!:1.png"

or give extension as 2nd parameter
convertToPng photo jpg
alias convertToPng "convertImage --format png \!:1.\!:2 -o \!:1.png"

or last option
convertToPng photo.jpg
alias convertToPng "convertImage --format png \!:1 -o `echo $1 | cut -f1 -d'.'`.png"

or write a function in your .bashrc as follows
function convert()
{
    convertImage --format png $1 -o `echo $1 | cut -f1 -d'.'`.png;
}

and execute above function as
convert photo.jpg

I prefer the function way as it gives you lot flexibility over aliases and you can do much more than just one statement.

A: echo photo.jpg | awk -F. '{print $1".png"}'

This could be used in a command line invocation like so:
$ convertImage --format png photo.jpg -o `echo photo.jpg | awk -F. '{print $1".png"}'`

redpajama_set_name: RedPajamaStackExchange


text:
Q: Customising MacOS Bundle's Info.plist file with CMake I'm using CMake generate build files for a cross platform game and want to specify custom NSMainNibFile and NSPrincipalClass values in certain bundle's Info.plist file
Here's the relevant portion of my Info.plist.in template:
<key>NSMainNibFile</key>
<string>${MAIN_NIBFILE}</string>
<key>NSPrincipalClass</key>
<string>${PRINCIPAL_CLASS}</string>

What I'm doing in my CMakeLists.txt is:
set_target_properties(GLWindow PROPERTIES
  MACOSX_BUNDLE_BUNDLE_NAME "OpenGL Test"
  MAIN_NIBFILE "MainMenu"
  PRINCIPAL_CLASS "NSApplication")
  MACOSX_BUNDLE_INFO_PLIST ${CMAKE_SOURCE_DIR}/CMake/Info.plist.in)`

If I get the MAIN_NIBFILE property for the target, it returns MainMenu as expected, but the actual generated Info.plist is empty.
BUT...
If I globally set these variables, it works fine.
# I would prefer to set these at target scope,
# but it doesn't bloody work!
set(MAIN_NIBFILE "MainMenu")
set(PRINCIPAL_CLASS "NSApplication")

Am I missing something here or is this a limitation of CMake or how it handles macOS bundles?

A: If you look at the documentation for MACOSX_BUNDLE_INFO_PLIST, you will see that it only supports setting a limited number of properties that affect the Info.plist template (MACOSX_BUNDLE_BUNDLE_NAME, etc). None of these are for the NSMainNibFile or NSPrincipalClass keys. However, in that documentation it gives a hint at the functionality of the template:

its Info.plist file is created by configuring a template

What is actually happening, is that the module is calling configure_file on the .plist.in file. This is why setting variables at the global scope works, but setting them at the property level does not.
So, the answer is that you must set those as variables, not as target properties. If you are worried about scope of these, you can unset the variables immediately after use, and, it should be noted that variables only are not visible to their parent scopes, unless they are specifically set as such.


text:
Q: MVC4/ Google OpenID limit to specific Google Apps Domain(s) I created a new MVC4/.NET4.5 project and enabled Google OpenID.  This worked, shockingly easily.
My company has "gone google" and our domains/ employee identities are in the Google Apps webspace.
How can I allow only our Google Apps domains to authenticate to my new website?  I'm hoping it's a simple thing like the authentication piece was.
Here is some additional information:

*

*I literally created a default web application and enabled the Google Authentication piece.  I could not believe how simple it was to validate against Google.

*My company has literally hundreds of email domains, all rolled up under one email domain "umbrella".  For example, my company's corporate email domain name is "foo.com", but under this we have "x.foo.com", "bar.com", and "yomommasougly.net".  All of these are part of the "foo.com" Google Apps domain.

*The ultimate goal is, a description of what needs to be done (and where) to take this default application and restrict it to all domains under the "foo.com" domain.

*With hundreds of domains, and more being added all the time, it is not practical to specify every domain explicitly.

A: Assuming you're using DotNetOpenAuth check out the authentication code for the Stack Exchange Data Explorer.
Essentially, you just ask for the e-mail address with your request:
request.AddExtension(
    new ClaimsRequest
    {
        Email = DemandLevel.Require,
    }
);

Then check the returned address against your domain whitelist (I'm assuming you're already only accepting google OpenIDs)
var sreg = response.GetExtension<ClaimsResponse>();
If (!HasWhiteListedDomain(sreg.Email)) {
    // Fail Here
}

Note that these bits of code need to be added to your Web.config to get the exact code for fetching the e-mail above working:
  <configSections>
    <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true" />
  </configSections>
  <dotNetOpenAuth>
    <openid>
      <relyingParty>
        <behaviors>
          <!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
                    with OPs that use Attribute Exchange (in various formats). -->
          <add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" />
        </behaviors>
      </relyingParty>
    </openid>
  </dotNetOpenAuth>

Edit:
If using OAuthWebSecurity getting the e-mail will just look something like this:
var userDataFromProvider = result.ExtraData;
var email = userDataFromProvider["email"];

Source


text:
Q: Getting error trying to commit using Subversion on Mac OS X Using Subversion I try to commit with:
 svn ci dir/filename

And I get this:
svn: system('emacs svn-commit.tmp') returned 256

What does this mean? How can I to fix it?

A: Possibly related:  I'm seeing similar errors on vim when setting SVN_EDITOR without the qualifying the path.  From your error output, I see you have done the same with emacs.  Try export SVN_EDITOR=/usr/bin/emacs.  Doing the same with /usr/bin/vim eliminated the 256 status codes.
I can't explain why.  Seems like a bug to me.
See this 2009 discussion about vim on OSX 10.5.

A: When you try to commit something to Subversion, it needs a commit comment. Unless you pass a commit comment on the command line (using -m message), Subversion will automatically launch your preferred editor. It appears that your editor is emacs, but there is a problem launching it.
Either fix emacs, or set your EDITOR or SVN_EDITOR environment variables to a different editor that actually works.

A: Looks like svn is not able to launch emacs for editing the comments for the commit.
If you just hava a few words of comments for your commit you could use:
svn ci dir/filename -m "Made some small changes"

another option might be to use the --editor-cmd option of svn. see svn help ci for details.

A: googling svn: system('emacs svn-commit.tmp') returned 256 shows the following link as the first result.
http://jjinux.blogspot.com/2008/03/vim-weird-os-x-105-problem.html

A: It sounds like SVN tried to invoke emacs to allow you to edit the commit log message, and
something failed.
Workaround: use the -m flag to specify a commit message on the command line:
svn ci dir/filename -m "log message here"


text:
Q: Getting DrawerLayout to Slide over the ActionBar I have  a sliding drawer menu in an activity, which has an actionbar with some tabs on it.
I'd like to get the sliding drawer to slide over the tabs , not below them.
This is what it looks like right now...

Any ideas on how this could be done?
Note: I understand that I might be breaking some conventions and UI patterns here, and if it does not work at all, I'll look at alternatives. But I'd like to get this working first.
EDIT: See the below screen shot of the Google Play Music app that does exactly what I need. See @CommonsWare's answer below where he does agree that I might be breaking convention. But then given the Play Music app, it may not be altogether that rare either.

A: Check also this library http://www.androidviews.net/2013/04/pager-sliding-tabstrip/
The guy did a great job. You can use it with a navigation drawer and it works perfectly.

A: Finally, a clean way to achieve navigation drawer over sliding tabs in this blog
http://www.paulusworld.com/technical/android-navigationdrawer-sliding-tabs

A: you can use below libraries to get navigation model similar to Google play music app.

*

*ActionBarSherlock  (github)

*nested-fragments  (github)

*PagerSlidingTabStrip  (github)

*NavigationDrawer  (Android developer site)

*Latest Support v4 library

I have created a project Navigation Drawer with Tab Strip Example at github, have a look at it.
Below is the screenshot of it.

A:
Any ideas on how this could be done?

Do any of the following:

*

*Switch away from action bar tabs, perhaps to ViewPager and a tabbed indicator (PagerTabStrip, TabPageIndicator from ViewPageIndicator)

*See if an existing third-party drawer implementation has not yet updated to the new UI standards

*Fork DrawerLayout and modify it to suit

*Roll your own navigation drawer from scratch

I understand that I might be breaking some conventions and UI patterns here

Correct.

A: This can be done WITHOUT a Third party library.  Check out Google's Sliding Tabs samples
     SlidingTabsBasic:   http://developer.android.com/samples/SlidingTabsBasic/project.html
     SlidingTabsColors:  http://developer.android.com/samples/SlidingTabsColors/project.html

Also, check out this awesome link:  http://manishkpr.webheavens.com/android-sliding-tabs-example/
Worked like a charm for me.  :)

A: I had the same problem, but the only solution I found was to use tabs inside the inner fragment (not fragmentActivity). I don't know if it was the best solution, the only problem i had was styling this tabs, for the rest, it works perfectly

A: I managed to achieve this requirement by setting the navigationMode inside OnDrawerClosed and onDrawerOpened functions. It is a temp fix since the tabs actually do not disappear immediately.
  public void onDrawerClosed(View view) {
          getActionBar().setTitle(mTitle);
          if(getActionBar().getTabCount()>0) //Add tabs when the fragment has it
          getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
                        ...
                    }

   public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
                    ..

                    }

If you have some fragments with tabs, and other without it don't forget to remove tabs onCreateView of fragment that does not have tabs.
 getActionBar().removeAllTabs();

A: Actionbar Navigaton Drawer and SwipeTabs cant be used simultaneously. You should implement Navigation Drawer using Actionbar and swipetabs by simple Tabhosts. You can use Tabhost for tabs and use fragments for inside view of each Tab. Fragments should be used via viewpager to provide scrolling/swiping effect. Connect tabs and viewpager with eachother through their methods
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TabHost
    android:id="@+id/tabHost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

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

        <HorizontalScrollView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true"
            android:scrollbars="none" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
            </TabWidget>
        </HorizontalScrollView>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <android.support.v4.view.ViewPager
                android:id="@+id/viewPager_home"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </FrameLayout>
    </LinearLayout>
</TabHost>

A: Play music does not use standard ActionBar.Tab
Then you can implement your own tab container by extend HorizontalScrollView
and work together with ViewPager

A: I have use tabs inside fragment of drawer.
I solve this problem adding
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

in onDrawerClosed() and getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); in onDrawerOpend() method.
I hope this will help you.


text:
Q: Energy conservation in systems with discrete time Numerical simulations of classical particle dynamics usually break energy conservation due to discretization of time. Is there any explicit numerical scheme that does not break energy conservation (without global rescaling of velocities)? Is it even possible for a particle systems with discretized time to have something like energy conservation law?

A: Yes. Symplectic integrators are designed to do exactly that. They are intended for solving Hamiltonian systems where the Hamiltonian is conserved.
https://en.wikipedia.org/wiki/Symplectic_integrator


text:
Q: Generate WPF Mouse events with position I'm trying to create a more-or-less high-level UI test for a WPF control (but without the complexities of UI Automation – UIA works, but I'd rather avoid it if possible), and found RaiseEvent and InputManager.ProcessInput for synthesizing input events. What I couldn't figure out, though, is how mouse (and touch) events can be created with a particular position. MouseEventArgs has a GetPosition method that returns the position for the event, but how can I set it?
The reason why I avoided UI Automation here is two-fold: (1) I want the tests to run headless, if possible, thus injecting events instead of simulating mouse movement; (2) I need to test touch input as well, for which I didn't find a library to simulate them so far.
I tried inheriting from MouseDevice only to find that there are no virtual methods that are of use to me here, so that seems a dead end as well.


text:
Q: Stored procedure converts int to decimal I am writing a stored procedure to return some stats. I have two different tables, one with stats collected after the system has been taken into use, another with stats since
My procedure is as follows:
CREATE PROCEDURE getStats(IN uID INT, IN since_date DateTime)
BEGIN
  DECLARE rowcount int;
  select klubid from core_medlemmer where id = uID into @klubid;
  select create_date from core_klub where id = @klubid into @create_date;

  if since_date < @create_date then
    -- select from historic and current
    select sum(attendance) from core_historic_modestatistik where medlemsid = uID into @historic_total;
    SELECT @historic_total + count(*) as total_attendance from core_fremmode where medlemsid= uID and dato >= since_date;
  else
    -- select only current
    SELECT count(*) as total_attendance from core_fremmode where medlemsid= uID and dato >= since_date;
  end if;
END //
DELIMITER ;

Executing this stored procedure with select sum(attendance) from core_historic_modestatistik where medlemsid = uID looks correct:
+-----------------+
| sum(attendance) |
+-----------------+
|             655 |
+-----------------+

But it appears that the addition converts it to a real:
+------------------------------------+
| total_attendance                   |
+------------------------------------+
| 656.000000000000000000000000000000 |
+------------------------------------+

The column i am summing is an int and the count() function should only be able to return INTs, so any tips as to why this is happening, and how to address itbest would be much appreciated.

A: I've found the best way to force types in select's in stored procs is to INSERT...SELECT into a temporary table (created in the proc with the desired types), and then select from that. You can try CAST(x AS SIGNED), but then you can't control BIGINT, INT, etc..
Edit: The CAST is usually fine within a stored procedure/query; but when you need more defined types for interaction with API calls, such as GetInt32(fieldnum), the temp table method can be very helpful.


text:
Q: Deriving joint probabilities from marginal probabilities & polychoric correlations Given three ordered-categorical variables: $u_1, u_2, u_3$ with $K$ categories, I'm trying to derive their expected variance-covariance matrix using their marginal probabilities, thresholds, and polychoric correlation matrix.
I can derive their variances using the marginal probabilities:
Where:
$\bar{u_1} = p_1*1 + \cdots + p_k*K$
$V(u_1) = p_1*(1-\bar{u_1}) + \cdots + p_k*(K-\bar{u_1})$
But I'm stuck on how to derive $Cov(u_1, u_2)$. I've been told I'll need the joint probabilities of $u_1$ and $u_2$, but I'm not sure how to get those from the information that I have:

*

*Marginal probabilities

*Thresholds

*Polychoric correlation matrix

Any help greatly appreciated. Thanks!

A: Asked for help too soon sorry, I found the solution in Olsson (1979, p.447):
The joint probability $p_{ij}$ can be derived via:
$p_{ij} = \Phi_2(a_i,b_j) - \Phi_2(a_{i-1},b_j) - \Phi_2(a_i,b_{j-1}) + \Phi_2(a_{i-1},b_{j-1})$
Where $a_i,b_j$ are the thresholds and $\Phi_2$ is the bivariate normal PDF with (polychoric) correlation $p$
Olsson, U. Maximum likelihood estimation of the polychoric correlation coefficient. Psychometrika 44, 443–460 (1979). https://doi.org/10.1007/BF02296207


text:
Q: The programming languages A, B and C Is it correct if I write something like

He has knowledge of the programming languages A, B and C

Or does it necessarily have to be like

He has knowledge of the A, B and C programming languages

A: Correct English, in my opinion, but "have knowledge of a programming language" sounds rather strange and stilted. I suggest, instead, the simple and unambiguous:

"He can program in A, B and C."

As has been commented, it's obvious that they are programming languages in this sentence, so there is no need to say so.


text:
Q: Wrapping map visibility issues in sfml I'm implementing a wrapping map consisting of two parts and only the first view is visible and works as intended.
The second view is invisible and I don't know why. If you go to the left, there is a a black area instead of the second view.
After having done many number changes/tests, it seems as the second view is limited to the area of the first view only.
With one tiled maps, that were not bigger than the screen size it worked like a charm, unlike here. Many thanks for any help in advance.
#include <SFML/Graphics.hpp>
#include <iostream>

int main()
{
    sf::RenderWindow mMainWindow(sf::VideoMode(1000,600), "Map", sf::Style::Close);
    sf::View view(sf::Vector2f(500, 300), sf::Vector2f(1000, 600));
    sf::View view2(sf::Vector2f(500, 300), sf::Vector2f(1000, 600));

    sf::Image mapimage;
    mapimage.loadFromFile("world1.jpg");  //1000*600 px
    sf::Texture maptexture;
    maptexture.loadFromImage(mapimage);
    sf::Sprite mapsprite(maptexture);
    sf::Sprite mapsprite2(maptexture);
    mapsprite.setPosition(0, 0);
    mapsprite2.setPosition(1000, 0);

    sf::RectangleShape viewrect;
    viewrect.setSize(sf::Vector2f(2000, 600));
    viewrect.setPosition(0, 0);
    viewrect.setFillColor(sf::Color(250,0,0,40));

    sf::RectangleShape viewrect2;
    viewrect2.setSize(sf::Vector2f(2000, 600));
    viewrect2.setPosition(0, 0);
    viewrect2.setFillColor(sf::Color(0,0,250,40));

    float fview2 = 1;
    view2.setViewport(sf::FloatRect(fview2, 0, 1, 1));
    int mapmovementvar = 0;

    while (mMainWindow.isOpen())
    {
        sf::Event event;

        while (mMainWindow.pollEvent(event))
        {
            switch (event.type)
            {
            case sf::Event::Closed:
                mMainWindow.close();
                break;
            }
        }
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
        {
            system("cls");
            view.move(-100, 0);
            fview2=fview2+0.1f;
            mapmovementvar--;

            if(mapmovementvar<0)
            {
                mapmovementvar=19;
                fview2=-0.9f;
                view.reset(sf::FloatRect(1900, 0, 1000, 600));
                view2.reset(sf::FloatRect(-1000, 0, 1000, 600));
            }

            view2.setViewport(sf::FloatRect(fview2, 0, 1, 1));
            std::cout << "fview2 " << fview2 << std::endl;
            std::cout << "mapmovementvar " << mapmovementvar << std::endl;
        }

        mMainWindow.clear();

        mMainWindow.setView(view);
        mMainWindow.draw(mapsprite);
        mMainWindow.draw(mapsprite2);
        mMainWindow.draw(viewrect);

        mMainWindow.setView(view2);
        mMainWindow.draw(mapsprite);
        mMainWindow.draw(mapsprite2);
        mMainWindow.draw(viewrect2);

        mMainWindow.display();
    }
    return 0;
}

A: I do not have fixed the problem with the views you were having, but I think using views wasn't even needed in your case. See my code below which I think implement what you want.
Initialization
As you can see, you can load Texture directly from a file if you don't absolutely need the Image object for other stuff. And views are overkill here and I think that's not the goal of views to be used like what you want.
#include <SFML/Graphics.hpp>
#include <iostream>

int main()
{
    float screenWidth = 1000;

    sf::RenderWindow mMainWindow(sf::VideoMode(screenWidth, 600), "Map",
            sf::Style::Close);

    // no need to use image, you can load texture directly from a file
    sf::Texture maptexture;
    maptexture.loadFromFile("world1.jpg"); //1000*600 px

    // you only really need one sprite, but that's not really a problem.
    sf::Sprite mapsprite(maptexture);

    // you don't need views at all, just a position.
    sf::Vector2f pos;

App loop
Nothing changed here.
    while (mMainWindow.isOpen())
    {
        sf::Event event;

        while (mMainWindow.pollEvent(event))
        {
            switch (event.type)
            {
            case sf::Event::Closed:
                mMainWindow.close();
                break;
            default:
                break;
            }
        }

Keyboard input handling
When handling input, only change what's dependant on the input. Here, only the position changes. (And the sprite scale for zoom, but that's bonus stuff here)
        // you may as well test with all directions because f*ck One Direction.
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
        {
            pos.x += 1.0f;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
        {
            pos.x -= 1.0f;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
        {
            pos.y -= 1.0f;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
        {
            pos.y += 1.0f;
        }

        // bonus zoom
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Equal)) // + zoom
        {
            mapsprite.setScale(mapsprite.getScale().x + 0.001f,
                    mapsprite.getScale().y + 0.001f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Dash)) // - zoom
        {
            mapsprite.setScale(mapsprite.getScale().x - 0.001f,
                    mapsprite.getScale().y - 0.001f);
        }

Adjusted position
Since we're always using the same map, we only need to keep track of the position inside one map rectangle. So, if we go pass that rectangle, we just adjust the position to get back inside the map and we do that before rendering so it's invisible that we just changed the map position.
        // Here's all the magic happening, you loop your position around the width.
        float width = mapsprite.getGlobalBounds().width;
        if (pos.x <= -width)
        {
            pos.x += width;
        }
        else if (pos.x > 0)
        {
            pos.x -= width;
        }

        std::cout << "X pos : " << pos.x << std::endl;

Rendering loop
We only need one Sprite object to achieve the rendering loop since we use the same Texture that the Sprite is referencing. We just give a new position to the Sprite, then draw it, then repeat. You can still use many Sprite objects without problem as Sprite is a light-weight object, but it would be useless here to use more than one.
        mMainWindow.clear();

        for (int i = 0; pos.x + (i * width) < screenWidth; ++i)
        {

            // display each sprite with a new position according to the last one.
            mapsprite.setPosition(pos.x + (i * width), pos.y);
            mMainWindow.draw(mapsprite);

        }

        mMainWindow.display();
    }
    return 0;
}


text:
Q: Formatação valor padra BRL em javascript estou com muita dificuldade em formatar um valor em BRL para um form. Gostaria que quando o usuario digitar o valor em BRL o ponto e virgula sejam posicionados automaticamente. Sem a necessidade do usuário digita-los. Por favor, alguem teria uma ideia ou um script pronto? muito obrigado

A: Eu encontrei uma solução com Reg Exp. Você usa a expressão regular para localizar os valores números e substituí-los pela formatação em Real.
var test = 'R$ 1.700,90';

function getMoney( str )
{

        return parseInt( str.replace(/[\D]+/g,'') );

}

function formatReal( int )

{

        var tmp = int+'';

        tmp = tmp.replace(/([0-9]{2})$/g, ",$1");

        if( tmp.length > 6 )

                tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");

        return tmp;
}

var int = getMoney( test );

console.log( formatReal(1000) );

console.log( formatReal(12006) );

console.log( formatReal(1111) );

console.log( formatReal(120090) );

console.log( formatReal(int) );

Perceba que ele localiza o "valor" nesse trecho.
tmp.replace(/([0-9]{2})$/g, ",$1");

e faz a substituição pelo valor em formato de "real brasileiro"
tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");


text:
Q: creating and verifying a pointer into "if" statement Is this code correct?
void foo ( int* p )
{
  if ( int* p2 = p ) // single "="
  {
    *p2++;
  }
}

I always been thinking it's not, but recently i've saw such code in a colleague's of mine sources.
What if "p" is NULL? MS VS 2008 works correct but shows "warning C4706: assignment within conditional expression".
Thank you.

A: The warning assignment within conditional expression is usually issued by compilers to prevent cases where you write
 if (a = b)
 {

where you meant
 if (a == b) // big difference!
 {

In your sample, the 'assignment warning' is actually bogus, since it is, in fact, not an assignment, but rather an intialization:
 {
      int *p2 = p;
      if (p2)
      {

      }
 }

and there is no risk that you'd actually wanted the syntax error (int *p2 == p ?!) instead :)
The rest of your post is perfectly valid C++03 (and later) and just does what it says1.

1
(which in terms of lasting effect, isn't much because

*

*p2 is dereferenced without ever doing something with it

*p2 is incremented without ever doing something with it,

but I guess that's just the sample code? In case it isn't obvious, *p2++ is equivalent to *p2; p2++;)

A: By raising warning C4706, the compiler is simply questioning whether you actually meant to write if ( int* p2 == p ) instead of if ( int* p2 = p ) as shown.
Per 6.4 of the 2003 C++ Standard, if ( int* p2 = p ) is legal:

The value of a condition [if (condition)] that is an initialized
  declaration in a statement other than a switch statement is the
  value of the declared variable implicitly converted to type bool.

If p is NULL, condition (int* p2 = p) fails because the value of p2 is 0, and thus implicitly false, and *p2 is not incremented.

A: It's formally correct (in C++, but not in C).  Allowing a definition as
a conditional was added with dynamic_cast, to support such things as:
if ( Derived* p = dynamic_cast<Derived*>( ptrToBase ) ) {
    //  ...
}

The argument was that there would never be a moment where p was in
scope, but not null.  After the if, p is no longer in scope.
The argument doesn't hold water, since on one hand, if you add an
else, within the else block, p is in scope, and null.  And the
justification involving limiting the scope really isn't very strong
anyway, because if the function is long enough for it to matter, the
function is too long and too complex.  This construct supports things
like:
if ( Derived1* p = dynamic_cast<Derived1*>( ptrToBase ) ) {
    // ...
}
if ( Derived2* p = dynamic_cast<Derived2*>( ptrToBase ) ) {
    // ...
}
// ...

But this really isn't something you want to do in good code.
All in all, I'd avoid the construct, replacing it with something like:
int* p2 = p;
if ( p2 != NULL ) {
    //  ...
}

It's more explicit and more readable.  It does mean that p2 is in
scope outside the if, but I'd argue that if this causes any problems,
the function itself needs refactoring, because it is too long and too
complex.
EDIT:
With regards to the warning: it's a complete idiocy on the part of the
compiler.  There's no assignment within the conditional expression:
there's no assignment, period, and there's no "conditional
expression" the condition in the original is a declaration, not an
expression.
If the compiler wanted to warn about something (on stylistic
grounds, because it agrees with me that this is bad style), then it
should warn about an implicit conversion to bool.  (And of course,
whether this warning is emitted should be under control of an option.
The compiler should compile the language, not impose style, unless one
asks it explicitly to warn about specific style issues.)

A: the code is error prone (why not break it into 2 statements) but otherwise correct.
 if you break this into:
void foo ( int* p )
{
  int* p2 = p;
  if ( p2 )
  {
    *p2++;
  }
}

it is more readable and won't give you the warning. You can see it's also correct (in case of null you are just assigning p2 with null, which is ok).

A: If p is NULL, the condition fails. So the code is ok.

A: This code seems odd. It's correct, but I fail to see in which cases is it useful.
It's less readable then simple alternatives (like Oren S. mentioned), and needlessly defines a new variable in order to increment (*p). The parameter p is already a new variable on the stack, why create another one?

A: Look at int* p  as this "p is a pointer to an int". And, "p2 is also a pointer to an int". You are making p2 point to the pointer that p is also pointing to when you say p2 = p. The statement *p2++; will increment the address by 4 and point to something besides the int you were originally pointing to.  Whichi should be a 32bit integer. The pointer increments by 4 on a 32bit compiler.   If you use (*p2)++ wrapped in parenthesis it will increment the integer the pointer is pointing to.
Yes it works... wierd.
int ClassPtr::MethodA(int *p)
{
    if (int *p2 = p)
    {
       (*p2)++;
       return *p2;
    }
          return 0;
}

A: I think grammatically the code has no problem. But it is not a good style.
If you definitely know there is single "=", you can also wite like this:
if ((int* p2 = p) != NULL)
{
    *p2++;
}

I prefer the pointer compares to NULL.


text:
Q: Двунаправленная трассировка путей (bidirectional path tracing) Пытаюсь постичь трассировку путей (path tracing). Пока-что разобрался лишь с самой основой - когда из каждой точки пересечения запускается луч в случайном направлении в пределах полусферы, затем снова, и так рекурсивно, пока луч не ударится в источник света. В результате такой подход приводит к тому что в случае с маленькими источниками освещения изображения получается крайне шумным.
Следующие изображения демонстрируют уровень шума в зависимости от кол-ва семплов (лучей) на пиксель.

Кстати, что касается лучей на пиксель - тут я тоже не уверен что все делаю правильно, ибо метод "Монте-Карло", насколько я понимаю, подразумевает что из каждой точки пересечения запускаются несколько лучей, а затем их результат суммируется и усредняется. Но такой подход приводит к тому, что кол-во лучей растет в геометрической прогрессии, и уже после 6 отскоков достигает неадекватных значений, поэтому я решил что лучше просто запускать изначально несколько лучей на один пиксель (чуть отклоненных от центра пикселя в случайном направлении, не выходящих за пределы пикселях), но в каждом пересечении при этом генерируется только 1 луч. Я не знаю соответствует ли данный подход "Монте-Карло" или нет, но по крайней мере так хотя бы рендеринг длится не вечно..
Bidirectional path tracing
Я стал искать способы, как можно было бы уменьшить кол-во шума, и наткнулся на двунаправленную трассировку лучей (bidirectional path tracing). Но к сожалению нигде в сети я так и не смог найти подробного объяснения данного алгоритма простыми словами. Все что я понял, это то, что лучи генерируются как из камеры так и из источников освещения, а затем происходит проверка на возможность соединения точек пересечения этих путей.

То есть получается, если точки пересечения синего луча из камеры и белого луча из источника могут быть беспрепятственно соединены (на пути соединения нету преград) значит можно считать что луч из камеры может пройти по точкам y1, y0 прямо к источнику.
Но возникает множество вопросов:

*

*Если источник не точечный, а имеет какую-то форму, получается точка из которой запускается луч источника должна быть случайно выбрана на поверхности этого источника (примерно как на рис. 1)? Если брать только центр - тогда ведь не будет отличий от точечного источника?

*Нужно ли на каждый путь из камеры строить путь из источника, или из источника путь должен/может быть только один, в то время как из камеры для одного пикселя строится сразу несколько путей (семплов)?

*Количество отскоков/переотражений/преломлений должно быть одинаково для пути из камеры и источника? Или нет?

Но на этом вопросы не заканчиваются. Я многократно натыкался на упоминания о том, что метод двунаправленной трассировки позволяет хорошо (в сравнении с обычной трассировкой) моделировать каустику для преломляющих объектов. Я решил провести мысленный эксперимент, и совершенно не понял каким образом метод двунаправленной трассировки вообще как-либо может быть полезен для этого.
Пример 1

Здесь получается что путь в итоге будет построен, но количество отскоков будет крайне большим, и ни о какой каустике речи не идет, несмотря на то что луч из камеры направлен почти в ту же точку где заканчивается путь луча из источника.
Пример 2

Здесь и вовсе получается что путь построен не будет, поскольку между конечными точками путей есть преграда, хотя он вполне мог быть построен если бы точка x3 соединялась с точкой y1, но по условиям алгоритма (если я все верно понимаю) соединяются только последние точки путей.
Вопрос:
В чем польза от такого алгоритма, если в немалом кол-ве случаев пути либо не простраиваются либо оказываются излишне длинными? Может быть я что-то не правильно понимаю? Я натыкался на многие источники, где данный алгоритм как-то описывался, но в основном он описывался математически (с применением всяких магических терминов типа biased-unbiased, PDF, BSDF и прочих), а не.. алгоритмически. Я не то чтобы силен в математике и всяческих математических обозначениях и формулировках, хотелось бы просто понять ЧТО ДЕЛАТЬ, как правильно реализовывать в коде, как соединяются эти пути, в какой последовательности и прочее. Это ведь можно объяснить простыми словами, псевдокодом? Буду крайне признателен если кто-то наконец прольет свет на всё это.


text:
Q: Convert/Port PDWORD code in C# I'm converting some code from C++ to C#, and I need some insight on how to deal with lines like these:
PDWORD rgb32_data = (PDWORD) malloc(640*480*4);

From what I understand, the PDWORD type represents an unsigned integer (32bit). What would be a good C# strategy to implement a similar structure?
EDIT: I figured out that I need to use an IntPtr to replace the PDWORD, but the IntPtr would hold a single value as opposed to many values as in an array. Any C# suggestions?
EDIT2: Uint[]s don't work for me - unfortunately, the only way I can make the program compile, with all its dependencies, is when I enter an IntPtr as a the argument, not an IntPtr[].
Thanks.
EDIT - I've marked the solution, in addition I needed to do the following:
Since I needed an IntPtr cast, I added this code
        IntPtr rgb32_ptr;
        GCHandle handle = GCHandle.Alloc(rgb32_data, GCHandleType.Pinned);
        try
        {
            rgb32_ptr = handle.AddrOfPinnedObject();
        }
        finally
        {
            if (handle.IsAllocated)
            {
                handle.Free();
            }
        }

to get an IntPtr to the same.

A: According to MSDN, PDWORD is defined as:
typedef DWORD*  PDWORD;

So it's a pointer to a DWORD, which MSDN also says is an unsigned 32-bit integer - in other words, a uint.
Note that your line of C++ code allocates memory for an array of 640 * 480 = 307,200 DWORDs.
You could translate this directly as:
uint[] rgb32_data = new uint[640 * 480];

But the code might really want to use it as just a series of bytes in memory, so you might instead want to use a byte array
byte[] rgb32_data = new byte[640 * 480 * 4];

and use the methods in the BitConverter class (especially the ToInt32() method) if you think that is closer to how the original program handles the data.

A: You can use unsafe pointers and Marshal.AllocHGlobal()
    Program()
    {
        unsafe
        {
            IntPtr ptr = Marshal.AllocHGlobal(640 * 480 * 4);

            uint* ptr2 = (uint*)ptr.ToPointer();

            for (int i = 0; i < 640*480; i++)
            {
                ptr2[i] = 0;
            }

            Marshal.FreeHGlobal(ptr);
        }
    }

A: PDWORD is a pointer to a 32-bit unsigned integer. In C#, that would be ref uint32. Or IntPtr if you're on the 32-bit runtime.
It depends on how you're going to use it. If you're passing it to unmanaged code, then I'd suggest the ref UInt32. If you're using it for memory allocation (the return value from a Windows API function that allocates memory, for example), then you'd want to use IntPtr.

A: PDWORD is a pointer to a DWORD.  There are a few options to convert the code to C# depending on how it will be used.
For the DWORD itself you can use System.UInt32 as an equivalent.  Marshal.AllocHGlobal might be a possibility as a replacement, but we would need to see how it's going to be used.  Are you accessing the memory yourself or maybe passing it to another unmanaged function?


text:
Q: How to get object's class name? Assuming var_dump's output of my object looks like following:
template: object(HTMLTemplateDeliverySlip)#158 (7) {
  ["order"]=>
  object(Order)#164 (62) {
  (...)

how can I print the name between brackets, which is (HTMLTemplateDeliverySlip) ?

A: You can use get_class:
echo get_class($object);

A: Print the name of the class using get_class function:
echo get_class($obj);


text:
Q: Looking for faster way for row by row looping and transposing data in Python data frames I have just recently started learning coding and wrote the following code in Python to transpose large dataset row by row.
The code works fine but is unfortunately somewhat slow and takes roughly 15 minutes to complete. Transposing the whole dataset at once does not work as it creates unnecessary rows to dataset as they can differ slightly company by company.
for index, row in subset.iterrows():
    temp = pd.DataFrame(np.transpose(pd.io.json.json_normalize(subset.Financials[a:b], max_level = 4)))
    temp['symbol'] = (row['Symbol'])
    #print(subset['Symbol'][a:b])
    #IncomeStatements.append(temp)

    IncomeStatements = pd.concat([IncomeStatements, temp])

    print(row['Symbol'], " | ", a, end="\r")
    #print(a)

    a = a+1
    b = b+1

The data has the following structure and each row contains the financials and a stock symbol:

Picture of the desired result.

I have tried some other methods such as apply with little success and all the help would be much appreciated.


text:
Q: Как при повторном клике на элемент удалить его из массива? js
У меня есть две кнопки и нужно, чтобы когда я первый раз кликал по одной из них, атрибут этой кнопки добавлялся в массив, а при повторном клике удалялся. Мой код не работает, что здесь не так? Буду благодарен за подсказку

let buttonArr = [];
let buttons = document.querySelectorAll('.button');
for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', (event) => {
        let thisButton = event.currentTarget;
        let buttonAtr = JSON.parse(thisButton.getAttribute('data-info'));
        selectButton(buttonAtr);
    });
}

function selectButton(btn) {
    let index = buttonArr.indexOf(btn);

    if(index == -1) {
        buttonArr.push(btn);
    } else {
        buttonArr.splice(index, 1);
    }

    console.log(buttonArr);
}

A:

let buttonArr = [];
let buttons = document.querySelectorAll('.button');
for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', (event) => {
        let thisButton = event.currentTarget;
        let buttonAtr = JSON.parse(thisButton.getAttribute('data-info'));
        selectButton(buttonAtr);
    });
}

function selectButton(btn) {
    let btnString = JSON.stringify(btn),
        index = buttonArr.findIndex(obj => JSON.stringify(obj) == btnString);

    if(index === -1) {
        buttonArr.push(btn);
    } else {
        buttonArr.splice(index, 1);
    }

    console.log(buttonArr);
}
<button class="button" data-info='{"q": 1, "w": 2}'>1</button>
<button class="button" data-info='{"q": 21, "w": 22}'>2</button>

A: Так попробуйте
let buttonArr = [];
let buttons = document.querySelectorAll('.button');
for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', (event) => {
        let thisButton = event.currentTarget;
        let buttonAtr = thisButton.getAttribute('data-info');
        selectButton(buttonAtr);
    });
}

function selectButton(btn) {
    let index = buttonArr.indexOf(btn);

    if(index == -1) {
        buttonArr.push(btn);
    } else {
        buttonArr.splice(index, 1);
    }

    console.log(buttonArr);
}

либо напишите свой аналог
 buttonArr.indexOf(btn)

A: Если вы хотите написать это на JavaScript, я бы предложил использовать classList.toggle(). Вы можете посмотреть демонстрацию по ссылке.
<div class="button-container">
  <button data-info="foo">1</button>
  <button data-info="bar">2</button>
  <button data-info="baz">3</button>
</div>
<script>
(function() {

  const getSelectedButtons = () => document.querySelectorAll('.button-container > button.process');
  const getButtons = () => document.querySelectorAll('.button-container > button');
  const getContainer = () => document.querySelector('.button-container');

  getButtons().forEach((b) => b.onclick = () => b.classList.toggle('process'));
  getContainer().onclick = () => console.log(Array.from(getSelectedButtons()).map((b) => b.dataset.info));

})();
</script>


text:
Q: State is not showing up in Redux store I'm new to Redux, bare with me.
I'm working on a basic news app with TypeScript and React on the frontend, and Node.js and Express on the backend. I recently started integrating Redux into my app.
When a user logs in to my app, I'm currently redirecting them to their profile page (component). The profile component has a useEffect that will then call my backend API (with Thunk) to get the user and put it in the Redux store if it can't already find it there. The API returns the user object (I can verify in my terminal that the API is returning a user object), but the user never ends up in the store, and therefore I can't render any of their information. I'll attach all the relevant code in hopes that maybe someone can spot the problem.
authReucer.ts:
import { User } from "../../../../shared/User";
import {
  AuthDispatchTypes,
  USER_SUCCESS,
  USER_FAIL,
  USER_LOADING,
} from "../actions/authActionsTypes";

interface UserRes {
  user: User;
  status: number;
  authenticated: boolean;
}

export interface AuthState {
  loading: boolean;
  user?: UserRes;
  authenticated: boolean;
}

const defaultState: AuthState = {
  loading: false,
  authenticated: false,
};

const authReducer = (
  state: AuthState = defaultState,
  action: AuthDispatchTypes
): AuthState => {
  switch (action.type) {
    case USER_FAIL:
      return {
        loading: false,
        authenticated: false,
      };
    case USER_LOADING:
      return {
        loading: true,
        authenticated: false,
      };
    case USER_SUCCESS:
      return {
        loading: false,
        authenticated: true,
        user: action.payload,
      };
    default:
      return state;
  }
};

export default authReducer;

authActionTypes.ts:
import { User } from "../../../../shared/User";

export const USER_LOADING = "USER_LOADING";
export const USER_FAIL = "USER_FAIL";
export const USER_SUCCESS = "USER_SUCCESS";

interface UserLoading {
  type: typeof USER_LOADING;
}

interface UserFail {
  type: typeof USER_FAIL;
}

interface UserSuccess {
  type: typeof USER_SUCCESS;
  payload: {
    user: User;
    status: number;
    authenticated: boolean;
  };
}

export type AuthDispatchTypes = UserLoading | UserFail | UserSuccess;

authActions.ts:
import axios from "axios";
import { Dispatch } from "redux";
import {
  AuthDispatchTypes,
  USER_LOADING,
  USER_FAIL,
  USER_SUCCESS,
} from "./authActionsTypes";

export const setUser = () => async (dispatch: Dispatch<AuthDispatchTypes>) => {
  try {
    dispatch({
      type: USER_LOADING,
    });

    const res = await axios.get("auth/login/success");

    dispatch({
      type: USER_SUCCESS,
      payload: res.data,
    });
  } catch (error) {
    dispatch({
      type: USER_FAIL,
    });
  }
};

Profile.tsx:
import React, { useEffect, useState } from "react";
import { Navbar } from "../components/Navbar";
import { setUser } from "../store/actions/authActions";
import { useSelector, useDispatch } from "react-redux";
import { AuthState } from "../store/reducers/authReducer";

export const Profile = () => {
  const dispatch = useDispatch();
  const userState = useSelector<AuthState, AuthState["user"]>(
    (state) => state.user
  );
const authenticated = useSelector<AuthState, AuthState["authenticated"]>(
    (state) => state.authenticated
  );

useEffect(() => {
    // Check if there's a user authenticated but we dont yet have it
    if (userState === undefined && authenticated) {
      dispatch(setUser);
    }
  });

return (

      <Navbar
      //authenticated={authenticated}
      //handleNotAuthenticated={handleNotAuthenticated}
      />

Profile

{userState && userState.user.username}

{userState && userState.user.email}

Your News Sources

      {

        {user &&
          user.sources.map((source: any) => {
            return
{source.name}
;
          })}

 }

  );
};

index.ts:
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { createStore, Store, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import rootReducer from "./store/reducers/rootReducer";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";

const store: Store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export type RootStore = ReturnType<typeof rootReducer>;

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

reportWebVitals();


text:
Q: Reset button killed my control pad While not paying attention, I accidentally reset the new controller for our PlayStation.
Now, when I connect it with the cable, it displays the message 'unknown USB device connected'.
How can I fix this?


text:
Q: Create a simple tabbed ("multi page") application with python and GTK I hope someone can help me.
My Aim

*

*creating a simple multi paged GTK application with python

*pages should be switched by using a sidebar or a top bar

*each page should be able to contain multiple elements (e.g. a few buttons, labels, ...) arranged in a grid or something

My code so far (some copy&paste from free sources and some modifications)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class StackSidebar(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="application title")
        self.set_default_size(900, 600)
        self.connect("destroy", Gtk.main_quit)

        grid = Gtk.Grid()
        self.add(grid)

        stack = Gtk.Stack()
        stack.set_hexpand(True)
        stack.set_vexpand(True)
        grid.attach(stack, 1, 0, 1, 1)

        stacksidebar = Gtk.StackSidebar()
        stacksidebar.set_stack(stack)
        grid.attach(stacksidebar, 0, 0, 1, 1)

        label = Gtk.Label("label 1 text inside")
        name = "label1"
        title = "label 1 name"
        stack.add_titled(label, name, title)

        label = Gtk.Label("label 2 text inside")
        name = "label2"
        title = "label 2 name"
        stack.add_titled(label, name, title)

        label = Gtk.Label("label 3 text inside")
        name = "label3"
        title = "label 3 name"
        stack.add_titled(label, name, title)

window = StackSidebar()
window.set_wmclass ("application title", "application title")
window.show_all()

Gtk.main()

Result
Click link to see the running application
Problem
I am only able to see/create just one label within each page. See label = Gtk.Label("label 1 text inside"). As stated before, I would like to arrange a few buttons and so on but do not have any idea how to begin that.
Could you help? Is that even possible? Is my approach OK or should I use something like GtkNotebook? Thanks in advance.

A: Thanks for your help. I looked at GtkGrid and it works really well.
This is my solution (snippet)
# See initial post for previous code

grid2 = Gtk.Grid()

button1 = Gtk.Button(label="Button 1")
label1 = Gtk.Label("This is a test label")
button3 = Gtk.Button(label="Button 3")
button4 = Gtk.Button(label="Button 4")
button5 = Gtk.Button(label="Button 5")
button6 = Gtk.Button(label="Button 6")

grid2.add(button1)
grid2.attach(label1, 1, 0, 2, 1)
grid2.attach_next_to(button3, button1, Gtk.PositionType.BOTTOM, 1, 2)
grid2.attach_next_to(button4, button3, Gtk.PositionType.RIGHT, 2, 1)
grid2.attach(button5, 1, 2, 1, 1)
grid2.attach_next_to(button6, button5, Gtk.PositionType.RIGHT, 1, 1)

name = "page3"
title = "page3-title"
stack.add_titled(grid2, name, title)

# See initial post for next code

Result
Click link to see running application


text:
Q: Can I select a dynamically added p element with it's child button? I have the following dynamically added p element.  The enclosing div is in the DOM. I want to use the button to remove the p.

ADDED: John C Smith, Son <button class="remove_ben" type="button">REMOVE</button>

There are a lot of references (previous questions) here on how to use the .on method to add a click function to a dynamically added elements (like the button in my example).  But can't figure out how to have the function act on the parent element.  I know I could add the click function to the p itself and just have clicking anywhere on the p remove it, but that isn't what I want.  I just want the "REMOVE" text to be a click-to-remove button.
This code removes the button alone.
$('.prime_ben').on('click', 'button.remove_ben', function() {
    this.remove();
});

I'd like to use something like this:
$('.prime_ben').on('click', 'button.remove_ben', function() {
this.parent.remove();
});

I know it's not working because the parent p is undefined (not in the DOM). Is there a way to select parent or sibling elements to the element selected with the .on method?

A: You were almost there. you have attached the delegated event correctly and parent element exists when you are performing remove button click:
$('.prime_ben').on('click', 'button.remove_ben', function() {
  $(this).parent().remove();
});


text:
Q: Write query to export database to csv file via Microsoft SQL Server Management Studio I am trying to write a query that will export the data from a table into a csv file.  I cannot use the manual methods of right clicking the results and selecting save as.  It has to be via query.  I turned on the SQLCMD mode on my Managment Studio and am trying to run this cmd:
sqlcmd -S sqlbusServer -d hhhdb -E -Q "SELECT * FROM Table"
   -o "MyData.csv" -h-1 -s"," -w 700

in the above code sqlbusServer is the name of the server, and hhhdb is the database name.
I keep getting an error "Incorrect syntax near 'S'.  Am I correct in just putting in the server name and db name without any ',", or [ around it?

A: I'm a bit confused. The sqlcmd is a command line tool. You would execute that from a DOS prompt, not from SSMS.
It's been awhile since I used it, but your syntax looks correct though.

A: Try this:
:!!sqlcmd -S sqlbusServer -d hhhdb -E -Q "SELECT * FROM Table"
-o "FILEPATH\MyData.csv" -h-1 -s"," -w 700

I simply added :!! front of "sqlcmd" and a filepath in front of the document name.
Examples:
http://www.codeproject.com/Tips/1017732/SQL-Server-export-to-CSV


text:
Q: dynamically set table titles with jquery's Datatables plugin - get titles from data object Im searching for a way to set tables titles dynamically.
there's a search form that performs database queries, and gets a different data-set each time, according to user choice.
right now titles are hard-coded in the html.
this is how I set up the table:

      agentId
      confirmTime
      name
      amount
      currency
      amountUSD

      agentId
      confirmTime
      name
      amount
      currency
      amountUSD

javascript:
Api.getDeposits(formData).then(function(res){
  $('#searchResults').dataTable( {
      "data": res,
      "scrollX": "100%",
      "columns": [
          { "data": "agentId" },
          { "data": "confirmTime" },
          { "data": "name" },
          { "data": "amount" },
          { "data": "currency" },
          { "data": "amountUSD" }
      ]
  });
});

sample data:
[{
  "agentId": 70,
  "amount": 250,
  "amountUSD": 250,
  "confirmTime": "2015-04-28 10:49:00",
  "currency": "USD",
  "email": "name@mail.ru",
  "name": "some name",
  "paymentMethod": "Credit Card",
  "status": "approved"
}]

I'd like to set tfoot, thead, according to the data I get from the server,
so I only have one template for many situations

A: Well. Your question does not make completely sense. If you can hardcode columns, why cant you hardcode the titles? I mean, if the email field is static, then the title email would be static too?
Anyway, I think you wants both - a template where you can pass any JSON with any number of fields and titles / field names. The following template does that :

script :
$.getJSON('url/to/json/data', function(json) {
    var keys = Object.keys(json['data'][0]),
        columns = [];
    for (var i=0;i<keys.length;i++) {
        columns.push(
            { data: keys[i], title: keys[i] }
        );
    }
    var table = $('#example').DataTable({
        data : json.data,
        columns : columns
    });
});

This will take any JSON with any number of fields on the form { 'data' : [...] } and make it to a dataTable with field names as titles and field objects as data.
If your JSON is on the form
{ "agents": [
  {
    "agentId": 70,
    ...
  }, ...
]

then simply rename the data references to agents ;
$.getJSON('url/to/json/data', function(json) {
    var keys = Object.keys(json['agents'][0]),
        columns = [];
    for (var i=0;i<keys.length;i++) {
        columns.push(
            { data: keys[i], title: keys[i] }
        );
    }
    var table = $('#example').DataTable({
        data : json.agents,
        columns : columns
    });
});

if your JSON is a plain array [{ ... }, { ... }] then skip the data reference completely :
$.getJSON('url/to/json/data', function(json) {
    var keys = Object.keys(json[0]),
        columns = [];
    for (var i=0;i<keys.length;i++) {
        columns.push(
            { data: keys[i], title: keys[i] }
        );
    }
    var table = $('#example').DataTable({
        data : json,
        columns : columns
    });
});


text:
Q: I can't seem to see data from my database. I tried putting up data inside announcement table Query not producing a result:
 SELECT AnnouncementID,
 Announcement, Date_Posted, Employee.EmployeeID ,
 Employee.AccessLevel
 FROM Announcement
 INNER JOIN Employee on Announcement.AnnouncementID = Employee.EmployeeID;

EmployeeTable
Announcement Data

A: At the current moment without seeing your employee table if you use this query it should return a result
  SELECT AnnouncementID,
  Announcement, Date_Posted, Employee.EmployeeID ,
  Employee.AccessLevel
  FROM Announcement
  LEFT JOIN Employee on Announcement.AnnouncementID = Employee.EmployeeID;

You need something along the lines of this
 ALTER TABLE Employee
 ADD EmployeeFK int;

 ALTER TABLE Employee
 ADD FOREIGN KEY (EmployeeFK) REFERENCES Announcement(AnnouncementId);

Here is a very basic example of what you need but i advise you need to read up on foreign keys.
http://sqlfiddle.com/#!9/261e20/1
The announcementFK is a foreign key in the employee table that is linked to the announcementid in the announcement table. You can then join on these values.
e.g. the value is 1 in the announcement table and the value is 1 in the employee table so therefore these match and a result is returned. Sorry but its hard to explain over the internet...


text:
Q: fail2ban regex filter doesnt work with nginx log files I have been banging my head all day trying to match my regex filter to my access.log with no luck. I have installed fail2ban on a gentoo server and its running fine (i manually baned my own IP and it works) but fail2ban regex fails and return 0 results with filters even my site has heavyload attack right now and last coupleof days.

by the way i dont use iptables software on my server (do i need to install one in order for fail2ban to work?)
  i guess fail2ban cant read my logformat or my time format, i tried to tweak everything but no luck, any help is very very appreciated

Here is my jail.local
[INCLUDES]
before = paths-common.conf
[DEFAULT]
action=%(action_mwl)s
ignoreip = 127.0.0.1/8 192.168.99.25
ignorecommand =
bantime  = 86400
findtime  = 300
backend = gamin

[wp-login]
enabled = true
filter = wp-login
banaction=iptables-allports
logpath = /var/log/nginx/localhost*access_log
bantime = 7200
maxretry = 1

[nginx-nohome]
enabled=true
port=http,https
filter=nginx-nohome
logpath=/var/log/nginx/localhost.error.log
bantime=86400
maxretry=2

[nginx-dos]
enabled = true
port    = http,8090,8080
filter  = nginx-dos
logpath = /var/log/nginx/localhost.access*log
findtime = 30
bantime  = 172800
maxretry = 140

[nginx-login]
enabled = true
filter = nginx-login
action = iptables-multiport[name=NoLoginFailures, port="http,https"]
logpath = /var/log/messages
bantime = 7200
maxretry = 6

[nginx-req-limit]
enabled = true
filter = nginx-req-limit
action = iptables-multiport[name=ReqLimit, port="http,https", protocol=tcp]
logpath = /var/log/nginx/localhost.access*log
findtime = 600
bantime = 7200
maxretry = 10

and here is my filters:
[Definition]i
failregex = limiting requests, excess:.* by zone.*client: <HOST>

# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex =
~

[Definition]
failregex = ^<HOST> -.*GET */wp-login* HTTP/1\.."
ignoreregex =

#
[Definition]
failregex = ^<HOST> -.*GET.*(\.php|\.asp|\.exe|\.pl|\.cgi|\scgi)
ignoreregex =

[Definition]
failregex = ^<HOST> -.*GET .*/~.*
ignoreregex =
~

On nginx side, this is my log format syntax and output:
log format
 log_format main
 '[$time_local] - $remote_addr '
 '"$request" $status $bytes_sent '
 '"$http_referer" "$http_user_agent" ';

accesslog output:
[01/Oct/2015:09:15:52 +0800] - 60.18.17.206, 113.21.15.23 "POST/httprl_async_function_callback?count=121 HTTP/1.1" 200 1351 "-" "Drupal (+http://drupal.org/)" "-"

errorlog format:
2015/09/22 00:04:06 [error] 7418#0: *287 FastCGI sent in stderr: "Primary    scriptunknown", client: 192.168.99.76, server: www.sams.com, request: "GET/city HTTP/1.0", host: "www.sams.com"

UPDATE:
My site does not use wordpress but i am getting millions of wordpress related link link wp-login.php that i want to block,
there are many agressive malicious search bots, ads bots, spider also that breaks my server, i want to block

A: So it seems that you're not very familiar with regexes, you have a steep learning curve. The fail2ban utility uses python regexes, it's worth reading that page a little.
Part of the problem you are having is this part of your failregex
^<HOST>

This says look for the pre-defined <HOST> regex at the beginning of the line (or immediately after a newline), that's that the ^ is for.
Looking at your log examples they all begin with a date/time, this is removed by fail2ban before the regex is applied to the rest of the line. The line doesn't begin with anything that '^' would recognse so that's why your regex is failing.
A simple example using your errorlog entry. If you want to take action for scriptunknown errors (that may or may not be a good thing) you could use a failregex like
failregex= scriptunknown", clinet: <HOST>

You can test this by running it past your log file using fail2ban-regex(1) e.g.
fail2ban-regex /path/to/logfile 'scriptunknown", client: <HOST>'
Running tests
=============

Use   failregex line : scriptunknown", client: <HOST>
Use         log file : /path/to/logfile
Use         encoding : UTF-8

Results
=======

Failregex: 1 total
|-  #) [# of hits] regular expression
|   1) [1] scriptunknown", client: <HOST>
`-

Ignoreregex: 0 total

Date template hits:
|- [# of hits] date format
|  [1] Day(?P<_sep>[-/])MON(?P=_sep)Year[ :]?24hour:Minute:Second(?:\.Microseconds)?(?: Zone offset)?
|  [1] Year(?P<_sep>[-/.])Month(?P=_sep)Day 24hour:Minute:Second(?:,Microseconds)?
`-

Lines: 2 lines, 0 ignored, 1 matched, 1 missed [processed in 0.00 sec]
|- Missed line(s):
|  [01/Oct/2015:09:15:52 +0800] - 60.18.17.206, 113.21.15.23  "POST/httprl_async_function_callback?count=121 HTTP/1.1" 200 1351 "-" "Drupal (+http://drupal.org/)" "-"

Ok so that may do what you want but it may be too broad, you'd have to look at the results and make those calls.

by the way i dont use iptables software on my server (do i need to install one in order for fail2ban to work?)

You need some sort of firewall that is compatible with fail2ban installed and working on your system. As you tested it and

i manually baned my own IP and it works

Then I guess there is something there doing the job.


text:
Q: Match exact word and not match if there is a special symbol before I have a simple regex that matches exact substring in a string:
"\bXXX\b"

That works cool except 1 case.. if there is special symbol before XXX it matches substring:
This is ABC #XXX DEF

How I can adjust regex so it doesn't match #XXX?

A: If you only want to allow spaces as separators, I would go for
(^|(?<= ))XXX($|(?= ))

Explanation:

*

*(^|(?<= )): Start of the line (^) or a "positive lookbehind" on a space ((?<= )).

*($|(?= )): End of the line ($) or a "positive lookahead" on a space ((?= )).

The lookbehind/lookahead expressions ensure that the space itself is not part of the match.

A: The best way is to use a classical whitespace or space boundary.
Involves no alternations and is quicker.
(?<!\S)XXX(?!\S)
this will also match XXX at the beginning or end of string.
Also, it might be possible to make it just a space boundary
(?<![^ ])XXX(?![^ ])
this will also match XXX at beginning or end of string, but force
space char on either side or other side if not.


text:
Q: graphql get query shows this error "variables are not allowed in scalars" query describeNotesByNameSpaace($id:bigint!) {
notes(where: {object_meta: {_contains: {owner_references: [{uid:$id}]}}}) {
id
}
}

A: Use below code
query describeNotesByNameSpace($jsonFilter: jsonb) {
  notes(where: {object_meta: {_contains: $jsonFilter}}) {
    id
  }
}

And query variable is
{
  "jsonFilter": {
    "owner_references": [
        {
            "uid": "1719430910876008448"
        }
    ]
  }
}


text:
Q: Reversing a template list I have the following definiton of a list
 class List<T> {
        var value: T
        var next: List<T>?

       func printList()
        {
          var currentValue = value
          var nextNode = next
           print(currentValue)

          while (nextNode != nil)
          {

            currentValue = nextNode!.value
            print(currentValue)
            if(nextNode!.next == nil)
            {
              break;
            }
             nextNode = nextNode!.next

          }
        }
     }

and I wrote an extension to reverse the list like this :

extension List {
        func reverse() {

        var firstNode = self
         var previousNode: List<T>? = nil
        var currentNode = firstNode
        var nextNode = firstNode.next
        while nextNode != nil {
            currentNode.next = previousNode
            previousNode = currentNode
            currentNode = nextNode!
            nextNode = currentNode.next
        }
        currentNode.next = previousNode
        firstNode = currentNode

        }
    }

However when I tested out with sample list : var mylist = List<Int>(value:1,next :List<Int>(value:2,next:List<Int>(value:3 , next :nil)))
when I reverse it and print it , it just prints "1 nil" .Any idea why the reverse function does not work as expected?

A: Let's step through the code. I added the initializer that you left out:
init(value:T, next:List<T>?) {
    self.value = value
    self.next = next
}

And created a variable f to hold the list that you're using:
let f = List<Int>(value: 1, next: List(value: 2, next: List(value: 3, next: nil)))

so that f is now {value: 1, next:{value: 2, next:{value:3, next:nil}}}
Now let's look at what happens when we call reverse():
var firstNode = self
var previousNode: List<T>? = nil
var currentNode = firstNode
var nextNode = firstNode.next

OK, so:

*

*firstNode is the entire list

*previousNode is nil

*currentNode is again the entire list

*nextNode is the tail of the list (i.e. {value: 2, next:{value:3, next:nil}}).
while nextNode != nil {
    currentNode.next = previousNode
    previousNode = currentNode
    currentNode = nextNode!
    nextNode = currentNode.next
}

So after one iteration:

*

*currentNode.next will get nil, which means currentNode is now just {value: 1, next:nil}

*previousNode will get currentNode, so again, {value: 1, next:nil}

*currentNode will become {value: 2, next:{value:3, next:nil}}

*nextNode will get the tail of that, i.e. {value:3, next:nil}
After the second iteration:

*

*currentNode.next will get previousNode, which is {value: 1, next:nil}

*previousNode will get currentNode, so it's {value: 2, next:{value: 1, next:nil}}

*currentNode becomes {value 3:, next: nil}

*nextNode gets the tail again, i.e. nil.

The loop stops at that point, because nextNode is nil. The next two lines are:
    currentNode.next = previousNode
    firstNode = currentNode

So now currentNode.next becomes {value: 2, next:{value: 1, next:nil}}, and firstNode is {value 3:, next: nil}. So you've kinda/sorta succeeded in reversing the elements, but:
f.reverse()
f.printList()

still only prints 1. What gives?!
If you look at reverse(), you'll see that nothing that that code does changes the value field of any of the lists involved. Only the next field gets changed, and the next of f got set to nil in that first iteration through the list, when currentNode.next was set to nil. So when you print f, printList() prints out just 1 and then stops.
To solve the problem, you need to address the value fields of each of the sub-lists, not just the next.


text:
Q: I'm trying to make sure my string has only valid UTF-8 characters in PHP. How can I do that?
Possible Duplicate:
PHP: replace invalid characters in utf-8 string in

I have a string that has an invalid character in it (it's not UTF-8) such as the following displaying SUB:

I think it's some kind of foreign invalid character.
Is there a way in PHP to take a string and use preg_replace or something else to ensure that I am only using valid UTF-8 characters in my strings, and anything else just gets removed?
Thanks.

A: First of all, there is no invalid UTF-8 characters. There are invalid UTF-8 bytes and byte sequences, which means someone is trying to pull off an encoding attack on your server. These can be validated with mb_check_encoding on the coming input data, and immediately failing with 400 Bad Request if you don't get valid UTF-8.
What you have is just the SUBSTITUTE control character, a valid character but unprintable.

Originally intended for use as a transmission control character to
  indicate that garbled or invalid characters had been received. It has
  often been put to use for other purposes when the in-band signaling of
  errors it provides is unneeded, especially where robust methods of
  error detection and correction are used, or where errors are expected
  to be rare enough to make using the character for other purposes
  advisable.

You can use this regex to get rid of it (and a few others):
$reg = '/(?![\r\n\t])[\p{Cc}]/u';

preg_replace( $reg, "", $str );

A: The mb_check_encoding function should be able to do this.
mb_check_encoding("Jetzt gibts mehr Kanonen", "UTF-8");

Note: I haven't tested this.


text:
Q: What's an efficient algorithm to make one list equal to another one? Let's say I have a list A that needs to look exactly like list B. All the objects that B has but A does not have need to be added to A. And all the objects that A has but not B, need to be removed from A.
The reason why I need this is because I have an ArrayList of Players that I'm saving to a file. Every time I update an attribute of a Player, I save the changes to the file by calling a method that looks to the ArrayList of Players and saves it. This works because the ArrayList has the references to the Players.
However, whenever I search for a Player in the list, I first update the list by reading the file where its stored. This replaces all the references with whole new objects. After I do this, if I make a change to a previously fetched user and try to save it. The new instance of the Player gets saved instead of the one I made the changes in.
Would coming up with a good algorithm to make a list equal to another the solution? Or is there a better way to update an entire list while keeping references in use there?
UPDATE: Updated solution, runs in O(nlogm) time. Loops through each element in destination, searches for it in source. If it's found, removed from source. If not, removed from destination. Then add remaining elements in source to destination. List needs to be sorted of course, but the list that I get from the file will already be sorted because I sort as I add.
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CopyList {
    public static void copyList(List dest, List src) {
        copy(dest, src);

        // the remaining elements in src list will be those that were originally
        // in src but not in dest and so they need to be added
        dest.addAll(src);
    }

    public static void copyList(List dest, List src, Verify v) {
        copy(dest, src);

        // the remaining elements in src list will be those that were originally
        // in src but not in dest and so they need to be added
        addAll(dest, src, v);
    }

    public static void copyList(List dest, List src, Comparator c) {
        copy(dest, src, c);

        // the remaining elements in src list will be those that were originally
        // in src but not in dest and so they need to be added
        dest.addAll(src);
    }

    public static void copyList(List dest, List src, Comparator c, Verify v) {
        copy(dest, src, c);

        // the remaining elements in src list will be those that were originally
        // in src but not in dest and so they need to be added
        addAll(dest, src, v);
    }

    private static void copy(List dest, List src) {
        // go through dest list to search if every element is in the new list
        // travel backwards through dest because we will be removing elements from it
        for(int i = dest.size()-1; i >= 0 ; i--) {
            int src_i = Collections.binarySearch(src, dest.get(i));
            if(src_i >= 0)
                // if element is found in src list, remove it from src list
                src.remove(src_i);
            else
                // if element is NOT found in src list, remove it from dest list
                dest.remove(i);
        }
    }

    private static void copy(List dest, List src, Comparator c) {
        // go through dest list to search if every element is in the new list
        // travel backwards through dest because elements might be removed
        for(int i = dest.size()-1; i >= 0 ; i--) {
            int src_i = Collections.binarySearch(src, dest.get(i), c);
            if(src_i >= 0)
                // if element is found in src list, remove it from src list
                src.remove(src_i);
            else
                // if element is NOT found in src list, remove it from dest list
                dest.remove(i);
        }
    }

    private static void addAll(List dest, List src, Verify v) {
        // verify each element in src list before adding it to dest list
        for(Object o: src)
            if(v.verify(o))
                dest.add(o);
    }
}

A: Wouldn't the simplest solution be to create a copy of list B?  This would only involve creating a copy of the underlying array which would require much less time and effort than a complicated algorithm (not to mention much easier to maintain).

A: I'd step back and think about the design of your program. It sounds like it would be more reasonable to have a class that manages all your Players -- saving them, updating them, handing out references to them. Then just don't hold a reference to a Player anywhere else, hold a reference to your PlayerManager (or whatever you want to call it), and query it to get Players.
This will give you one canonical list, and you won't need to worry about out-of-date references.

A:
However, whenever I search for a Player in the list, I first update the list by reading the file where its stored.

Why are you doing this? It would make much more sense to search the in-memory copy.
Oh, and there's a really easy way to make a contain the same things as b:
a = b;

A: I agree with the other submission here that this seems unnecessary for your application, but out of interest if you want an algorithm that does what you describe in better than n^2 time, there is one (and it runs in n*log n time)
sort list users (n log n)
sort list new_users (n log n)
iterate through users and new_users in parallel, adding or removing items from users as necessary ( n )

A: Did you consider using HashSet for your lists? This way you can just do addAll() and have a union of these lists. Use LinkedHashSet if you want to preserve original order. Would be much faster. You'd just have to override hashCode() in Player class to return hash of their name.

A: Your program would be faster if you used sets instead of lists i.e. O(1) time complexity assuming no hash collisions.
for(User u : new_users) {
    if (!users.contains(u)) {
        users.add(u);
    }
}
for(User u : users) {
    if (!new_users.contains(u)) {
        users.remove(u);
    }
}


text:
Q: Representing a chain of nodes in a human readable way I'm trying to represent a subway map type thing that has to be drawn progressively (like its growing).
My code all works perfectly but its unreadable. Basically it's a tree structure with recursive nodes and subnodes and my test code looks like this:
        Children.Add(new TrackLine(800));
        Children[0].Children.Add(new TrackSpot());
        Children[0].Children[0].Children.Add(new TrackSplitter());

        Children[0].Children[0].Children[0].Children.Add(new TrackRotate(-45));
        Children[0].Children[0].Children[0].Children[0].Children.Add(new TrackColorChange(Color.Red));
        Children[0].Children[0].Children[0].Children[0].Children[0].Children.Add(new TrackLine(100));
        Children[0].Children[0].Children[0].Children[0].Children[0].Children[0].Children.Add(new TrackRotate(45));
        Children[0].Children[0].Children[0].Children[0].Children[0].Children[0].Children[0].Children.Add(new TrackLine(200));

Does anyone have any suggestions of how to fix that mess?

A: You're looking for a way to add it to the deepest child that has no children of it's own?
class Node
{
  List<Node> children ;

  public void addNode( Node newNode )
  {
    if( children.Count > 0 )
      children[0].addNode( newNode ) ; // recursive call
      // to ask first child to add newNode to it
    else
      children.Add( newNode ) ;        // just add it to the children list of THIS node
  }
}

A: To make that code more readable I'd use variables with appropriate names (since I don't know your subject domain, mine are probably not appropriate):
Children.Add(new TrackLine(800));
var lineA = Children[0];

lineA.Children.Add(new TrackSpot());
var spotA = lineA.Children[0];

spotA.Children.Add(new TrackSplitter());
var splitterA = spotA.Children[0];

splitterA.Children.Add(new TrackRotate(-45));
var rotateNeg45 = splitterA.Children[0];

rotateNeg45.Children.Add(new TrackColorChange(Color.Red));
var colorRed = rotateNeg45.Children[0];

colorRed.Add(new TrackLine(100));
var lineB = colorRed.Children[0];

lineB.Children.Add(new TrackRotate(45));
var rotatePos45 = lineB.Children[0];

rotatePos45.Children.Add(new TrackLine(200));
var lineC = rotatePos45.Children[0];

Another approach is to use strings as indexes for Children like this:
    Children.Add(new TrackLine(800));
    Children["lineA"].Children.Add(new TrackSpot());
    Children["lineA"].Children["spotA"].Children.Add(new TrackSplitter());

However I probably would not do it because managing the string constants would be a mess on its own and it would probably require changing Children implementation.


text:
Q: Using PHP variables within echo quoted string? How can I use ucwords($firstname) within echo ""? ie
<?php
$firstname = "john";
$surname = "smith";
echo "Welcome ucwords($firstname) ucwords($surname)";
?>

A: <?php
$firstname = "john";
$surname = "smith";
echo "Welcome " . ucwords($firstname) . " " .  ucwords($surname);
?>

Like this.

A: echo "Welcome" .  ucwords($firstname) . " " . ucwords($surname);

EDIT:
Alternative pattern:
$firstname = ucwords($firstname);
$surname = ucwords($surname);

echo 'Welcome $firstname $surname';

A: Like this:
<?php
$firstname = "john";
$surname = "smith";
echo "Welcome " . ucwords($firstname) . " " . ucwords($surname);
?>

or this:
<?php
$firstname = "john";
$surname = "smith";
$format = "Welcome %s %s";
printf($format, ucwords($firstname), ucwords($surname));
?>

A: echo "Welcome " . ucwords($firstname) . " " . ucwords($surname);

A: It's hacky in the extreme, but you can use variable functions for this:
$uc = 'ucwords';
$firstname = 'fred';
$lastname = 'jones';

echo "Welcome {$uc($firstname)} {$uc($lastname)}";

A: PHP Script:
<?php
$firstname = 'john';
$surname = 'smith';
//Use of single quote instead double is an optimize way
echo 'Welcome '.ucwords($firstname).' '.ucwords($surname);
?>

Output:
Welcome John Smith
Reference


text:
Q: Android - can't clip rect after rotation I'm trying to create custom drawable and in the draw(Canvas) function I use the methods: clipRect and rotate.
The clipRect working alone but if the rotate function ran before, the clipRect does nothing.

*

*It works on devices with android 6 and some of the devices with other android versions.


text:
Q: QMake Uses Wrong Directory For 32 Bit Build All I am attempting to compile a 32 bit build on a 64 bit 13.04 ubuntu.
I have installed the correct multiarch g++ libs and the ia32-libs package. I can see the .so's I need in /usr/lib/i386-linux-gnu and /lib32/
My approach so far:
export QMAKESPEC=linux-g++-32
qmake myproject.pro
make

I have noticed that I am compiled with the -m32 flag, however when it comes to link time, I see /usr/lib/x86_64-linux-gnu. This is not being set from any of the .pro files, I confirmed with a quick
grep -r 'x86_64-linux-gnu' <src>

I feel like I'm missing a flag somewhere, or maybe it's using the wrong g++ and I need to adjust the link? I can't find any information on this.

Link call:
g++ -m32 -Wl,-O1 -o output [redacted.o] -L/[some_lib_dir] -L/usr/lib/x86_64-linux-gnu -lQtCore -lpthread

A: I had to switch to Ubuntu 32 bit. I determined the problem is that qmake does not let you set the link directories for its core plugin libraries.
Other people interested in researching look into:
qmake -query
qmake -set QT_INSTALL_PATH

That seems to be the link directory being used, but I was unable to specify my own unqiue directory.


text:
Q: Sliding Menu with Child Extends Tab Activity in android How to use sliding menu with child which extends tab activity,i.e., child contains tab layout..  I know how to implement sliding menu but problem is child need to extends both tab activity for tab and base activity for sliding menu.
1.BaseActivity for sliding menu:

public class BaseActivity extends Activity {
 SharedPreferences pre;
 Editor editor;
 static int dbcount;
 SQLiteDatabase db, db1;
 String url;
 static TextView tv;
 String status, response;

 protected FrameLayout frameLayout;
 protected ListView mDrawerList;
 protected String[] listArray = { "Veg Starters","Veg Burgers",
  "Non-Veg Starters","Non-Veg Burgers","Veg Wraps","Non-Veg Wraps" };
 protected static int position;
 private DrawerLayout mDrawerLayout;

@SuppressWarnings("deprecation")
private ActionBarDrawerToggle actionBarDrawerToggle;

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

    // Shared pref
    pre = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());

    // create database if not already exist
    db = openOrCreateDatabase("Mydb", MODE_PRIVATE, null);
    // create new table if not already exist
    db.execSQL("create table if not exists pendingdatatbl(Id integer
      primary key autoincrement,Siteid varchar, ToggleStatus
      varchar, ImagePath varchar,LoginTime varchar,LogoutTime
      varchar,LatLong varchar)");

    dbcount = (int) DatabaseUtils.queryNumEntries(db,
          "pendingdatatbl");
    //Database d = new Database();

    frameLayout = (FrameLayout) findViewById(R.id.content_frame);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.sidemenu_item, listArray));
    mDrawerList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            mDrawerList.getChildAt(position).setBackgroundColor(
                    Color.parseColor("#ff5722"));
            openActivity(position);
        }
    });

    // disable ActionBar app icon to behave as action to toggle nav
           //drawer
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setDisplayShowHomeEnabled(false);
    getActionBar().setHomeButtonEnabled(true);

    // orange color of action bar
    android.app.ActionBar bar = getActionBar();
    bar.setBackgroundDrawable(new
           ColorDrawable(Color.parseColor("#ff5722")));

    // ActionBarDrawerToggle ties together the the proper
          interactions
    // between the sliding drawer and the action bar app icon
    actionBarDrawerToggle = new ActionBarDrawerToggle(this,
    mDrawerLayout,
    R.drawable.ic_launcher,
    R.string.open_drawer,
    R.string.close_drawer)
    {
        @Override
        public void onDrawerClosed(View drawerView) {
            getActionBar().setTitle(listArray[position]);
            invalidateOptionsMenu();
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(getString(R.string.app_name));
            invalidateOptionsMenu();
            super.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerSlide(View drawerView, float
             slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            super.onDrawerStateChanged(newState);
        }
    };
    mDrawerLayout.setDrawerListener(actionBarDrawerToggle);

        isLaunch = false;
        openActivity(0);

    }
  }

protected void openActivity(int position) {

    mDrawerLayout.closeDrawer(mDrawerList);
    BaseActivity.position = position;

    switch (position) {
    case 0:
        startActivity(new Intent(this, AndroidTabAndListView.class));
        break;
    case 1:

        startActivity(new Intent(this, tab2.class));

        break;

    case 2:
        startActivity(new Intent(this, tab3.class));
        break;

    default:
        break;
    }

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (actionBarDrawerToggle.onOptionsItemSelected(item)) {

        return true;

    }

    switch (item.getItemId()) {

    default:
        return super.onOptionsItemSelected(item);
    }

}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);

    return super.onPrepareOptionsMenu(menu);

}

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        dialogOnBackPress();
        return true;
    }
    return super.onKeyDown(keyCode, event);
    }

protected void dialogOnBackPress() {

    new AlertDialog.Builder(BaseActivity.this)
            .setMessage("Are you sure you want to exit?")
            .setCancelable(false)
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int id) {
                            BaseActivity.this.finish();

                            Intent intent = new
                       Intent(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    }).setNegativeButton("No", null).show();

             }

    return super.onCreateOptionsMenu(menu);
   }

 2.Tab Activity class and child class of sliding menu(But here i
              need extend BaseActivity also) :

public class AndroidTabAndListView extends TabActivity{
// TabSpec Names
  private static final String INBOX_SPEC = "Inbox";
  private static final String OUTBOX_SPEC = "Outbox";
  private static final String PROFILE_SPEC = "Profile";
  static TextView tvNewNotifications;
  @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TabHost tabHost = getTabHost();

    // Inbox Tab
    TabSpec inboxSpec = tabHost.newTabSpec("Menu");
    // Tab Icon
    inboxSpec.setIndicator("Menu",
       getResources().getDrawable(R.drawable.ic_action_list_2));
    Intent inboxIntent = new Intent(this, InboxActivity.class);
    // Tab Content
    inboxSpec.setContent(inboxIntent);

    // Outbox Tab
    TabSpec outboxSpec = tabHost.newTabSpec("Search");
    outboxSpec.setIndicator("Search",
       getResources().getDrawable(R.drawable.ic_action_search));
    Intent outboxIntent = new Intent(this, OutboxActivity.class);
    outboxSpec.setContent(outboxIntent);

    LayoutInflater inflater = (LayoutInflater)
         getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View chatTab = inflater.inflate(R.layout.cart_count, null);

    // Profile Tab
    TabSpec profileSpec = tabHost.newTabSpec("Account");
    profileSpec.setIndicator("Account",
       getResources().getDrawable(R.drawable.ic_action_user));
    Intent profileIntent = new Intent(this, ProfileActivity.class);
    profileSpec.setContent(profileIntent);

    // Adding all TabSpec to TabHost
    tabHost.addTab(inboxSpec); // Adding Inbox tab
    tabHost.addTab(outboxSpec); // Adding Outbox tab
    tabHost.addTab(profileSpec); // Adding Profile tab
    for(int i=0;i<3;i++){

     tabHost.getTabWidget().getChildAt(i).setBackgroundColor(
        Color.parseColor("#f50057"));

     }

}

}
Sliding Menu:

Tab menu:


text:
Q: How to remove array of words from a sentence? I have an array of stop words:
myArray = ["","a","ago","also","am","an","and","ani","ar","aren't","arent","as","ask","at","did","didn't","didnt","do","doe","would","be","been","best","better"]
I would like to remove matching items from a sentence:
str = 'A something and hello'
So it becomes:
'something hello'
1. How can I do that in ruby?
2. How could I also do it for an array of characters (which removes all matching characters)?
Here's the array of characters:
["(",")","@","#","^"]

A: sentence = 'A something and hello'
array  = ["","a","ago","also","am","an","and","ani","ar","aren't","arent",
          "as","ask","at","did","didn't","didnt","do","doe","would",
          "be","been","best","better"]

sentence.split.delete_if{|x| array.include?(x)}.join(' ')

 => "A something hello"

you might want to downcase all words before comparison, to get rid of the "A" in the beginning of the sentence:
sentence.split.delete_if{|x| array.include?(x.downcase)}.join(' ')

 => "something hello"

if you have an array of strings, it's easier:
(sentence.split - array).join(' ')
=> "A something hello"    #  but note that this doesn't catch the "A"

to also delete the special characters:
special = ["(",")","@","#","^"]

sentence.split.delete_if{|x| array.include?(x.downcase) || special.include?(x) }.join(' ')

another approach to delete words or phrases is:
array.each do |phrase|
  sentence.gsub!(/#{phrase}/,'')
end

A: A one-line variant of Tilo's answer that is clean and case-insensitive (although it returns all lowercase output, which may not be ideal for all uses):
(sentence.downcase.split - array).join(' ')

A:  array.map {|s| s.gsub(keyword, '')}

A: My solution:
stop_words = ["","a","ago","also","am","an","and","ani","ar","aren't","arent","as","ask","at","did","didn't","didnt","do","doe","would","be","been","best","better"]
output = %w(A something and hello) - stop_words


text:
Q: Not able to click a sign in button using selenium webdriver? Here is what inspect element option in chrome has found.
<input class="buttonstylenormal margin-top5" type="submit" value="Sign In" onclick="return isFirstClick()">

It is not having ID in it, which would have made my work easier. All I have now is class, value and type. With these I am not able to click the button Sign In.
Please help me with the right code to click this button.

A: You can use XPath, as @jainish said, or try to use CssSelector, that uses the same syntax that CSS has to apply styles.
To find it using CssSelector, you can use a few variations:
driver.findElement(By.cssSelector("input[type='submit']"))

or
driver.findElement(By.cssSelector("input.buttonstylenormal.margin-top5"))

or
driver.findElement(By.cssSelector("input.buttonstylenormal.margin-top5[type='submit']"))

CssSelector may help you even in other elements you'd like to find that do not have an ID.
Hope it's somehow helpful.

A: Try this below xpath.
Explanation: Use value attribute of input tag.
 //input[@value='Sign In']

OR
Explanation: Use class and value attribute of input tag.
//input[@class='buttonstylenormal margin-top5'][@value='Sign In']

OR
Explanation: Use class and type attribute of input tag.
//input[@class='buttonstylenormal margin-top5'][@type='submit']