text:
Q: Why should I use dependency injection? I am having a hard time looking for resources on why I should use dependency injection. Most of the resources that I see explains that it just passes an instance of an object to another instance of an object, but why? Is this just for cleaner architecture/code or does this affect performance as a whole?
Why should I do the following?
class Profile {
    public function deactivateProfile(Setting $setting)
    {
        $setting->isActive = false;
    }
}

Instead of the following?
class Profile {
    public function deactivateProfile()
    {
        $setting = new Setting();
        $setting->isActive = false;
    }
}

A: The example you give is not dependency injection in the classical sense. Dependency injection usually refers to passing objects in a constructor or by using "setter injection" just after the object is created, in order to set a value on a field in a newly created object.
Your example passes an object as an argument to an instance method. This instance method then modifies a field on that object. Dependency injection? No. Breaking encapsulation and data hiding? Absolutely!
Now, if the code was like this:
class Profile {
    private $settings;

    public function __construct(Settings $settings) {
        $this->settings = $settings;
    }

    public function deactive() {
        $this->settings->isActive = false;
    }
}

Then I would say you are using dependency injection. The notable difference is a Settings object being passed in to the constructor or a Profile object.
This is useful if the Settings object is expensive or complex to construct, or Settings is an interface or abstract class where multiple concrete implementations exist in order to change run time behavior.
Since you are directly accessing a field on the Settings object rather than calling a method, you can't take advantage of Polymorphism, which is one of the benefits of dependency injection.
It looks like the Settings for a Profile are specific to that profile. In this case I would do one of the following:

*

*Instantiate the Settings object inside the Profile constructor

*Pass the Settings object in the constructor and copy over individual fields that apply to the Profile
Honestly, by passing the Settings object in to deactivateProfile and then modifying an internal field of the Settings object is a code smell. The Settings object should be the only one modifying its internal fields.

A: I know I'm coming late to this party but I feel an important point is being missed.

Why should I do this:

class Profile {
    public function deactivateProfile(Setting $setting)
    {
        $setting->isActive = false;
    }
}

You shouldn't. But not because Dependency Injection is a bad idea. It's because this is doing it wrong.
Lets look at this things using code. We're going to do this:
$profile = new Profile();
$profile->deactivateProfile($setting);

when we get about the same thing out of this:
$setting->isActive = false; // Deactivate profile

So of course it seems like a waste of time. It is when you do it this way. This is not the best use of Dependency Injection. It's not even the best use of a class.
Now what if instead we had this:
$profile = new Profile($setting);

$application = new Application($profile);

$application.start();

And now the application is free to activate and deactivate the profile without having to know anything in particular about the setting that it's actually changing. Why is that good? In case you need to change setting. The application is walled off from those changes so you're free to go nuts in a safe contained space without having to watch everything break as soon as you touch something.
This follows the separate construction from behavior principle. The DI pattern here is a simple one. Build everything you need at as low a level as you can, wire them together, then start all the behavior ticking with one call.
The result is you have a separate place to decide what connects to what and a different place to manage what says what to whatever.
Try that on something you have to maintain over time and see if it doesn't help.

A: Dependency Injection makes your code easier to test.
I learned this first-hand when I was tasked with fixing a hard-to-catch bug in Magento's PayPal integration.
An issue would arise when PayPal was telling Magento about a failed payment: Magento wouldn't register the failure properly.
Testing a potential fix "manually" would be very tedious: you'd need to somehow trigger a "Failed" PayPal notification. You'd have to submit an e-check, cancel it, and wait for it to error out. That means 3+ days to test a one-character code change!
Luckily, it appears that the Magento core devs who developed this function had testing in mind, and used a dependency injection pattern to make it trivial. This allows us to verify our work with a simple test case like this one:
<?php
// This is the dependency we will inject to facilitate our testing
class MockHttpClient extends Varien_Http_Adapter_Curl {
    function read() {
        // Make Magento think that PayPal said "VERIFIED", no matter what they actually said...
        return "HTTP/1.1 200 OK\n\nVERIFIED";
    }
}

// Here, we trick Magento into thinking PayPal actually sent something back.
// Magento will try to verify it against PayPal's API though, and since it's fake data, it'll always fail.
$ipnPayload = array (
  'invoice'        => '100058137',         // Order ID to test against
  'txn_id'         => '04S87540L2309371A', // Test PayPal transaction ID
  'payment_status' => 'Failed'             // New payment status that Magento should ingest
);

// This is what Magento's controller calls during a normal IPN request.
// Instead of letting Magento talk to PayPal, we "inject" our fake HTTP client, which always returns VERIFIED.
Mage::getModel('paypal/ipn')->processIpnRequest($ipnPayload, new MockHttpClient());

I'm sure the DI pattern has plenty of other advantages, but increased testability is the single biggest benefit in my mind.
If you're curious about the solution to this problem, check out the GitHub repo here: https://github.com/bubbleupdev/BUCorefix_Paypalstatus

A: As a customer, when you hire a mechanic to do something to your car, do you expect that mechanic to build a car from scratch only to then work with it? No, you give the mechanic the car you want them to work on.
As the garage owner, when you instruct a mechanic to do something to a car, do you expect the mechanic to create his own screwdriver/wrench/car parts? No, you provide the mechanic with the parts/tools he needs to use
Why do we do this? Well, think about it. You're a garage owner who wants to hire someone to become your mechanic. You will teach them to be a mechanic (= you will write the code).
What's going to be easier:

*

*Teach a mechanic how to attach a spoiler to a car using a screwdriver.

*Teach a mechanic to create a car, create a spoiler, created a screwdriver
and then attach the newly created spoiler to the newly created car with the newly created screwdriver.

There are massive benefits to not having your mechanic create everything from scratch:

*

*Obviously, training (= development) is dramatically shortened if you just supply your mechanic with existing tools and parts.

*If the same mechanic has to perform the same job multiple times, you can make sure he reuses the screwdriver instead of always throwing the old one out and creating a new one.

*Additionally, a mechanic who has learned to create everything will need to be much more of an expert, and thus will expect a higher wage. The coding analogy here is that a class with many responsibilities is much harder to maintain than a class with a single strictly defined responsibility.

*Additionally, when new inventions hit the market and spoilers are now being made from carbon instead of plastic; you will have to retrain (= redevelop) your expert mechanic. But your "simple" mechanic won't have to be retrained as long as the spoiler can still be attached in the same way.

*Having a mechanic who doesn't rely on a car that they've built themselves means that you have a mechanic who is able to handle any car they may receive. Including cars that didn't even exist yet at the time of training the mechanic. However, your expert mechanic will not be able to build newer cars that have been created after their training.

If you hire and train the expert mechanic, you're going to end up with an employee who costs more, takes more time to perform what ought to be a simple job, and will perpetually need to be retrained whenever one of their many responsibilities need to be updated.
The development analogy is that if you use classes with hardcoded dependencies, then you're going to end up with hard to maintain classes which will need continual redevelopment/changes whenever a new version of the object (Settings in your case) is created, and you'll have to develop internal logic for the class to have the ability to create different types of Settings objects.
Furthermore, whoever consumes your class is now also going to have to ask the class to create the correct Settings object, as opposed to simply being able to pass the class any Settings object it wishes to pass. This means additional development for the consumer to figure out how to ask the class to create the right tool.

Yes, dependency inversion takes a bit more effort to write instead of hardcoding the dependency. Yes, it's annoying to have to type more.
But that is the same argument as choosing to hardcode literal values because "declaring variables takes more effort". Technically correct, but the pro's outweigh the cons by several orders of magnitude.
The benefit of dependency inversion is not experienced when you create the first version of the application. The benefit of dependency inversion is experienced when you need to change or extend that initial version. And don't trick yourself into thinking that you will get it right the first time and won't need to extend/change the code. You will have to change things.

does this affect performance as a whole?

This does not affect runtime performance of the application. But it massively impacts the development time (and therefore performance) of the developer.

A: Why (what's even the issue)?

Why should I use dependency injection?

The best mnemonic I found for this is "new is glue": Every time you use new in your code, that code is tied down to that specific implementation. If you repeatedly use new in constructors, you will create a chain of specific implementations. And because you can't "have" an instance of a class without constructing it, you can't separate that chain.
As an example, imagine you're writing a race car video game. You started with a class Game, which creates a RaceTrack, which creates 8 Cars, which each create a Motor. Now if you want 4 additional Cars with a different acceleration, you will have to change every class mentioned, except maybe Game.
Cleaner code

Is this just for cleaner architecture/code

Yes.
However, it might very well seem less clear in this situation, because it's more an example of how to do it. The actual advantage only shows when several classes are involved and is more difficult to demonstrate, but imagine you would have used DI in the previous example. The code creating all those things might look something like this:
List<Car> cars = new List<Car>();
for(int i=0; i<8; i++){
    float acceleration = 0.3f;
    float maxSpeed = 200.0f;
    Motor motor = new Motor(acceleration, maxSpeed);
    Car car = new Car(motor);
    cars.Add(car);
}
RaceTrack raceTrack = new RaceTrack(cars);
Game game = new Game(raceTrack);

Adding those 4 different cars can now be done by adding these lines:
for(int i=0; i<4; i++){
    float acceleration = 0.5f;
    float maxSpeed = 100.0f;
    Motor motor = new Motor(acceleration, maxSpeed);
    Car car = new Car(motor);
    cars.Add(car);
}

*

*No changes in RaceTrack, Game, Car, or Motor were necessary - which means we can be 100% sure that we did not introduce any new bugs there!

*Instead of having to jump between several files, you will be able to see the complete change on your screen at the same time. This is a result of seeing creation/setup/configuration as an own responsibility - it's not the job of a car to build a motor.

Performance considerations

or does this affect performance as a whole?

No. But to be completely honest with you, it might.
However, even in that case, it's such a ridiculously small amount that you don't need to care. If at some point in the future, you have to write code for a tamagotchi with the equivalent of 5Mhz CPU and 2MB RAM, then maybe you might have to care about this.
In 99.999%* of cases it will have a better performance, because you spent less time fixing bugs and more time improving your resource-heavy algorithms.
*completely made up number
Added info: "hard-coded"
Make no mistake, this is still  very much "hard-coded" - the numbers are written directly in the code. Not hard-coded would mean something like storing those values in a text file - e.g. in JSON format - and then reading them from that file.
In order to do that, you have to add code for reading a file and then parsing JSON. If you consider the example again; in the non-DI version, a Car or a Motor now has to read a file. That doesn't sound like it makes too much sense.
In the DI version, you would add it to the code setting up the game.

A: I was always baffled by dependency injection.  It seemed to only exist within Java spheres, but those spheres spoke of it with great reverence.  It was one of the great Patterns, you see, which are said to bring order to chaos.  But the examples were always convoluted and artificial, establishing a non-problem and then setting out to solve it by making the code more complicated.
It made more sense when a fellow Python dev imparted to me this wisdom: it's just passing arguments to functions.  It's barely a pattern at all; more like a reminder that you can ask for something as an argument, even if you could have conceivably provided a reasonable value yourself.
So your question is roughly equivalent to "why should my function take arguments?" and has many of the same answers, namely: to let the caller make decisions.
This comes with a cost, of course, because now you're forcing the caller to make some decision (unless you make the argument optional), and the interface is somewhat more complex.  In exchange, you gain flexibility.
So: Is there a good reason you specifically need to use this particular Setting type/value?  Is there a good reason calling code might want a different Setting type/value?  (Remember, tests are code!)

A: The advantage is that without dependency injection, your Profile class

*

*needs to know how to create a Settings object (violates Single Responsibility Principle)

*Always creates its Settings object the same way (creates a tight coupling between the two)

But with dependency injection

*

*The logic for creating Settings objects is somewhere else

*It's easy to use different kinds of Settings objects

This may seem (or even be) irrelevant in this particular case, but imagine if we're not talking about a Settings object, but a DataStore object, which might have different implementations, one that stores data in files and another that stores it in a database. And for automated tests you want a mock implementation as well. Now you really don't want the Profile class to hardcode which one it uses - and even more importantly, you really, really don't want the Profile class to know about filesystem paths, DB connections and passwords, so the creation of DataStore objects has to happen somewhere else.

A: Like all patterns, it is very valid to ask "why" to avoid bloated designs.
For dependency injection, this is easily seen by thinking of the two, arguably, most important facets of OOP design...
Low coupling
Coupling in computer programming:

In software engineering, coupling is the degree of interdependence between software modules; a measure of how closely connected two routines or modules are; the strength of the relationships between modules.

You want to achieve low coupling. Two things being strongly coupled means that if you change the one, you very likely have to change the other. Bugs or restrictions in the one likely will induce bugs/restrictions in the other; and so on.
One class instantiating objects of the others is a very strong coupling, because the one needs to know about the existence of the other; it needs to know how to instantiate it (which arguments the constructor needs), and those arguments need to be available when calling the constructor. Also, depending on whether the language needs explicit deconstruction (C++), this will introduce further complications. If you introduce new classes (i.e., a NextSettings or whatever), you have to go back to the original class and add more calls to their constructors.
High cohesion
Cohesion:

In computer programming, cohesion refers to the degree to which the elements inside a module belong together.

This is the other side of the coin. If you look at one unit of code (one method, one class, one package etc.), you want to have all code inside that unit to have as few responsibilities as possible.
A basic example for this would be the MVC pattern: you clearly separate the domain model from the view (GUI) and a control layer that glues those together.
This avoids code bloat where you get large chunks that do lots of different things; if you wish to change some part of it, you have to keep track of all the other features as well, trying to avoid bugs, etc.; and you quickly program yourself into a hole where it's very hard to get out.
With dependency injection, you delegate the creation or keeping track of, well, dependencies to whatever classes (or configuration files) which implement your DI. Other classes will not care much about what exactly is going on - they will be working with some generic interfaces, and have no idea what the actual implementation is, which means they are not responsible for the other stuff.

A: You should use techniques to solve the problems they're good at solving when you have those problems. Dependency inversion and injection are no different.
Dependency inversion or injection is a technique that allows your code to decide on what implementation of a method gets called at run time. This maximizes the benefits of late binding. The technique is necessary when the language does not support run time replacement of non-instance functions. For example, Java lacks a mechanism to replace calls to a static method with calls to a different implementation; contrast with Python, where all that's necessary to replace the function call is to bind the name to a different function (reassign the variable holding the function).
Why would we want to vary the implementation of the function? There's a two main reasons:

*

*We want to use fakes for testing purposes. This allows us to test a class that depends on a database fetch without actually connecting to the database.

*We need to support multiple implementations. For example, we might need to set up a system that supports both MySQL and PostgreSQL databases.

You may also want to take note of inversion of control containers. This is a technique that is intended to help you avoid huge, tangled construction trees that look like this pseudocode:
thing5 =  new MyThing5();
thing3 = new MyThing3(thing5, new MyThing10());

myApp = new MyApp(
    new MyAppDependency1(thing5, thing3),
    new MyAppDependency2(
        new Thing1(),
        new Thing2(new Thing3(thing5, new Thing4(thing5)))
    ),
    ...
    new MyAppDependency15(thing5)
);

It lets you register your classes and then does the construction for you:
injector.register(Thing1); // Yes, you'd need some kind of actual class reference.
injector.register(Thing2);
...
injector.register(MyAppDepdency15);
injector.register(MyApp);

myApp = injector.create(MyApp); // The injector fills in all the construction parameters.

Note that it's simplest if the classes registered can be stateless singletons.
Word of caution
Note that dependency inversion should not be your go-to answer for decoupling logic. Look for opportunities to use parameterization instead. Consider this pseudocode method for example:
myAverageAboveMin()
{
    dbConn = new DbConnection("my connection string");
    dbQuery = dbConn.makeQuery();
    dbQuery.Command = "SELECT * FROM MY_DATA WHERE x > :min";
    dbQuery.setParam("min", 5);
    dbQuery.Execute();
    myData = dbQuery.getAll();
    count = 0;
    total = 0;
    foreach (row in myData)
    {
        count++;
        total += row.x;
    }

    return total / count;
}

We could use dependency inversion for some parts of this method:
class MyQuerier
{
    private _dbConn;

    MyQueries(dbConn) { this._dbConn = dbConn; }

    fetchAboveMin(min)
    {
        dbQuery = this._dbConn.makeQuery();
        dbQuery.Command = "SELECT * FROM MY_DATA WHERE x > :min";
        dbQuery.setParam("min", min);
        dbQuery.Execute();
        return dbQuery.getAll();
    }
}

class Averager
{
    private _querier;

    Averager(querier) { this._querier = querier; }

    myAverageAboveMin(min)
    {
        myData = this._querier.fetchAboveMin(min);
        count = 0;
        total = 0;
        foreach (row in myData)
        {
            count++;
            total += row.x;
        }

        return total / count;
    }

But we shouldn't, at least not completely. Notice that we've created a stateful class with Querier. It now holds a reference to some essentially global connection object. This creates problems such as difficulty in understanding the overall state of the program and how different classes coordinate with each other. Notice also that we're forced to fake out the querier or the connection if we want to test the averaging logic. Further A better approach would be to increase parameterization:
class MyQuerier
{
    fetchAboveMin(dbConn, min)
    {
        dbQuery = dbConn.makeQuery();
        dbQuery.Command = "SELECT * FROM MY_DATA WHERE x > :min";
        dbQuery.setParam("min", min);
        dbQuery.Execute();
        return dbQuery.getAll();
    }
}

class Averager
{
    averageData(myData)
    {
        count = 0;
        total = 0;
        foreach (row in myData)
        {
            count++;
            total += row.x;
        }

        return total / count;
    }

class StuffDoer
{
    private _querier;
    private _averager;

    StuffDoer(querier, averager)
    {
        this._querier = querier;
        this._averager = averager;
    }

    myAverageAboveMin(dbConn, min)
    {
        myData = this._querier.fetchAboveMin(dbConn, min);
        return this._averager.averageData(myData);
    }
}

And the connection would be managed at some even higher level that's responsible for the operation as a whole and knows what to do with this output.
Now we can test the averaging logic completely independently of the querying, and what's more we can use it in a wider variety of situations. We might question whether we even need the MyQuerier and Averager objects, and maybe the answer is that we don't if we don't intend to unit test StuffDoer, and not unit testing StuffDoer would be perfectly reasonable since it's so tightly coupled to the database. It might make more sense to just let integration tests cover it. In that case, we might be fine making fetchAboveMin and averageData into static methods.


text:
Q: Advanced custom fields in WP - images I can't get ACF's to show images.
I created a field with the field type of image-1
<img src="<?php the_field('image-1'); ?>" alt="" />

All it shows is the broken image thing in chrome.
Is anyone familiar with this plugin and knows how to get image fields to work?

A: I am assuming that you meant the field type is 'image', not 'image-1'.  Your code is completely correct.  More likely you are having other unrelated issues.  I would guess that you might be having some sort of permissions issue, and the image is not actually being uploaded.
First, check the javascript console.  In Chrome, right-click (ctrl-click on mac) the image, select 'inspect element' to open Chrome Dev Tools, and see what the img src is.  In Dev Tools, right click on the img src and select 'open in new tab'.  That should open up the image directly.  My hunch is that the image won't open this way.  If that is the case, then the image was not correctly uploaded by ACF, and the error has nothing to do with the PHP code you are using to display it (which as I've said is completely correct).
There are various permissions related issues that you would need to look into.  Here's a link to one such issue: http://support.advancedcustomfields.com/discussion/3395/image-upload-bug/p1.
UPDATE:
Based on your comment regarding getting thumbnails to work, here's the code you would need:
$attachment_id = get_field('image-1');
$size = "thumbnail"; // (thumbnail, medium, large, full or custom size)

$image = wp_get_attachment_image_src( $attachment_id, $size );
// url = $image[0];
// width = $image[1];
// height = $image[2];
?>
<img src="<?php echo $image[0]; ?>" />
<?php

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android HTTPS SSLHandshake Exception : Connection Reset By Peer, using ksoap on Lollipop Android Device I have a problem connecting to the https site using Lollipop Android device using ksoap library. i'm getting SSLHandshake Exception : Connection Reset By Peer. I notice Android 5.0 have changes on TLS/SSL configuration, on their site it state

TLSv1.2 and TLSv1.1 protocols are now enabled,
  AES-GCM (AEAD) cipher suites are now enabled,
  MD5, 3DES, export, and static key ECDH cipher suites are now disabled,
  Forward Secrecy cipher suites (ECDHE and DHE) are preferred.

I check the server, it's using TLS_RSA_WITH_3DES_EDE_CBC_SHA as the cipher suite which is not supported by Android 5.0
I have tried using solution on this link to accept all certificate :
KSOAP 2 Android with HTTPS
And make custom SSLSocketFactory to just enabled the preffered cipher suite :
How to override the cipherlist sent to the server by Android when using HttpsURLConnection?
Bu no success i'm getting an error "TLS_RSA_WITH_3DES_EDE_CBC_SHA is not supported"
Is there any workaround to handle this matter on client side because i know this can be solved by upgrading the server to add modern cipher suite which Android 5 supported.

A: I had the same problem. I found a link https://code.google.com/p/android/issues/detail?id=88313 where I found a code:
public class MySSLSocketFactory extends SSLSocketFactory {
           SSLContext sslContext = SSLContext.getInstance("TLS");

           public MySSLSocketFactory() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
                super(null, null, null, null, null, null);

                final TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustMgrFactory.init((KeyStore) null);

                sslContext.init(null, trustMgrFactory.getTrustManagers(), new SecureRandom());
            }

            @Override
            public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
                final SSLSocket sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
                sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
                return sslSocket;
            }

            @Override
            public Socket createSocket() throws IOException {
                final SSLSocket sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket();
                sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
                return sslSocket;
            }
    }

You could try to use custom SSlSocketFactory as I've wrote above. Also it's not the best solution. You can have some security issue later, because for connection it can use some old cipher algorithm.
Hope this helps.

A: I had the same problem I wrote SSL_RSA_WITH_3DES_EDE_CBC_SHA instead of TLS_RSA_WITH_3DES_EDE_CBC_SHA And it worked for me.
You can check this Is TLS_RSA_WITH_3DES_EDE_CBC_SHA equivalent to SSL_RSA_WITH_3DES_EDE_CBC_SHA


text:
Q: Restructuring app with ServiceStack and JsonP I initially started off with an MVC application which contained my JQuery Mobile site and my ServiceStack rest services. My gets and posts were done via AJAX and all is working fine.
I now moved my servicestack rest services to an ASP.NET application and now I am having cross domain issues.
I thought about using JSONP but that will sort out the "gets" but I read I cannot make "post" requests (not too familiar to JSONP at the moment).
I want to know what my options are?
Should I
1) just make the AJAX calls back to my MVC controllers and then from there make calls to  my new REST services  (in the ASP.net app with ServiceStack)
2) Find a way of making cross domain calls (from the browser) if at all possible.
and if I go with 1) is there a performance hit as I am now going to the MVC app and then making a call to the ASP.NET service stack rest services.

A: My vote would be for option 1, especially if the applications are going to be hosted off of the same network / domain.
That said if you were interested in going the cross domain route then that is also an option. In terms of making cross domain gets via jsonp this is the article that helped me greatly get up and running in regards to MVC: http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
Cross domain POSTS are a little annoying as you need to perform a GET request and handle the serialization of any "GET" parameters manually.

A: As you know this isn't an issue when you host ServiceStack and MVC together which you can easily setup with the ServiceStack.Host.Mvc NuGet pacakge as seen in the SocialBootstrapApi demo.
Using a Reverse Proxy
I don't like Option 1) where you proxy all HTTP Requests to ServiceStack via MVC because of the additional code boilerplate and overhead.
If you were to use a proxy it's less overhead, code and cleaner to just configure it below a native/top-level reverse proxy server and route all paths beginning with /api to an internal ServiceStack url with everything else going to your MVC Host. If using IIS you can enable this with IIS Rewrite and Application Request Routing. This is also fairly trivial to setup with Nginx and Apache
Enable Cross-Domain Requests
You can make Cross Domain request by using JSONP or enabling CORS, here's how you can do that in ServiceStack:
servicestack REST API and CORS


text:
Q: node-postgres get error connect ECONNREFUSED I want to connect my apps nodejs using node-posgres to PostgreSQL.
My apps in localhost (ubuntu) and my postgresql in virtual machine in the cloud with operating system OpenSuse.
This is my code :
var express = require('express');
var app = express();

var http = require('http');
var pg = require('pg');

var conString = "postgres://postgres:mypassword@myurl.com:5432/postgres";

app.get('/', function (req, res) {
    res.send('HOLAAAA');
});

// respond with "SERVER" on the homepage
app.get('/server', function (req, res) {

    var client = new pg.Client(conString);
    client.connect(function (err) {
        if (err) {
            return console.error('could not connect to postgres', err);
        }
        console.log('CONNECT PASSED');
        client.query('SELECT * FROM visit', function (err, result) {
            if (err) {
                return console.error('error running query', err);
            }
            console.log('QUERY PASSED');
            console.log(result.rows[0].theTime);
            //output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
            client.end();
        });
    });

});

var server = app.listen(3000, function () {

    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);

});

But i got an error like this:
could not connect to postgres { [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }

Please help me how to solve this.
Thanks!

A: @Madhavan Kumar thank you very much for your help
the steps to resolve this were as follows:
On the remote server:-
1- find \ -name "postgresql.conf" to find place of config file
2- sudo nano /path/to/config/postgresql.conf to edit config file
3- change this #listen_addresses = 'localhost' to this listen_addresses = '*' then save and exit
4- find \ -name "pg_hba.conf" to find hba config file
5- sudo nano /path/to/config/pg_hba.conf to edit hba config file
6- add

host    all             all              0.0.0.0/0                       md5
host    all             all              ::/0                            md5

at the end of the file, then save and exit
7- run /etc/init.d/postgresql restart to restart postgres
In the code connect like this:-
let sequelize = new Sequelize(
  config.db.name,
  config.db.username,
  config.db.password,
  {
    host: config.ip,
    port: config.port,
    dialect : 'postgres'
  }
)

A: First try a simple psql command from the local end,
psql -d DBNAME -h YOUR_IP -U USERNAME

it mayn't work for you. This can be because of two reasons, the VM's ip is not resolved by your local station. (or) is the VM in public cloud like amazon (or) your desktop. If it is in public group, the port 5432 on the VM is not open to the public world.  You need to write a security group to do it.
If you are sure, it is not any one of the above two issues, better visit postgres /etc/postgresql/9.3/main/pg_hba.conf and see if remote connections are enabled. NodeJs app, you must test at the end.


text:
Q: POS software/hardware general questions I'm looking for answers to a few general questions as to how point of sale (POS) software and hardware generally works in brick-and-mortar stores.  I realize there will be many edge cases given the sheer number of solutions out there, but I'm looking for answers on the most common setups...
So, here it goes:
I realize that there are several standards for hardware interface standardization (OPOS, JavaPOS, UnifiedPOS).  However, what is most common these days?
When a credit or debit card is scanned, does the scanning device take care of processing the card, or is it transmitted to the main POS terminal, which then connects to the processing service for processing?
Are there any standards on software for the main POS terminal systems?
How are product identifiers generally stored - barcode, ASIN, proprietary standard?
Thanks in advance!

A: UnifiedPOS, as the name implies, appears to be the most universal standard.  JavaPOS, as you might expect, is Java language specific, while OPOS is WIN32/COM based, which suggests that it is an older standard.
OPOS, JavaPOS, and POS for .NET are all based on the UnifiedPOS standard, and they all appear to have broad support.  So your choice comes down to which programming language you want to use to develop the platform.
Hardware written to the UnifiedPOS standard should work with any of these platforms.  The UnifiedPOS committee says that 36 different point-of-service peripheral types currently support the standard.


text:
Q: SSRS Report Skip Page I have an SSRS Report that I need help with  -
So the design looks like below -

You will notice that there are page breaks between each table. So each "account" starts on a new page.
What currently happens is if there are no results in the table I get the table returned with the following

So an extra page is created with a table telling us there are no results.....however is there any way that the table and therefore the page is just skipped/ignored altogether if no results exist?

A: Set the Hidden property in the Visibility section of the table properties to true when there are no records in the dataset that populates that table and it shouldn't render in your final report:
=iif(CountRows() = 0, true, false)

Page break options on the table properties:


text:
Q: Trouble using insertion sort with a Python list I'm given a text file that resembles the following...
hello 20
world 30
i'm 50
ok 20

I'm trying to use insertion sort to arrange the numerical part of the data. My code looks like the following...
def insertion_sort():
    filename = input('Enter filename: ')
    lst = []
    for line in open(filename):
        lst.append(int(line))
    print(lst)
    for index in range(1,len(lst)):
        value = lst[index]
        leftvalue = index -1
        while leftvalue >= 0 and lst[leftvalue] > value:
            if value < lst[leftvalue]:
                lst[leftvalue + 1] = lst[leftvalue]
                lst[leftvalue] = value
                leftvalue = leftvalue - 1
            else:
                break
    return lst == insertion_sort()

I'm getting the following error...
ValueError: invalid literal for int() with base 10: 'Merchant_0 96918\n'
I have tried using float in replacement with int but I can't convert strings to floats.

A: You can't get an integer with :
lst.append(int(line))
if line contains, say 'world 30'
What do you try to obtain exactly ? If you want to get the numeric value, try :
int(line.split(' ')[1])
Or better (works even if there are multiple spaces in the input lines) :
import re
reobj=re.search('(\d+)$',line)
int(reobj.group(1))

The whole sorting process becomes :
import operator
import re

lines = {}
for line in open('tst.txt'):
    reobj=re.search('(\d+)$',line)
    int_key=int(reobj.group(1))
    value=line[0:reobj.start()]
    lines[int_key]=value

# See : http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value?rq=1
print "Sorted : ", sorted(lines.iteritems(), key=operator.itemgetter(0))


text:
Q: foreach isn't working properly <?php

$find = array('Mahmoud', 'Ahmed', 'Arafa');

if(isset($_POST['user_input']) && !empty($_POST['user_input'])){
    $user_input = $_POST['user_input'];

    for ($i=0; $i < count($user_input); $i++) {
        //echo 'eshta';
        foreach($find as $pattern) {
            echo "$pattern";
            if($pattern[0] == $user_input[$i]){
                $flag = 1;

                for ($k=0; $k < count($pattern); $k++) {
                    if($pattern[$k] != $user_input[$i + $k]){
                        $flag = 0;
                        break;
                    }
                }

                if($flag){
                    for ($k=1; $k < count($pattern) - 1; $k++) {
                        $user_input[$i + $k] = '*';
                    }
                }
            }
        }
    }

    echo $user_input;
}

?>

This is a snippet from my script.php for word censoring. In this line:
'echo "$pattern";

it outputs the whole array, not the current word (pattern). What's the problem?

A: How about something like this?
URL: https://www.tehplayground.com/hlpAbDTdt4Rv617K
<?php

$find = array('Mahmoud', 'Ahmed', 'Arafa');

    for ($i=0; $i < count($find); $i++) {
        //echo 'eshta';
        foreach($find as $i => $pattern) {
            echo $find[$i];
        }
    }
?>

Reference: Loop through an array php


text:
Q: How to set a projection matrix on Three.js which does this kind of mapping? How to make a projection matrix on Three.js which does the mapping from 3d points to screen coordinates described by the rule below?
screen_x = x - z*0.5
screen_y = y - z*0.5
depth = z

A: The projection matrix represents the following equations:
xx xy xz xt    <- x' = (xx*x + xy*y + xz*z + xt) / (wx*x + wy*y + wz*z + 1)
yx yy yz yt       y' = (yx*x + yy*y + yz*z + yt) / (wx*x + wy*y + wz*z + 1)
zx zy zz zt       z' = (zx*x + zy*y + zz*z + zt) / (wx*x + wy*y + wz*z + 1)
wx wy wz  1

From that all the other elements will be zero, but
screen_x = x-z*0.5 : xx=1,       xz=-0.5
screen_y = y-z*0.5 :       yy=1, xz=-0.5
depth  z'= z       :             zz=1      (and ww=1)

EDIT This not the general projection matrix, but only applicable to this particular problem.
The general [symmetric] projection matrix is of form
 a  0  0  d
 0  b  0  e
 0  0  c  f
 0  0  1  0,

from which it follows that x and y will be divided by wx*z == z.


text:
Q: Get fcm token programmatically I have initialised firebase in android without using the google-services plugin like this
FirebaseOptions.Builder builder = new FirebaseOptions.Builder()
                        .setApplicationId("application-id")
                        .setApiKey("api-key")
                        .setDatabaseUrl("database-url")
                        .setStorageBucket("storage-bucket")
                        .setProjectId("project-id")
                        .setGcmSenderId("gcm-sender-id");
                FirebaseApp.initializeApp(context,builder.build());

Now after initialising the firebase app how can i get the token generated to send push notification via FCM

A: I think you could get it like:
 FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(instanceIdResult -> {
            String token = instanceIdResult.getToken();
            updateToken(token, apiService, sessionManager); // update token on server
        });


text:
Q: Execute after setTimeout finished Probably not very suitable title, but the question is the following.
I've got this piece of code
var someprogram = function(){
    if(stopprocess) return;
    //do things
    setTimeout(someprogram, 1000);
}
setTimeout(someprogram, 1000);
Sofar it works. After some number ot iterations, lets say 12, stopprocess is true and whole thing stops. I want to do some more things after the return. So the question is what is the best way to rewrite the structute to be able to do so? Because I need the timeout, but I don't know how else to stop the whole thing without using a return-statement. Any ideas? (I have only one javascript file for this task)

A: there are many ways to do this simple way is to write all your logic in a function and execute it.
    var logic = function(){
       //do things
     }

and execute it before return
var someprogram = function(){
    if(stopprocess){
       logic(); // your code is executed now
       return;
   }

    setTimeout(someprogram, 1000);
}
setTimeout(someprogram, 1000);

A: May be this one works for you:
var someprogram = function() {
    if(stopprocess) {
        //do the rest

    } else {
        //do things
        setTimeout(someprogram, 1000);
    }
}

setTimeout(someprogram, 1000);


text:
Q: String Manipulation and System Call in C I'm a C amateur, and I'm having trouble manipulating strings in C. The objective is to add the current pid to a base string, then call it with system(system_call). I have the following:
char system_call[100] = "top -p "
char pid_string[30];

//quite a bit of other code

int main(int argc, char *argv[])
{
    pid_t pid = getpid();
    sprintf(pid_string,"%d",pid);
    strcat(system_call,pid_string);

    printf(system_call); //prints what I expect; something like 'top -p 5580'
    system(system_call); //doesn't work
}

The system call simply gives sh: system: not found. I'm sure people good with C will know the problem instantly. I thought maybe the trailing 0 after strings in C had something to do with it, but I'm too terrible at C to recognize it or know what to do about it. I also tried system("%s",system_call) but system only takes one argument. Is there something wrong with my memory allocation? Any insight is appreciated.

A: The variable pid is not given a value before use in the sprintf.

A: Cant see any problem with your string construction, maybe the problem is that "system" itself does not work for some reason on your system :-), or "top" is not acessible


text:
Q: Force change vue js/css assets hash (fingerprint) Building vue app in production as in:
NODE_ENV=production vue-cli-service build

Adds the static assets hash fingerprints as below:
  dist/js/chunk-vendors.d710a916.js      986.81 KiB        297.69 KiB
  dist/js/app.ad3f94f2.js                231.00 KiB        56.02 KiB
  dist/3115008e.worker.js                30.59 KiB         9.98 KiB
  dist/css/app.7eecdb26.css              174.87 KiB        24.16 KiB
  dist/css/chunk-vendors.565b13d4.css    42.77 KiB         6.81 KiB

The assets are served with a high maxage cache. Due to some issues involving the headers of these static assets, I want to force renaming all assets, preferably via changing the length of the hash fingerprint (or the algorithm).
So in vue.config.js I added:
module.exports = {
    configureWebpack: {
        output: {
            hashFunction: 'sha256',
            hashDigestLength: 8,
        },
    ...
}

The problem is that it affects only dist/3115008e.worker.js (the hash changes, and length increases to 8). All other assets name remain unchanged.
What changes are required to modify the hash fingerprint length (or algorithm) for the chunk-vendors and app assets?

A: Update:
I ended up forcing assets hash change by modifying the loader's hashType option in vue.config.js(which seem to default to 'md5'):
module.exports = {
  ...
  chainWebpack: config => {
    config.module
        .rule('vue')
        .use('vue-loader')
        .loader('vue-loader')
        .tap(options => {
            options.hashType = `sha1`
            return options
        })
},

I wasn't able to change the hash length. It seems to be hardcoded in @vue/cli-service": "^4.1.2"


text:
Q: Tangent bundle of $S^n$ diffeomorphic to subspace of $S^n \times \mathbb{R}$? A set of lecture notes on differential geometry I was reading noted that the tangent bundle of a standard n-sphere $TS^n$ is diffeomorphic to the space $\{(x, y) \in S^n \times \mathbb{R}^{n+1}| <x, y> = 0 \}$. Why is this true?

A: If $S\subset M$ is a submanifold of an ambiant manifold, you can see the tangent space of $S$ at a point $p$ as a linear subspace of the tangent space of $M$ at $p$, under the identification $i_{\star,p}:T_pS\to T_pM$, where $i:S\to M$ is the inclusion. Moreover, if the ambient one is an affine subspace, a tangent vector at a point $p$ is identified with a vector of the underlying vector space (in the case of $\mathbb{R}^n$, this is no more that $\mathbb{R}^n\to T_p\mathbb{R}^n, v\mapsto \partial_v=$ the directionnal derivative at the point $p$ in the direction of $v$). So the following computations are right under the identifications that I precised above:
Take a smooth curve $\gamma:(-\varepsilon,\varepsilon)\to S^n$ with $\gamma(0)=x\in S^n$ and $\gamma'(0)=y\in T_pS^n$. Since $||\gamma(t)||^2=\langle\gamma(t),\gamma(t)\rangle=1$ for all $t$, then by differentiating and evaluating at $0$ you get
$$2\cdot\langle\gamma(0),\gamma'(0)\rangle=0\iff\langle x,y\rangle = 0.$$
This leads to the identification you are given.


text:
Q: iOS 7 supportedInterfaceOrientation not working as intended So I have root controller that can rotate to any orientations and a view controller that only shows landscape mode using supportedInterfaceOrientations
- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

So when I present that view controller by setting the window's root controller to be that at some point of the app, like button press, it starts on landscape mode. Everytime it rotates it calls that method. But when I rotate to portrait it went portrait even though I told them to use landscape only. Any advice?

A: The problem is that only the topmost view controller is consulted. For example, if you have a navigation controller and its root view controller, only what the navigation controller says is important. (And you can use the navigation controller delegate's navigationControllerSupportedInterfaceOrientations: to give the answer you want.)


text:
Q: Added new column to a table but updateOrCreate method won't update - Laravel I just added a new column with php artisan make:migration , and after that I called updateOrCreate method hoping to filling the new column with values on all the existing records.
But nothing happened. I tracked down and found that the parameter for the new column was passed right to updateOrCreate method. But why was it not working? Thanks.

A: Just to close the question off and give it an answer, as Jeemusu pointed out, you needed to add the new column to your $fillable array inside the table model - thus allowing it to be inserted in to your database.


text:
Q: What is the difference between a GPU and a graphics card in a pc? What is the difference between both these things? Are they same? Is there a difference between their capabilities?

A: The graphics card is the hardware as a whole, while the GPU is a chip, part of the graphics card or an onboard similar, which stands for "Graphics Processing Unit".

Image: GPU on Graphics Card

A: Graphics Card is a complete board that gets binary data from the processor and outputs the result to the monitor in the form of pixels.Now there are lots of components in the Graphics card like

*

*GPU

*RAM (A dedicated RAM inside the graphics card used only by the card.Not to be confused with the system RAM)

*DAC (Digital to Analog Converter) that converts the digital data to analog format to be displayed in the monitor.

GPU(Graphics Processing Unit) is the dedicated processor inside Graphics Card that does all the heavylifting. It differs from the main processor in that its specially designed to perform the rendering task.

A: Graphics card is the piece of hardware that is responsible of producing output to monitor. It has a connector(s) for monitor(s) and another connector to computer motherboard. Graphics card has its own memorymodules and most importantly the graphics processing unit that actually creates the display we see on monitor screen. Modern graphics cards also have power input connectors and their own cooling solutions.
GPU is short from Graphics Processing Unit. It is specially designed processor to most effectively process the displaying needs of a working computer.
GPU is an integral part of a graphics card, so that is the difference between these two.

A: In previous generations, an integrated GPU was a seperate chip connected over pci, agp or pci-e to the system which was on the motherboard. These processors were in many cases minimal, low powered processors, such as Via unichrome, or intel integrated/HD graphic, though it was entirely possible to find motherboards with better graphics chips like Nvidia or Ati - this is common with laptops, if they arn't using switchable graphics. These days, integrated GPUs are more often embedded into processors and are on the same die. With some older systems, the iGPU used the same PCIe or AGP lanes as the discrete card, so it was not possible to use a discrete card and the iGPU at once. iGPUs also usually share ram with the system. Other than this, its entirely possible that your iGPU can do nearly all the things you need, and/or be on par with a low  to medium end discrete card at the very least.
Graphics cards on the other hand are swappable pieces of equipment that, as per their name, come on their own cards. In most cases these tend to have better, more powerful processors, and their own ram. While primarily used for gaming, its possible to use an array of graphics cards for speeding up tasks that require parallel processing like password cracking. You can also, in some cases, get identical cards to work together through crossfire or sli  You might also get a graphics card to add more monitors to a system. These days, most graphics cards are PCIe x16 (though means exist to install them on a x1 slot) running at x8 or x16 speeds, or mxm - which is a laptop slot for graphics cards.

A: A very good explanation from howstuffworks. Here is the gist:
It's a PCB (printed circuit board) similar to the motherboard. Just as a motherboard has got a 'primary' RAM and a CPU, a graphics card too has got a RAM and GPU (graphics processing unit). GPU is designed to process much faster than the CPU (usually needed in computer games).


text:
Q: Matlab plots in loops Can any expert here tell me what is wrong on my code:
folderContents=ls;
folderContents(1:2,:)=[];
nFolderContents=size(folderContents,1);
for i=1:nFolderContents;
        [~, data] = hdrload(folderContents(i,:));
        if size(folderContents(i,:),2)<size(folderContents,2);
        temp=folderContents(i,6:9);
        else
        temp=folderContents(i,6:7);
        end
        temp1(i)=strread(temp);
        w=2*pi*(data([18 35 51 68],1));
        permfreespace=8.854e-12;
        perm=data([18 35 51 68],3);
        cond=perm.*w.*permfreespace;
        conds([18 35 51 68],i)=cond;

       hold all
    end

    figure(4);plot(temp1,conds);

the problem is that I want to plot only these lines [18 35 51 68], but I see many lines. nFolderContents is equal to 31, when I choose for i=1:4 I get same problem. why ??

A: Maybe I'm missing something, but can you not just do:
plot(temp1([18 35 51 68]),conds([18 35 51 68],:))

A: When MATLAB first time executes the line
conds([18 35 51 68],i)=cond;

it creates an array "conds" with 68 rows and assign the data from 4-element vector "cond" to rows 18,35,51,68 of i-th column of "conds". Rest rows contain zeros. So, I guess, in your code you see 4 lines you are interested in, and 64 lines along X-axis...
To solve your problem it should be enough to replace the mentioned above line by
conds(:,i)=cond;

Hopefully, I have not missed something ))
Cheers,
//Oleg


text:
Q: How should we deal with a question being bumped repeatedly via edits performed by the author of the accepted answer? I noticed this question had been bumped recently, and when looking at the edit history it appears that a single user edits the title repeatedly. Presumably in an effort to gain exposure for their answer. I noticed similar behavior here. Is this appropriate, and should it be reported in any way?
I would think good questions and answers should receive traffic based on their appeal and how often they show up in search results, not the traffic generated by being on the front page(?).

A: This is absolutely inappropriate; the edits don't improve anything which is further reflected by the fact that the user rolls them back repeatedly. This is a blatant abuse of privileges and you should flag the post for moderator attention. A related discussion can be found here: Any consideration to preventing tactical edits, which can be used to generate artificial Question exposure?. Can I get suspended for bumping my post? doesn't really answer your question; that is about a question author bumping their own post.
Fortunately, this type of behaviour is relatively easy to spot via the Stack Exchange Data Explorer. We can query for the number of edits to question by an author of one of its answers, and then inspect the revisions manually to decide whether they're really worthwhile or just intended to bump the question. This query does so, and the case you found is indeed in the top 20 results. I've just used it to flag two obvious cases of sockpuppetry.


text:
Q: How do I .focus a form input area with a click on the form button? So I have a search form in the nav menu of my website, and I'd like to have the search button once clicked on, to redirect to the search input, and not to the archive/search section of the website.
I wrote this:

function l() {
  document
    .getElementsByClassName("search-button")[0]
    .addEventListener("click", function(e) {
      var t = document.getElementsByClassName("search-input")[0];
      t.value.length < 2 && (e.preventDefault(), t.setFocus());
    });
}
l();
<form role="search" class="search-form" method="get" action=# placeholder="Searching for …" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Searching for …'">
  <input class="search-input" name="s" type="text" placeholder="Searching for ..." onfocus="this.placeholder=''" onblur="this.placeholder='Searching for ...'">
  <button type="submit" class="search-button" title="Search Blogs">
 </button>
</form>

But it doesn't seem to do much.
I thought the placeholder maybe would count as a t.value.lenght>2 but even without a placeholder (input already focused) the button redirects to the search page, which should be stopped by e.preventDefault() shouldn't it?
Maybe is there a CSS way of stopping the button to link to the search page?
Thanks


text:
Q: Does Solr support group multiple fields? I am newer to solr, we want to get document list of each group that grouped by multi-fields. And I finds solr supports grouping-result, but this feature supports just one field. And I also finds ReduceStream support multiple-fields, but the results set of ReduceStream are not like group-format. The parallel Sql feature can group by multi-fields, but cat not get document list of each group. My question is that: is there any ways to group result by multiple fields and the result set show as grouping-result feature.
Any help will be appreciated.

Note:I want to get document list of each group not the aggregation of each group, so facet.pivot, RollupStream etc can not match my question.
And I find that ElasticSearch can statify my question by using terms aggregation(child aggregation) and top-hints metric aggregation.

A: I would try to merge the two fields at indexing time, in a third field e.g.
group_title = title + category


text:
Q: Does replaying an assassination still affect stocks? I missed a few investment opportunities, and also did those missions way earlier in the game than I should have. If I replay those missions, will the stock market be re-affected?
(Attempting a replay pops a statement indicating that afterward, you will be restored to the point just before the replay, so my hunch is no. But I'm wondering if anyone's tried it yet, or if I need to restart to get my guys up to their nine-figure potential.)

A: Currently, replaying these missions will not have any effect on the stock prices. Replaying missions is only to get a better rating.
The capacity to retroactively impact the stock market may be implemented in a future patch but this kind of change is fairly unlikely.
If you are looking for other stock market tips, here's a fairly useful guide.


text:
Q: How to add wikipage in wikipage library using powershell? I tried to add a wikipage in the wikipage library using the code provided by Vijai Anand Ramalingam on c-sharpcorner.com.
I'm copy-pasting the script here to avoid dead link issues preventing future readers from accessing it. I obviously replaced all the variables to allow the script to suits my local environnement.
$listName="A"
$siteURL="http://serverName:1111"
$site=Get-SPSite $siteURL
$web=$site.RootWeb
$list=$web.Lists[$listName]
$rootFolder = $list.RootFolder
$wikiPage = $rootFolder.Files.Add("/"+$rootFolder+"/Home.aspx", [Microsoft.SharePoint.SPTemplateFileType]::WikiPage)
$wikiItem = $wikiPage.Item
$wikiItem[[Microsoft.SharePoint.SPBuiltInFieldId]::WikiField] = "Template Preview"
$wikiItem.UpdateOverwriteVersion()

This code is not working because it throws the following error:
You cannot call a method on a null-valued expression
$wikiPage = $rootFolder.Files.Add("/"+$rootFolder+"/Home7.aspx", [Microsoft.Sh ...

A: Replace
$wikiPage = $rootFolder.Files.Add("/"+$rootFolder+"/Home.aspx", [Microsoft.SharePoint.SPTemplateFileType]::WikiPage)

by
$wikiPage = $rootFolder.Files.Add($rootFoler.ServerRelativeUrl + "/Home.aspx", [Microsoft.SharePoint.SPTemplateFileType]::WikiPage)


text:
Q: SQL query that generates another SQL query Our product has two parts, a server application and a client application.  The server application uses SQL server as the database engine.  The client application uses SQL Anywhere.  Data on the server replicates to the client using our proprietary replication scheme.
We recently had a problem at a client which caused us headaches.  We've fixed the issue with that customer, but I want to produce a tool that we can use to find rows in the Users table that could be the cause of the problem.
We have a number of tables in the server application's database that keep track of the data that needs to be replicated to the clients.  What these tables are and how they are layed out is irrelevant to this question.
I want to write a query in SQL Server that we can run and whose output is a query that the tech support guys can just copy to their clipboard and paste it into a remote session with the SQL Anywhere database query tool on the client.  This is not hard to do, the problem is that that there may be more than one row in the client that needs to be checked.
The query I have looks something like this:
SELECT 'SELECT Id, Name FROM MyClientTable WHERE <Condition to identify problem rows> AND Id = ''' + CONVERT( nvarchar(36), Id ) + ''''
FROM MyServerTable
WHERE <Condition to identify problem row candidates>

This produces one query for each candidate row.  I want one query that looks more like:
SELECT Id, Name FROM MyClientTable WHERE <condition to identify problem rows> AND ID IN ( . . . )

Is there a way that I can pull this off?  If so, just how do I do it?

A: This may work for you:
DECLARE @Tsql VARCHAR(MAX)
SET @Tsql = 'SELECT Id, Name FROM MyClientTable WHERE <condition to identify problem rows> AND ID IN ('

SELECT @Tsql = @Tsql + CAST(ID AS VARCHAR) + ','
FROM MyServerTable
WHERE <Condition to identify problem row candidates>

--Remove last trailing comma, append closing parentheses.
SELECT @Tsql = LEFT(@Tsql, LEN(@Tsql) - 1) + ')'

PRINT @Tsql

Edit: tsql changes for compatibility with older versions of SQL Server.

A: You can use the following query
;WITH Ids(IdValues)
AS
(
    SELECT '''' + CAST (Id AS VARCHAR(39)) + ''',' AS 'text()'
    FROM MyServerTable WHERE <Condition to identify problem row candidates>
    FOR XML Path('')
)
SELECT 'SELECT Id, Name FROM MyClientTable WHERE <Condition to identify problem rows> AND Id IN (' + LEFT(IdValues,LEN(IdValues)-1) + ')'
FROM Ids;


text:
Q: std::enable_if as single argument of constructor I'm fairly new to template metaprogramming and have been working through some of the concepts - however, I've been stumped a little by this particular snippet I came across.
template<class TAG, typename... DATATYPES>
struct Message {

    Message (typename std::enable_if<sizeof...(DATATYPES) >= 1>) {
    }

    ... (various other constructor declarations here)

    std::tuple<DATATYPES...> m_data;
};

I had assumed when reading it that it was enabling the default constructor if there were one or more DATATYPES arguments, but having tested it all I got was a compilation error.
I would appreciate any assistance in helping my understanding of this snippet as I understand what enable_if is supposed to be doing but within this context I don't seem to be able to wrap my head around what's actually happening.
EDIT: I guess this is less a question of 'how do I achieve this particular effect?' and more along the lines of 'what is this code actually producing, and does it match up with what I understood to be the intention of the original author?'

A: std::enable_if is not used correctly if not followed by ::type.  std::enable_if<expr> itself is a fairly useless struct type.
A correct way of conditionally enabling the default constructor:
template<class TAG, typename... DATATYPES>
struct Message {
private:
    struct dummy_type {};
public:
    template <typename T = std::tuple<DATATYPES...>>
    Message(
        typename std::enable_if<std::tuple_size<T>() >= 1, dummy_type>::type
        = dummy_type{}
    ) {}
    //...
};

Live at coliru.

A: Member function signatures are a part of class definition and need to be resolved when the class is instantiated. This means that compiler tries enable_if, too, and if the conditon is not fullfilled, it discovers that it doesn't have the nested type - hard error.
To make SFINAE work, you need to make the constructor a template and have enable_if depend on a template parameter. See @acheplers's answer for example.
What the code in OP does is a weird way of asserting the size of DATATYPE pack, which would be done with static_assert much more clearly. Or, maybe the author just didn't know how to do SFINAE correctly.


text:
Q: Asynchronous readline loop without async / await I'd like to be using this function (which runs fine on my laptop), or something like it, on my embedded device. But two problems:

*

*Node.JS on our device is so old that the JavaScript doesn't support async / await. Given our hundreds of units in the field, updating is probably impractical.

*Even if that weren't a problem, we have another problem: the file may be tens of megabytes in size, not something that could fit in memory all at once.  And this for-await loop will set thousands of asynchronous tasks into motion, more or less all at once.

async function sendOldData(pathname) {
    const reader = ReadLine.createInterface({
      input: fs.createReadStream(pathname),
      crlfDelay: Infinity
     })
    for await (const line of reader) {
      record = JSON.parse(line);
      sendOldRecord(record);
    }
}

function sendOldRecord(record) {...}

Promises work in this old version. I'm sure there is a graceful syntax for doing this sequentially with Promises:
read one line
massage its data
send that data to our server

sequentially, but asynchronously, so that the JavaScript event loop is not blocked while the data is sent to the server.
Please, could someone suggest the right syntax for doing this in my outdated JavaScript?

A: Make a queue so it takes the next one off the array

function foo() {

  const reader = [
    '{"foo": 1}',
    '{"foo": 2}',
    '{"foo": 3}',
    '{"foo": 4}',
    '{"foo": 5}',
  ];

  function doNext() {
    if (!reader.length) {
      console.log('done');
      return;
    }
    const line = reader.shift();
    const record = JSON.parse(line);
    sendOldRecord(record, doNext);
  }

  doNext();

}

function sendOldRecord(record, done) {
  console.log(record);
  // what ever your async task is
  window.setTimeout(function () {
    done();
  }, Math.floor(2000 * Math.random()));
}

foo();

A: Basically you can achieve this using functional approach:
const arrayOfValues = [1,2,3,4,5];

const chainOfPromises = arrayOfValues.reduce((acc, item) => {

  return acc.then((result) => {
    // Here you can add your logic for parsing/sending request

    // And here you are chaining next promise request
    return yourAsyncFunction(item);
  })

}, Promise.resolve());

// Basically this will do
// Promise.resolve().then(_ => yourAsyncFunction(1)).then(_ => yourAsyncFunction(2)) and so on...

// Start
chainOfPromises.then();

A: The Problem
Streams and asynchronous processing are somewhat of a pain to get them to work well together and handle all possible error conditions and things are even worse for the readline module.  Since you seem to be saying that you can't use the for await () construct for the readable (which even when it is supported, has various issues), things are even a bit more complicated.
The main problem with readline.createInterface() on a stream is that it reads a chunk of the file, parses that chunk for full lines and then synchronously sends all the lines in a tight for loop.
You can literally see the code here:
for (let n = 0; n < lines.length; n++) this[kOnLine](lines[n]);

The implementation of kOnLine does this:
 this.emit('line', line);

So, this is a tight for loop that emits all the lines it read out.  So ... if you try to do something asynchronous in your responding to the line event, the moment you hit an await or an asynchronous callback, this readline code will send the next line event before you're done processing the previous one.  This makes it a pain to do asynchronous processing of the line events in sequential order where you finishing asynchronous processing one line before starting on the next one.  IMO, this is a very busted design as it only really works with synchronous processing.  You will notice that this for loop also doesn't care if the readline object was paused either.  It just pumps out all the lines it has without regard for anything.
Discussion of Possible Solutions
So, what to do about that.  Some part of a fix for this is in the asynchronous iterator interface to readline (but it has other problems which I've filed bugs on).  But, the supposition of your question seems to be that you can't use that asynchronous iterator interface because your device may have an older version of nodejs.  If that's the case, then I only know of two options:

*

*Ditch the readline.createInterface() functionality entirely and either use a 3rd party module or do your own line boundary processing.

*Cover the line event with your own code that supports asynchronous processing of lines without getting the next line in the middle of still processing the previous one.

A Solution
I've written an implementation for option #2, covering the line event with your own code.  In my implementation, we just acknowledge that line events will arrive during our asynchronous processing of previous lines, but instead of notifying you about then, the input stream gets paused and these "early" lines get queued.  With this solution the readline code will read a chunk of data from the input stream, parse it into its full lines, synchronously send all the line events for those full lines.  But, upon receipt of the first line event, we will pause the input stream and initiate queueing of subsequent line events.  So, you can asynchronously process a line and you won't get another one until you ask for the next line.
This code has a different way of communicating incoming lines to your code.  Since we're in the age of promises for asynchronous code, I've added a promise-based reader.getNextLine() function to the reader object.
This lets you write code like this:
import fs from 'fs';

async function run(filename) {
    let reader = createLineReader({
        input: fs.createReadStream(filename),
        crlfDelay: Infinity
    });

    let line;
    let cntr = 0;
    while ((line = await reader.getNextLine()) !== null) {
        // simulate some asynchronous operation in the processing of the line
        console.log(`${++cntr}: ${line}`);
        await processLine(line);
    }
}

run("temp.txt").then(result => {
    console.log("done");
}).catch(err => {
    console.log(err);
});

And, here's the implementation of createLineReader():
import * as ReadLine from 'readline';

function createLineReader(options) {
    const stream = options.input;
    const reader = ReadLine.createInterface(options);

    // state machine variables
    let latchedErr = null;
    let isPaused = false;
    let readerClosed = false;
    const queuedLines = [];

    // resolves with line
    // resolves with null if no more lines
    // rejects with error
    reader.getNextLine = async function() {
        if (latchedErr) {
            // once we get an error, we're done
            throw latchedErr;
        } else if (queuedLines.length) {
            // if something in the queue, return the oldest from the queue
            const line = queuedLines.shift();
            if (queuedLines.length === 0 && isPaused) {
                reader.resume();
            }
            return line;
        } else if (readerClosed) {
            // if nothing in the queue and the reader is closed, then signify end of data
            return null;
        } else {
            // waiting for more line data to arrive
            return new Promise((resolve, reject) => {
                function clear() {
                    reader.off('error', errorListener);
                    reader.off('queued', queuedListener);
                    reader.off('done', doneListener);
                }

                function queuedListener() {
                    clear();
                    resolve(queuedLines.shift());
                }

                function errorListener(e) {
                    clear();
                    reject(e);
                }

                function doneListener() {
                    clear();
                    resolve(null);
                }

                reader.once('queued', queuedListener);
                reader.once('error', errorListener);
                reader.once('done', doneListener);
            });
        }
    }

    reader.on('pause', () => {
        isPaused = true;
    }).on('resume', () => {
        isPaused = false;
    }).on('line', line => {
        queuedLines.push(line);
        if (!isPaused) {
            reader.pause();
        }
        // tell any queue listener that something was just added to the queue
        reader.emit('queued');
    }).on('close', () => {
        readerClosed = true;
        if (queuedLines.length === 0) {
            reader.emit('done');
        }
    });

    return reader;
}

Explanation
Internally, the implementation takes each new line event and puts it into a queue.  Then, reader.getNextLine() just pulls items from the queue or waits (with a promise) for the queue to get something put in it.
During operation, the readline object will get a chunk of data from your readstream, it will parse that into whole lines.  The whole lines will all get added to the queue (via line events).  The readstream will be paused so it won't generate any more lines until the queue has been drained.
When the queue becomes empty, the readstream will be resumed so it can send more data to the reader object.
This is scalable to very large files because it will only queue the whole lines found in one chunk of the file being read.  Once those lines are queued, the input stream is paused so it won't put more into the queue.  After the queue is drained, the inputs stream is resumed so it can send more data and repeat...
Any errors in the readstream will trigger an error event on the readline object which will either reject a reader.getNextLine() that is already waiting for the next line or will reject the next time reader.getNextLine() is called.
Disclaimers
This has only been tested with file-based readstreams.
I would not recommend having more than one reader.getNextLine() in process at once as this code does not anticipate that and it's not even clear what that should do.


text:
Q: Shuffle between SSE integer registers I have two sse integers which i am assigning it as follows:
    __m128i m1 = _mm_set_epi32(4,3,2,1);
    __m128i m2 = _mm_set_epi32(40,30,20,10);

Now, I have to do some shuffle between these two registers and store the result in another two registers such that the output will be as follows:
     m3 = (30,3,10,1);
     m4 = (40,4,20,2);

Is there any way that i can achieve this!!
Thanks

A: You can do that like this:
t1 = _mm_shuffle_epi32(m1, 0xd8);
t2 = _mm_shuffle_epi32(m2, 0xd8);
m4 = _mm_unpackhi_epi32(t1,t2);
m3 = _mm_unpacklo_epi32(t1,t2);

Here is a full example
#include <x86intrin.h>
#include <stdio.h>

int main() {
        __m128i m1 = _mm_set_epi32(4,3,2,1);
        __m128i m2 = _mm_set_epi32(40,30,20,10);

        __m128i m3, m4, t1, t2;
        t1 = _mm_shuffle_epi32(m1, 0xd8);
        t2 = _mm_shuffle_epi32(m2, 0xd8);
        m4 = _mm_unpackhi_epi32(t1,t2);
        m3 = _mm_unpacklo_epi32(t1,t2);

        int out3[4], out4[4];
        _mm_store_si128((__m128i*)out3, m3);
        _mm_store_si128((__m128i*)out4, m4);
        printf("%d %d %d %d\n", out3[3], out3[2], out3[1], out3[0]);
        printf("%d %d %d %d\n", out4[3], out4[2], out4[1], out4[0]);
}

Output
30 3 10 1
40 4 20 2

A: I came up with a slightly different solution to Z Boson:
#include <emmintrin.h>
#include <iostream>
#include <cstring>

void print_data(const char *name, __m128i v)
{
    struct { int a, b, c, d; } unpacked;

    std::memcpy((void *)&unpacked, (void *)&v, sizeof(v));
    std::cout << name << ":";
    std::cout << unpacked.d << " " << unpacked.c << " "
          << unpacked.b << " " << unpacked.a << std::endl;
}

int main()
{

    __m128i m1 = _mm_set_epi32(4,3,2,1);
    __m128i m2 = _mm_set_epi32(40,30,20,10);
    __m128i mask = _mm_set_epi32(-1,0,-1,0);

    /*
     m3 = (30,3,10,1);
     m4 = (40,4,20,2);
    */

    __m128i tmp1 = _mm_shuffle_epi32(m2, 0x80);
    __m128i tmp2 = _mm_shuffle_epi32(m1, 0x31);
    __m128i m3 = _mm_or_si128(_mm_and_si128(mask, tmp1), _mm_andnot_si128(mask, m1));
    __m128i m4 = _mm_or_si128(_mm_and_si128(mask, m2), _mm_andnot_si128(mask, tmp2));

    print_data("m3", m3);
    print_data("m4", m4);
}

I'm sure the unpack variant is slightly better...


text:
Q: PHP upload to MySQL database with download and view file Does not download correctly: can't open the link. Help  appreciated. I am new to PHP and MySQL. I have MySQL set to BLOB for the content and I am not sure how to be clearer, I can see the link(s) for the file with the respective id to the file content $id in the url, but when I click on the link nothing opens up, I want to be able to open the file inthe brownser. I intend on being able to open .zip files and extract in later development. A sfar as security please also explain in good details so I can learn. I see my code was mod, but still not working in the array link.
UPLOAD.PHP:
<?php
$dbname="upload";
$host="localhost";
$user="SELF";
$pass="PICME";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
?>
<form method="post" enctype="multipart/form-data">

            <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
            <input name="userfile" type="file" id="userfile">

         <input name="upload" type="submit" class="box" id="upload" value=" Upload ">

</form>
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileType = $_FILES['userfile']['type'];
$fileSize = $_FILES['userfile']['size'];
$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (name, type, size, content) ".
"VALUES ('$fileName', '$fileType', '$fileSize', '$content')";
mysql_query($query) or die('Error, query failed');
echo "
File $fileName uploaded
";
}
?>'
(DOWNLOAD.PHP)FILE
'<?php
$dbname="upload";
$host="localhost";
$user="SELF";
$pass="PICME";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
$query = "SELECT id, name FROM upload";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0)
{
echo "Database is empty
";
}
else
{
while(list($id, $name) = mysql_fetch_array($result))
{
?>
<a href="download.php?id=<?php echo urlencode($id);?>"><?php echo urlencode($name);?>

<?php
}
}
exit;
?>
<?php
$dbname="upload";
$host="localhost";
$user="SELF";
$pass="PICME";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
$query = "SELECT id, name FROM upload";
if(isset($_GET['id']))
{
// if id is set then get the file with the id from database
$id    = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) =                     mysql_fetch_array($result);
$content = $row['content'];
header("Content-Disposition: attachment; filename=$name");
header('Content-type: image/jpeg' . $type); // 'image/jpeg' for JPEG images
header('Content-Length:' . $size);
exit;
print $content;
ob_clean();
flush();
echo $content;
}
?>

A: It seems you are not validating the Mime type of the file while uploading and setting Mimetype  for JPEG while downloading.
Please make sure you are uploading the correct file format.
Also, the id is urlencoded but not decoded while retrieving from DB.


text:
Q: JSF2: navigation flow question I am not sure if what I want is possible, but it worth a try to ask. Let say, I have 2 pages: List.jsf and CreateNew.jsf. List.jsf display data from datasource as <p:dataTable>. CreateNew.jsf insert a new entry into the datasource. What I want is from CreateNew.jsf, when I click create, it create a new entry in a database, then return back to List.jsf, but at this point List.jsf somehow refresh itself so that new entry will be displayed as well. Is it possible to achieve it? Couples thing worth to note: Managed bean for List.jsf is SessionScoped and the managed bean for CreateNew.jsf is RequestScoped
Navigation flow in handle inside faces-config.xml.

A: Either change the @SessionScoped bean associated with List.jsf to be @ViewScoped so that a new one is constructed, or add a method like reloadList() to the @SessionScoped bean, inject that as @ManagedProperty into the @RequestScoped bean and let it call that method after creating the new entry.


text: Q: Differentiable manifolds, Serge Lang I have started reading "Introduction to differentiable manifolds" by Serge Lang. In this book, Lang takes a different approach, by immediately introducing manifolds on arbitrary Banach spaces. His approach uses little to no multilinear algebra and he states the following in the foreword: "The orgy of multilinear algebra in standard treatises arises from unnecessary double dualization and an abusive use of the tensor product." What exactly does he mean by this? How is the use of the tensor product "abusive"?.Is there something inelegant about the traditional treatment of finite dimensional manifolds and differential forms on them?


text:
Q: Mergin pom.xml with that of parent I inherited a maven project whose structure is a bit confusing.
There is one home pom.xml in the parent folder, and yet another one in a child folder. This structure is a bit confusing since there the parent has nothing in it, other than doing managing the child.
Is there a way to merge the two? I tried doing so manually but failed. I think my problem lies with Tycho and the eclipse plugin.
Here is the child pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>my.project</groupId>
    <artifactId>my.project.foo.parent</artifactId>
    <version>2.4.0</version>
  </parent>
  <artifactId>my.project.foo</artifactId>
  <packaging>eclipse-plugin</packaging>
</project>

And the parent is:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>my.project</groupId>
  <artifactId>my.project.foo.parent</artifactId>
  <version>2.4.0</version>
  <packaging>pom</packaging>

  <properties>
    <tycho.version>0.24.0</tycho.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <mars-repo.url>http://download.eclipse.org/releases/mars</mars-repo.url>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <repositories>
    <repository>
      <id>mars</id>
      <url>${mars-repo.url}</url>
      <layout>p2</layout>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>my.project</groupId>
      <artifactId>my</artifactId>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>my.project</groupId>
      <artifactId>cli</artifactId>
      <version>1.0</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-maven-plugin</artifactId>
        <version>${tycho.version}</version>
        <extensions>true</extensions>
          <configuration>
            <encoding>UTF-8</encoding>
            <source>1.8</source>
            <target>1.8</target>
          </configuration>
      </plugin>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>target-platform-configuration</artifactId>
        <version>${tycho.version}</version>
        <configuration>
          <environments>
            <environment>
              <os>linux</os>
              <ws>gtk</ws>
              <arch>x86</arch>
            </environment>
            <environment>
              <os>linux</os>
              <ws>gtk</ws>
              <arch>x86_64</arch>
            </environment>
            <environment>
              <os>win32</os>
              <ws>win32</ws>
              <arch>x86</arch>
            </environment>
            <environment>
              <os>win32</os>
              <ws>win32</ws>
              <arch>x86_64</arch>
            </environment>
            <environment>
              <os>macosx</os>
              <ws>cocoa</ws>
              <arch>x86_64</arch>
            </environment>
          </environments>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-packaging-plugin</artifactId>
        <version>0.24.0</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-surefire-plugin</artifactId>
        <version>${tycho.version}</version>
      </plugin>
    </plugins>
  </build>
</project>

A: In the parent pom.xml change
<packaging>pom</packaging> to <packaging>eclipse-plugin</packaging>

and <artifactId>my.project.foo.parent</artifactId> to <artifactId>my.project.foo</artifactId>
Then, erase (or move) pom.xml in the child, and move everything in
the child folder to the parent folder. (If you do not erase it, it may override pom.xml in the parent.)


text:
Q: How to extend template script? I have the following template in my .gitlab-ci.yml file:
x-android-build-tools: &android_build_tools
  image: jangrewe/gitlab-ci-android
  stage: build
  script:
    - export GRADLE_USER_HOME=$(pwd)/.gradle
    - chmod +x ./gradlew
  artifacts:
    expire_in: 1 hours
    paths:
      - app/build/

I want to extend the script part to make actual builds. For example:
android-stage-build:
  <<: *android_build_tools
  environment: stage
  only:
    - dev
  after_script:
    - ./gradlew :app:assembleDebug

It works well, but it has a problem. Docker launches the both jobs instead of ignoring the template.
Is there way to run only the "android-stage-build" job which triggers the template job when it will be needed?

A: In order to make gitlab ci ignore the first entry, you need to add a dot (.) in front of the definition.
.x-android-build-tools: &android_build_tools
  image: jangrewe/gitlab-ci-android
  stage: build
  script:
    - export GRADLE_USER_HOME=$(pwd)/.gradle
    - chmod +x ./gradlew
  artifacts:
    expire_in: 1 hours
    paths:
      - app/build/

android-stage-build:
  <<: *android_build_tools
  environment: stage
  only:
    - dev
  after_script:
    - ./gradlew :app:assembleDebug

Besides that, I think, based on what I read here, you don't want to use after_script.
I think you want to use the before_script in the template, and on the build stage specific the script-key.
The main difference is that after_script also runs if the script fails. And by what I read here, it does not look like you would like that to happen.

A: Yes. You're simply missing a . :)
See https://docs.gitlab.com/ee/ci/yaml/yaml_optimization.html#anchors
It should work if you write it like this:
.x-android-build-tools: &android_build_tools
  image: jangrewe/gitlab-ci-android
  stage: build
  script:
    - export GRADLE_USER_HOME=$(pwd)/.gradle
    - chmod +x ./gradlew
  artifacts:
    expire_in: 1 hours
    paths:
      - app/build/

android-stage-build:
  <<: *android_build_tools
  environment: stage
  only:
    - dev
  after_script:
    - ./gradlew :app:assembleDebug


text:
Q: File name encoding in Python 2.7 I want to read files with special file names in Python (2.7). But whatever I try, it always fails to open them.
The filenames are
F\xA8\xB9hrerschein

and
Gro\xDFhandel

I know, the encoding was done with one of several codepages. I could try to find out which one and try to convert it and all the mumbo jumbo, but I don't want that.
Can't I somehow tell python to open that file without having to go through all that encoding stuff? I mean opening the file by its raw name in bytes?

A: After all, I fixed it with
reload(sys)
sys.setdefaultencoding('utf-8')

and setting the environment variable
LANG="C.UTF-8"

Thanks for the hints.

A: One way is to use os.listdir(). See the following example.
Add some data to a file with non-ascii character 0xdf in the name:
$ echo abcd > `printf "A\xdfA"`

Check that the file contains a non-ascii character:
$ ls A*
A?A

Start Python, read the directory and open the first file (which is the one with the non-ascii character):
$ Python
>>> import os
>>> d = os.listdir('.')
>>> d
['A\xdfA']
>>> f = open(d[0])
>>> f.readline()
'abcd\n'
>>>

A: If you have source code like
with open('Großhandel') as input:
    #stuff

You should look at Source Code Encodings and write
 #!python2
 # -*- coding: utf-8 -*-
 with open('Großhandel') as input:
 …

It is worth mention that the authors of PEP-263 are Marc-André Lemburg and Martin von Löwis, which I suppose makes pushing defined toward source encoding back in 2002 slightly more understandable.

A: Under Linux, filenames can be encoded in any character encoding. When opening a file, you must use the exact name encoded to match.
I.e. If the filename is Großhandel.txt encoded using UTF-8, it must be encoded as Gro\xc3\x9fhandel.txt.
If you pass a Unicode string to open(), the user's locale is used to encode the filename, which may match the filename.
Under OS X, UTF-8 encoding is enforced. Under Windows, the character encoding is abstracted by the i/o drivers. A Unicode object passed to open() should always be used for these Operating Systems, where it'll be converted appropriately.
If you're reading filenames from the filesystem, it would be useful to get decoded Unicode filenames to pass straight to open() - Well, you can pass Unicode strings to os.listdir().
E.g.
Locale: LANG=en_GB.UTF-8
A directory with the following files, with their filenames encoded to UTF-8:
test.txt
€.txt

When running Python 2.7 using a string:
>>> os.listdir(".")
['\xe2\x82\xac.txt', 'test.txt']

Using a Unicode path:
>>> os.listdir(u".")
[u'\u20ac.txt', u'test.txt']


text:
Q: How to remove parent element in case child elements are removed from DOM? Script
$scope.removableElement=['NAME','TITLE'];

Name

<input type="text" ng-if="removableElement.indexOf('NAME')!=-1"/>

<input type="text" ng-if="removableElement.indexOf('TITLE')!=-1"/>

Adress

<input type="text" ng-if="removableElement.indexOf('STATE')!=-1"/>

<input type="text" ng-if="removableElement.indexOf('CITY')!=-1"/>

Since, removableElement array does not contain "STATE" AND "CITY", 'div' containing these element should be removed. Please suggest.

A: First do the checking. Figure out the relationships, parent to child strong, but child to parent is a weak relationship.

Option 1 (much slower):

var myNode = document.getElementById("foo");
myNode.innerHTML = '';
Option 2 (much faster):

var myNode = document.getElementById("foo");
while (myNode.firstChild) {
    myNode.removeChild(myNode.firstChild);
}


text:
Q: Connecting Seekbar with Hardware buttons on device import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class pushke extends Activity {

    private SeekBar volumeSeekbar = null;
    private AudioManager audioManager = null;
      MediaPlayer mp;
      MediaPlayer mp2;
      MediaPlayer mp3;
      MediaPlayer mp4;
      MediaPlayer mp5;
      MediaPlayer mp6;
      SeekBar seekGuns;
      RelativeLayout rguns;

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            setContentView(R.layout.guns);
            initControls();
           rguns=(RelativeLayout) findViewById(R.id.rguns);

mp=MediaPlayer.create(this, R.raw.hekler);
ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        if (mp2.isPlaying()){
            mp2.pause();
            mp2.seekTo(0);
        }
        if (mp3.isPlaying()){
            mp3.pause();
            mp3.seekTo(0);
        }
        if (mp4.isPlaying()){
            mp4.pause();
            mp4.seekTo(0);
        }
        if (mp5.isPlaying()){
            mp5.pause();
            mp5.seekTo(0);

        }
        if (mp6.isPlaying()){
            mp6.pause();
            mp6.seekTo(0);

        }
        if (mp.isPlaying()){
            mp.pause();
            mp.seekTo(0);
        }
        else{
            mp.start();
        }

    }
});
}
     private void initControls()
    {
        try
        {
            volumeSeekbar = (SeekBar)findViewById(R.id.seekGuns);
            audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            volumeSeekbar.setMax(audioManager
                    .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
            volumeSeekbar.setProgress(audioManager
                    .getStreamVolume(AudioManager.STREAM_MUSIC));

            volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
            {
                @Override
                public void onStopTrackingTouch(SeekBar arg0)
                {
                }

                @Override
                public void onStartTrackingTouch(SeekBar arg0)
                {
                }

                @Override
                public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
                {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                            progress, 0);
                }
            });
        }
        catch (Exception e)
        {
            e.printStackTrace();

        }
    }
  @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
   {
          int index = seekGuns.getProgress();
          seekGuns.setProgress(index + 1);
          return true;
   } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
    {
          int index = seekGuns.getProgress();
          seekGuns.setProgress(index - 1);
          return true;
   }
    return super.onKeyDown(keyCode, event);
   }

I am trying to connect hardware buttons to my seekbar so when I click on volume buttons, seekbar which is used for volume, increase-decrease depending on which button I pressed.
I got this code which is supposed to be working, but I have no idea why it's not working in my case, everytime I launch my app on phone as emulator, and use hardware volume button app crashes.
I get this in LoGcat but Ican't figure out how to fix it or where is the problem because eclipse is not showing me any errors.
Here is my logcat: http://i.imgur.com/o4qSvCv.png

A: This is because you have declared two Seekbar variables.
 private SeekBar volumeSeekbar = null;
 SeekBar seekGuns;

and in your onKeyDown method you are using seekGuns named variable which is not initialized.
So you have two option.
1) Initialize means find the id for seekguns variable.
2) Use volumeSeekbar instead of seekguns in onKeyDown method.