text:
Q: PhpStorm and phpDocumentor For several hours trying to add phpDocumentor to PhpStorm , I used a few instruction:
http://kevinquillen.com/ide/2015/02/01/setting-up-phpdocumentor-in-phpstorm-8
Now it looks like
this
But when I run phpdoc I got this :
C:\xampp\php\php.exe phpdoc -d c:\dokumentacja_php\folder_zrodlowy -t c:\dokumentacja_php\folder_docelowy
Collecting files .. OK
Initializing parser .. OK
Parsing files
Parsing C:\dokumentacja_php\folder_zrodlowy\Test.php
Storing cache in "C:\dokumentacja_php\folder_docelowy" .. OK
Load cache                                                         ..    0.010s
Preparing template "clean"                                         ..    0.019s
Preparing 17 transformations                                       ..    0.000s
Build "elements" index                                             ..    0.000s
Replace textual FQCNs with object aliases                          ..    0.000s
Resolve @link and @see tags in descriptions                        ..    0.000s
Enriches inline example tags with their sources                    ..    0.000s
Build "packages" index                                             ..    0.002s
Build "namespaces" index and add namespaces to "elements"          ..    0.000s
Collect all markers embedded in tags                               ..    0.000s
Transform analyzed project into artifacts                          ..
Applying 17 transformations
  Initialize writer "phpDocumentor\Plugin\Core\Transformer\Writer\FileIo"
  Initialize writer "phpDocumentor\Plugin\Twig\Writer\Twig"
  Initialize writer "phpDocumentor\Plugin\Graphs\Writer\Graph"
  Execute transformation using writer "FileIo"
  Execute transformation using writer "FileIo"
  Execute transformation using writer "FileIo"
  Execute transformation using writer "FileIo"
  Execute transformation using writer "FileIo"
  Execute transformation using writer "twig"
  Execute transformation using writer "twig"
  Execute transformation using writer "twig"
[2016-01-17 02:59:54] phpDocumentor.ALERT: Fatal Error (E_ERROR): Uncaught TypeError: Argument 1 passed to Monolog\ErrorHandler::handleException() must be an instance of Exception, instance of Error given in C:\xampp\php\pear\phpDocumentor-2.8.5\phpDocumentor-2.8.5\vendor\monolog\monolog\src\Monolog\ErrorHandler.php:122 Stack trace: #0 [internal function]: Monolog\ErrorHandler->handleException(Object(Error)) #1 {main}   thrown {"code":1,"message":"Uncaught TypeError: Argument 1 passed to Monolog\\ErrorHandler::handleException() must be an instance of Exception, instance of Error given in C:\\xampp\\php\\pear\\phpDocumentor-2.8.5\\phpDocumentor-2.8.5\\vendor\\monolog\\monolog\\src\\Monolog\\ErrorHandler.php:122\nStack trace:\n#0 [internal function]: Monolog\\ErrorHandler->handleException(Object(Error))\n#1 {main}\n  thrown","file":"C:\\xampp\\php\\pear\\phpDocumentor-2.8.5\\phpDocumentor-2.8.5\\vendor\\monolog\\monolog\\src\\Monolog\\ErrorHandler.php","line":122} []
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta charset="utf-8"/>
    <title>API Documentation</title>
    <meta name="author" content=""/>
    <meta name="description" content=""/>

    <link href="../css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
    <link href="../css/font-awesome.min.css" rel="stylesheet">
    <link href="../css/prism.css" rel="stylesheet" media="all"/>
    <link href="../css/template.css" rel="stylesheet" media="all"/>

    <link rel="shortcut icon" href="../images/favicon.ico"/>
    <link rel="apple-touch-icon" href="../images/apple-touch-icon.png"/>
    <link rel="apple-touch-icon" sizes="72x72" href="../images/apple-touch-icon-72x72.png"/>
    <link rel="apple-touch-icon" sizes="114x114" href="../images/apple-touch-icon-114x114.png"/>

            API Documentation

                            Charts

                                     Class hierarchy diagram

                            Reports

                                                                                Errors 5

                                                                                Markers 0

                                                                                Deprecated 0

                                \

Test

                                                \

\Test

Created by PhpStorm.

Notice: Array to string conversion in C:\xampp\php\pear\phpDocumentor-2.8.5\phpDocumentor-2.8.5\vendor\erusev\parsedown\Parsedown.php on line 1405

Notice: Undefined property: Parsedown::$Array in C:\xampp\php\pear\phpDocumentor-2.8.5\phpDocumentor-2.8.5\vendor\erusev\parsedown\Parsedown.php on line 1405

Fatal error: Uncaught TypeError: Argument 1 passed to Monolog\ErrorHandler::handleException() must be an instance of Exception, instance of Error given in C:\xampp\php\pear\phpDocumentor-2.8.5\phpDocumentor-2.8.5\vendor\monolog\monolog\src\Monolog\ErrorHandler.php:122
Stack trace:
#0 [internal function]: Monolog\ErrorHandler->handleException(Object(Error))
#1 {main}
  thrown in C:\xampp\php\pear\phpDocumentor-2.8.5\phpDocumentor-2.8.5\vendor\monolog\monolog\src\Monolog\ErrorHandler.php on line 122
PHP Notice:  Array to string conversion in C:\xampp\php\pear\phpDocumentor-2.8.5\phpDocumentor-2.8.5\vendor\erusev\parsedown\Parsedown.php on line 1405
PHP Notice:  Undefined property: Parsedown::$Array in C:\xampp\php\pear\phpDocumentor-2.8.5\phpDocumentor-2.8.5\vendor\erusev\parsedown\Parsedown.php on line 1405
PHP Fatal error:  Uncaught TypeError: Argument 1 passed to Monolog\ErrorHandler::handleException() must be an instance of Exception, instance of Error given in C:\xampp\php\pear\phpDocumentor-2.8.5\phpDocumentor-2.8.5\vendor\monolog\monolog\src\Monolog\ErrorHandler.php:122
Stack trace:
#0 [internal function]: Monolog\ErrorHandler->handleException(Object(Error))
#1 {main}
  thrown in C:\xampp\php\pear\phpDocumentor-2.8.5\phpDocumentor-2.8.5\vendor\monolog\monolog\src\Monolog\ErrorHandler.php on line 122

Process finished with exit code 255

Unfortunately, I do not know what I'm doing wrong . Did anyone have a similar problem ?

A: Marcin,
firstly, change PHP version to PHP5. PHP7 isn't supported by PHPDocumentator yet.
secondly, it would be better to use that in Parameters field:
phpDocumentor.phar -d $ProjectFileDir$ -t $ProjectFileDir$\Docs

$ProjectFileDir$ - is an absolute path to project root dir, generated automaticaly by PHPStrom macro's.

Regards,
Piotr


text:
Q: Pressure sensor unstable after Arduino power off/on I am using my Arduino Uno to read analog sensor values from this pressure sensor.
I have the Arduino powered with a 12V power supply from the wall. I'm using the 5V from the arduino for the LCD and an 8ch relay board as well.
The sensor is just connected to the 5V, GND and the signal goes to analog input 3. I calibrated the sensor 4 times already, because it keeps giving me unstable values after I pull the power supply out:

The sensor is fixed at the bottom of the water tank, and shielded from water with silicone. Therefore the pressure load is already constant. (e.g. 25 cm h2o).  With calibration procedure I meant that I increased stepwise the waterheight, and measured the output signal and then let excel make a linear fit with an equation, which I implement in the software.
As you can see, the sensor's response is quite linear every time, but for me it seems like a sort of offset problem. When I used an external power supply and measured the voltage of the sensor with a DMM, it seemed stable, going to the same voltage every time.
Has anyone an idea what is going wrong, or what I have to add or something? (Already read something about adding a capacitor but I don't think it's a short-time interval).
I'm new to this site and just started with programming with Arduino.
(I'm trying to make my aquarium refresh water automatically).
-EDIT: Thanks everyone for the suggestions. I didn't solve the problem with the pressure sensor, but I'm pretty sure it was the problem that the differential p2 was blocked and therefore the reference pressure wrong. Since I indeed want to measure continuously for a long time, the hose like in a washing is no solution for me. I decided to do it with an ultrasonic (hc-sr04) sensor. This works fine! Problem solved:)

A: The sensor has two holes. On first big, you have the attachemnt of the hose. Second is below your sensor, it is breathing hole that transmits atmospheric pressure. Since you have poured the sensor with silicone and submerged into the water is clearly no go solution. Remove the silicone and attach a hose, and use the sensor like in instruction manual.
I suspect you want to measure level of water continously, in that case the hose will leak pressure at long term, and it will be useless. This kind of sensor are used in maching machines, where the water goes away and then is filled again, air leaking trough the hose can be neglected.
Since you already flooded the sensor, install a hose and bore the wall at the bottom, put the sensor in upside down position, externaly - not submerged obviously.

A: I think @Marko has correctly identified the problem. The pressure transducer is differential - it measures the difference in pressure between P1 and P2 as shown in Figure 3 in the datasheet.

Figure 3 from datasheet.

Figure 3
   illustrates the gauge configuration in the basic chip carrier
   (case 98ASB17756C). A fluorosilicone gel isolates the die
  surface and wire bonds from the environment, while allowing the pressure signal to be transmitted to the silicon diaphragm.
The MPxx5004 series sensor operating characteristics are based on
  use of dry air as pressure media. Media, other than dry air,
  may have adverse effects on sensor performance and long-term reliability. Internal reliability and qualification test for dry air, and
  other media, are available from the factory. Contact the factory for information regarding media tolerance in your application.

You need to vent P2 to atmosphere and monitor the pressure at P1 without getting it wet.

A: The reasons suggested above are physically wrong: blocking the reference outlet should not change the calibrated value. It might however make your calibration curve nonlinear which is not the case in the original question (since the gas in the blocked chamber is not in equilibrium with an infinite 1 ATM reservoir, but rather finite. Simply put, the volume taken by the membrane 'inflating' is not insignificant, and pressure higher than 1 ATM can build up in the blocked chamber). In other words, repeating the experiment should yield similar results. Otherwise the sensor or electronics are noisy. I suspect the Arduino voltage is not stable between resets, even further so when powered from USB.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get a new instance of a durandal viewmodel with every system.acquire I'm using the hottowel template and I'm trying to load views dynamically on to a dashboard type view.
The views should also be able to be viewed individually.
So lets say i have a graph view. I want to be able to navigate to it like this :"mysite.com/#/graph/1".
I should also be able to compose the view through ko bindings into the dashboard view.
What I'm doing right now is to on the activate method of the dashboard load a users saved dashboard views. Like this:
dashboard activate
function activate() {

        return datacontext.getUserDashboardConfigurations(userId)
        .then(function (data) {

            _.each(data.elements(), function (view) {
                system.acquire("viewmodels/" + view.viewType()).then(function (model) {
                    var newModel =  model.create(); //factory method
                    newModel.__moduleId__ = model.__moduleId__;
                    newModel.viewSettingsId(view.SettingsId());
                    views.push(newModel);
                });
            });

            vm.showLoad(false);
        });
    }

I probably haven't understood how durandal and/or require correctly. But the model returned by the acquire method is the same for every view of the same type. 3 graph views composed to the dashboard all gets the same instance of the graph model. So what I did was to create a sort of factory method for the model.
Graph model
define( function(logger, dataContext) {

    function model() {
        var viewSettingsId= ko.observable(0);

        function activate() {
        //omitted
        }

        function viewAttached(view) {
            //omitted
        }

        return {
            activate: activate,
            title: 'Graph View',
            viewSettingsId: viewSettingsId
        };
    }

    return {
        create: function() {
            return new model();
        }
    };
});

ko binding

router overridden
  router.getActivatableInstance = function(routeInfo, params, module) {
        if (typeof module == 'function') {
            return new module();
        } else {
            if (module.create && typeof module.create == 'function') {
                var newModule = module.create();
                newModule.__moduleId__ = module.__moduleId__;

                return newModule;
            }
            return module;
        }
    };

This sort of solves the problem for the dashboard. Navigation also work. But I feel that there must be a better solution. Maybe durandal widgets? But I want to have them as normal views and "widgets" on the dashboard. How can I solve this in a cleaner way?

A: I solved it. I found the samples, duh. I have overlooked that link in the documentation.
The master detail sample made it clear. Changed viewmodel to use the prototype pattern in the example. Then use the viewmodel.activateItem after system.acquire.
Then compose the views like the example. Works and feels cleaner!
dashboard activate
function activate() {
        return datacontext.getUserDashboardConfigurations(userId)
        .then(function (data) {

            currentDashboardconfiguration = data;

            _.each(data.elements(), function (view) {

                system.acquire("viewmodels/" + view.viewType()).then(function (model) {

                    var newModel = new model();

                    viewModel.activator().activateItem(newModel, { id: view.viewSettingsId() }).then(function (suc) {
                        views.push(newModel);
                    });
                });
            });

            vm.showLoad(false);
        });
}

graph model
define( function(logger, dataContext) {

    var ctor = function()
    {
        this.viewSettingsId = ko.observable(0);
        this.title: 'Graph View',
    }

    ctor.prototype.activate = function() {
        //omitted
     }

    ctor.prototype.viewAttached = function(view) {
       //omitted
    }

    return ctor;
});

ko binding


text:
Q: Contribution in Rift: Invasions, Rifts, Footholds and other events All of these events in Rift have a contribution meter.  How exactly is contribution calculated for these?  Furthermore, what might be the best way to maximize contribution per event?
Some rifts I noticed I don't contribute as much as other rifts but I feel like i'm doing the same thing.

A: Currently, no one really knows the EXACT quantification of contribution as it relates to events. A few solid facts are known, however:

*

*Contribution is gained for each action taken.

*Contribution scales based on the presumed length of an event - the Unstable Stages of a major rift will give less contribution per action than the first stage of a level 7 minor Rift.

*Number of targets matters. A Bard using Motif of Bravery on 25 raid members will give more contribution than channeling Cadence upon one target.

A: Update:
With version 1.1. there the contribution meter got removed. Before version 1.1 the contribution was primary calculated simply
on APM (action per minute). Pre version 1.1 the correct answer should have been "Do as much actions as you can". One way to
optimize the contribution was to switch to a role with the ability to spam as much actions as possible. If you were playing a
Rogue switch to Bard and spam Motifs while fighting event based invasions, rift or bosses.
With version 1.1 the contribution got normalised between the roles/souls. You'll get virtual the same amount of loot whatever
your role/soul combination is. You'll only have to participate a limited amount at the event to get the chance for the rare
or epic planarite drop. I remeber several times i had to fight a handful invasions while questing and got a rare or epic drop.
In version 1.1 it was better to fight invasions because for the amount of effort you got much more planarit comparing to
close rift (and if you defending a soulstone the invasions will come to you). With version 1.2 the amount of planarite for
fighting invasions got reduced to a third, but still give you more planarite comparing to the effort colsing rifts.
Old answer:
There is no exact calculation known but the Rift Wiki has some valuable explanations: http://telarapedia.com/wiki/Rift#Player_Rewards
A major factor is that you not fail the challange in the unstable stages (which get players "into higher contribution categories").
Contribution rating is based on tanking, buffing, healing and damage comparing to other players taking part on the rift event (the rating is adjusted on the player level). There are for sure other factors like the level and scale of the rift (some can be singled for other you'll need a group) and random dice for blue and purple tokens (because they're limited per rift event).
tl;nr: Don't fail in the unstable stages and tank, heal, buff,, do damge as much as you can.


text:
Q: How Can Retrieving child value from root firebase url How Can Access Name,Email,Contact etc. from root firebase url.
Means RootUrl --> UserDetails --> Ad --> Ad123 --> Name,Email etc.
I Used below Code But It not Retrieving data from database and toast not appearing.
The Code Image is Attached.Data Structure Image
Code for retrieving data from databse

A: Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("UserDetails").child("Ad").child("Ad123");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String contact = dataSnapshot.child("Contact").getValue(String.class);
        String dob = dataSnapshot.child("DOB").getValue(String.class);
        String departemnt = dataSnapshot.child("Departemnt").getValue(String.class);
        //and so on
        Log.d("TAG", contact + " / " + dob + " / " + departemnt);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(eventListener);

A: You have to point out to a node of a Firebase. For that you could use -
 DatabaseReference ref = rootRef.child("UserDetails/Ad/Ad123");


text:
Q: How do I add a batch of models to a collection that already has items? I'm building a news feed. On initialization, the app calls Collection.fetch() and receives 20 stories.
Then, when a user clicks "load more", I want to fetch 20 more stories, and add it to the collection. (I will hit a URL to do this.)
However, .fetch resets the collection. How can I hit a URL and download more stories without resetting the collection?

A: Pass {add: true} as an option to fetch.


text:
Q: Architecting a Docker Swarm with persistent storage I'm having a small amount of trouble pinning down exactly how I want to architect my Docker Swarm cluster. Currently it consists of:

*

*1 MariaDB which will need to have persistent storage suitable for a database.

*2 x MediaWiki servers which will need to have persistent storage suitable for storing images, videos and other media files.

*Some kind of ingress that will map a domain name to each of the MediaWiki servers based on domain name.
I could do with some feedback on possible ways of architecting this. Ideally I'd like all three servers to contain instances of the MediaWiki application or perhaps 2 servers and 1 dedicated host server for the database. One MediaWiki application receives around 20x the traffic of the other so would benefit running over multiple machines.
The trouble I'm having is trying to persist data between deployments. I'm currently considering something like CephFS with block storage mounted into one master host and two slave instances replicating from that.
I also have not explored the ingress component yet but I'm assuming I can configure some kind of Nginx server, ideally with Lets Encrypt enabled, that will proxy traffic to either of the MediaWiki hostnames depending on the incoming domain name, however this may be a naive assumption.

A: You are going way over the top with ceph to store images. You are bound for failure on that.
Run it all in swarm but store your media on a block storage like AWS S3 for example. If you don't use a provider with something like S3 then look into
https://minio.io/
Its API compatible with S3. The benefit being most all major software has options in it for S3.


text:
Q: Will limiting OR conditions in your SQL can fix SQL injection vulnerbilty? Our website was reported as vulnerable to SQL injection and the developer who fixed this vulnerability was telling that they have to limit the OR clauses in the search criteria.
Previously users used to search with like 500 orders which is now limited. As he is saying as per SQL injection practice, you have to limit OR conditions in your SQL.
For example following log is showing those OR conditions, which as per his claim are limited.
Is it fine? and his claim is right?
Edit: Database is Oracle 11.2.
Conditions:
and (UPPER(online_order_id) LIKE :param_online_order_id0
or UPPER(online_order_id) LIKE :param_online_order_id1
or UPPER(online_order_id) LIKE :param_online_order_id2
or UPPER(online_order_id) LIKE :param_online_order_id3
or UPPER(online_order_id) LIKE :param_online_order_id4
or UPPER(online_order_id) LIKE :param_online_order_id5
or UPPER(online_order_id) LIKE :param_online_order_id6
or UPPER(online_order_id) LIKE :param_online_order_id7
or UPPER(online_order_id) LIKE :param_online_order_id8
or UPPER(online_order_id) LIKE :param_online_order_id9
or UPPER(online_order_id) LIKE :param_online_order_id10
or UPPER(online_order_id) LIKE :param_online_order_id11
or UPPER(online_order_id) LIKE :param_online_order_id12
or UPPER(online_order_id) LIKE :param_online_order_id13
or UPPER(online_order_id) LIKE :param_online_order_id14
or UPPER(online_order_id) LIKE :param_online_order_id15
or UPPER(online_order_id) LIKE :param_online_order_id16
or UPPER(online_order_id) LIKE :param_online_order_id17
or UPPER(online_order_id) LIKE :param_online_order_id18
or UPPER(online_order_id) LIKE :param_online_order_id19
or UPPER(online_order_id) LIKE :param_online_order_id20
or UPPER(online_order_id) LIKE :param_online_order_id21
or UPPER(online_order_id) LIKE :param_online_order_id22
or UPPER(online_order_id) LIKE :param_online_order_id23
or UPPER(online_order_id) LIKE :param_online_order_id24
or UPPER(online_order_id) LIKE :param_online_order_id25
or UPPER(online_order_id) LIKE :param_online_order_id26
or UPPER(online_order_id) LIKE :param_online_order_id27
or UPPER(online_order_id) LIKE :param_online_order_id28
or UPPER(online_order_id) LIKE :param_online_order_id29
or UPPER(online_order_id) LIKE :param_online_order_id30
or UPPER(online_order_id) LIKE :param_online_order_id31
or UPPER(online_order_id) LIKE :param_online_order_id32
or UPPER(online_order_id) LIKE :param_online_order_id33
or UPPER(online_order_id) LIKE :param_online_order_id34
or UPPER(online_order_id) LIKE :param_online_order_id35
or UPPER(online_order_id) LIKE :param_online_order_id36
or UPPER(online_order_id) LIKE :param_online_order_id37
or UPPER(online_order_id) LIKE :param_online_order_id38
or UPPER(online_order_id) LIKE :param_online_order_id39
or UPPER(online_order_id) LIKE :param_online_order_id40
or UPPER(online_order_id) LIKE :param_online_order_id41
or UPPER(online_order_id) LIKE :param_online_order_id42
or UPPER(online_order_id) LIKE :param_online_order_id43
or UPPER(online_order_id) LIKE :param_online_order_id44
or UPPER(online_order_id) LIKE :param_online_order_id45
or UPPER(online_order_id) LIKE :param_online_order_id46
or UPPER(online_order_id) LIKE :param_online_order_id47
or UPPER(online_order_id) LIKE :param_online_order_id48
or UPPER(online_order_id) LIKE :param_online_order_id49
or UPPER(online_order_id) LIKE :param_online_order_id50
or UPPER(online_order_id) LIKE :param_online_order_id51
or UPPER(online_order_id) LIKE :param_online_order_id52
or UPPER(online_order_id) LIKE :param_online_order_id53
or UPPER(online_order_id) LIKE :param_online_order_id54
or UPPER(online_order_id) LIKE :param_online_order_id55
or UPPER(online_order_id) LIKE :param_online_order_id56
or UPPER(online_order_id) LIKE :param_online_order_id57
or UPPER(online_order_id) LIKE :param_online_order_id58
or UPPER(online_order_id) LIKE :param_online_order_id59
or UPPER(online_order_id) LIKE :param_online_order_id60
or UPPER(online_order_id) LIKE :param_online_order_id61
or UPPER(online_order_id) LIKE :param_online_order_id62
or UPPER(online_order_id) LIKE :param_online_order_id63
or UPPER(online_order_id) LIKE :param_online_order_id64
or UPPER(online_order_id) LIKE :param_online_order_id65
or UPPER(online_order_id) LIKE :param_online_order_id66
or UPPER(online_order_id) LIKE :param_online_order_id67
or UPPER(online_order_id) LIKE :param_online_order_id68
or UPPER(online_order_id) LIKE :param_online_order_id69
or UPPER(online_order_id) LIKE :param_online_order_id70
or UPPER(online_order_id) LIKE :param_online_order_id71)

A: It's common to see SQL injections in code performing this type of function, because the code puts together an in clause formed by concatenating values together (often with no validation).
As several folks have pointed out in the comments - it's likely that your developer fixed a SQL injection, but did it in a manner that is likely to cause performance problems and other limitations.   The developer is correctly following the general guidance to use parameterized queries (bind variables) but following that guidance blindly does not work well in this case.
The best way to fix this (as Damien_The_Unbeliever mentions) is to bind this to an array type on the Oracle DB side - this requires only one bind, and will give you the best performance.  This requires the addition of an object on the DB side, so is more complex to implement.
The other option is to continue to use the in clause but ensure the code validating the values as they are being concatenated in - in the case of an order ID it's likely that you can just check that it is an integer.  This will not perform as well as the first option, but will handle larger number of orders more gracefully.


text:
Q: How to start a Console App as running under the System Windows user account? I tried
var process = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = filename,
        UserName = "System",
        UseShellExecute = false,
    },
};

process.Start();

but it yields

Win32Exception was unhandled
Login failed: unknown user name or wrong password

I will have to use CreateProcessAsUser?
How can I get the appropriate parameters to pass to that method?

A: The System accounts password is maintained interally by Windows (I think) i.e. attempting to start a process as the System account by supplying credentials in this way is ultimately destined to failure.
I did however find a forum post that describes a neat trick that can be used to run processes under the system account by (ab)using windows services:
Tip: Run process in system account (sc.exe)
Alternatively the Windows Sysinternals tool PsExec appears to allow you to run a process under the System account by using the -s switch.

A: The Username should be LocalSystem if you want to run your process with high privileges (it's a member of Administrators group) or LocalService for normal privileges
EDIT: My mistake LocalSystem & LocalService are not regulary users and, therefore, they cannot be provided as a username. Kragen's solution is the right one


text:
Q: how to concatenate variable and speical character using php I want to concatenate the following two variables $path1 and $path2 to get $path and then concatenate $path with $filename to get $fullpath. Any help would be appreciated.
$path1="images"
$path2= "\"

$path = $path1+$path2

$fullpath=$path + $filename

A: $path1="images"
$path2= "\\"

$path = $path1.$path2

$fullpath=$path.$filename

Remember that you have to escape character \ (using the escape character \). Finally string concatenation in PHP is performed using the . operator

A: You can use concatenation operator ('.') in php.
$path1 = "images";
$path2 = "\";

$path = $path1.$path2;

$fullpath = $path.$filename;

A: PHP uses . (dot) to concatenate strings, not +, so try that instead.
Manual reference: http://php.net/manual/en/language.operators.string.php

A: You can use dot(.) for concatenate in php like
$path = $path1.$path2

$fullpath=$path.$filename


text:
Q: Passport-ldapauth: Error: getaddrinfo ENOTFOUND This is how i set up my passport-ldapauth strategy:
let OPT = {
    server: {
        url: 'ldap://****:389',
        bindDN: "",
        bindCredentials: "",
        searchBase: 'ou=Users,dc=astron,dc=hu',
        searchFilter: "(uid={{username}})"
    },
    usernameField: 'username',
    passwordField: 'password',
};
passport.use(new LdapStrategy(OPT, function (user, done) {
    if (user != null) {
        return done(null, user);
    } else return done(new Error("i dont know"), null)
}))
app.use(passport.initialize())

This is where is use it:
 async authenticate(req, res): Promise < boolean > {
         return new Promise < boolean > ((resolve,
                     reject) => {
                     let authenticate: express.RequestHandler = <express.RequestHandler>passport.authenticate('ldapauth', (error, user, info) => {
                if (error) {
                    return reject(error);
                }
                if (!user) {
                    return resolve(false);
                }
                req.user = user;
                resolve(true);
            });
            authenticate(req, res,
                null);
        }
        )
    }

And i get this error:

Error: getaddrinfo ENOTFOUND **** ****:389
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)

My question would be why do i get the error? I am sure the url and the username/password is correct.

A: There is only one meaning of this error, your node application is not able to connect to ldap server. May be you are giving correct ip/host but its not accessible from the machine where you are running node application.
You can try to connect to ldap with some tools from the same machine and see if it is able to connect to server.

A: I have same error when developing. I used restify (let restify = require('restify')) to make https call, in console it shows ENOTFOUND error without specific context.
Then I switch to use other approach

*

*https (require('https'))

*xhr (const XMLHttpRequest = require('xhr2'))

I use both to make ajax call to the same API. It works without error.


text:
Q: How to install new version of Netbeans without lost project data? I'm using Netbeans 7.1.1. Yesterday I checked Netbeans new version and got 7.1.2 version. Then I want to update Netbeans to version 7.1.2, but Netbeans doesn't auto detect previous version and remove it before install. And I don't wanna lose current projects data too! How to install Netbeans new version with remove previous version and keep projects data?

A: Per-project data is stored in a separate directory for each project; by default this directory is .netbeans directly inside the project root, but it's customizable. Uninstalling the previous version does not touch any of this data so no problem there.
Configuration applicable to NetBeans itself goes into your home directory by default; the uninstaller gives you the option of not deleting that, so do not check "NetBeans user directory" when uninstalling and you should be fine.


text:
Q: How can access Scala JDBC connection in Python Notebook ---Databricks I have a connection object in Scala cell, which I would like reuse it in Python cell.
Is there alternate to temp table to access this connection.
Databricks

A: Not really - Python code is executed in the different context, so you can have some data exchange either via SparkSession itself (.set/.get on the SparkConf, but it works only for primitive data), or by registering the temp view


text:
Q: Equivalent condition for base of a root system In Humphrey's Lie algebra, following is the definition of base of a root system.

Let $\Phi$ be a root system in standard Euclidean space $\mathbb{R}^n$. A subset $\Delta$ of $\Phi$ is called as a base of $\Phi$ if
(1) $\Delta$ is basis of the vector space $\mathbb{R}^n$.
(2) Every $\alpha$ in $\Phi$ is a $\mathbb{Z}$-combination of elements of $\Delta$ with coefficients either all non-negative or all non-positive.

The elements of a base have property that their inner product is non-positive: $(\alpha,\beta)\leq 0$ for all $\alpha,\beta\in\Delta$  with $\alpha\neq\beta$.
Question: Suppose $\Delta'$ is a subset of $\Phi$ with condition that
(1) $\Delta'$ is a basis of the vector space $\mathbb{R}^n$.
(2) For any $\alpha\neq \beta$ in $\Delta'$, $(\alpha,\beta)\leq 0$. Then is $\Delta'$ necessarily a base of $\Phi$?


text:
Q: (Non)Existence of matrices $A,B\ne0$ with $AB=0\ne BA$ Do there exist non-zero matrices $A,B$ such that $AB=0$ and $BA\ne 0$?

A: Sure.
$$A=\left[\begin{array}{cc}0 & 1\\0 &0\end{array}\right],\quad B=\left[\begin{array}{cc}1 & 0\\0 & 0\end{array}\right].$$

A: Yes there exist such matrices.
Find them.


text:
Q: Android - How to set color of a TextView and background together with SharedPreferences in my app I have a menu button called "Settings" in which I can choose what colours set up to the background of some layout. Unfortunately I combine two layouts together to show what I want to show, and the problem is that I can only set background colour (that is in a layout) but not the the colour of TextView (that is in the other layout).
Layout main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/main_layout">
<EditText
android:id="@+id/editText1"
android:layout_height="65dip"
android:layout_marginTop="2dip"
android:hint="Scrivi"
android:layout_width="fill_parent" />
<ListView android:id="@+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:fastScrollEnabled="true">
</ListView>
</LinearLayout>

Layout listitem_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/main_layout">
<TextView
android:id="@+id/textView1"
android:text="TextView"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="fill_parent">
</TextView>
<TextView
android:text="TextView"
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>

MainActivity:
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SearchCocktail extends Activity{
EditText ed;
ListView lview;

String[] first = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",     "Nine", "Ten"};

String[] second = { "Uno", "Due", "Tre", "Quattro", "Cinque", "Sei", "Sette", "Otto",  "Nove", "Dieci"};

int textlength = 0;
ArrayList<String> first_sort = new ArrayList<String>();
ArrayList<String> second_sort = new ArrayList<String>();

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ed = (EditText) findViewById(R.id.editText1);
lview = (ListView) findViewById(R.id.list);
lview.setAdapter(new MyCustomAdapter(first, second));
...........
public View getView(int position, View convertView, ViewGroup parent){

LayoutInflater inflater = getLayoutInflater();
View row;

row = inflater.inflate(R.layout.listitem_row, parent, false);

TextView textview = (TextView) row.findViewById(R.id.textView1);
TextView textview1 = (TextView) row.findViewById(R.id.textView2);

textview.setText(data_first[position]);
textview1.setText(data_second[position]);

return (row);
}
}

@Override
protected void onResume(){
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();

String colorePref = prefs.getString(PreferencesFromXml.COLORE_PREF,  PreferencesFromXml.COLORE_DEFAULT);
int coloreDiSfondo = Color.parseColor(colorePref);
findViewById(R.id.list).setBackgroundColor(coloreDiSfondo);
editor.commit();
}
}

PreferencesFromXml activity:
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class PreferencesFromXml extends PreferenceActivity{

public static final String COLORE_DEFAULT = "#000000";

public static final String COLORE_PREF = "colore";

public static final String TITOLO_PREF = "titolo";

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.preferences);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    Editor editor = prefs.edit();

    Preference titoloPrefs = findPreference(TITOLO_PREF);
    titoloPrefs.setSummary(prefs.getString(TITOLO_PREF, getString(R.string.titolo_custom)));
    titoloPrefs.setOnPreferenceChangeListener(new OnPreferenceChangeListener()
    {
        public boolean onPreferenceChange(Preference prefs, Object value)
        {
            prefs.setSummary((CharSequence) value);
            return true;
        }
    });editor.commit();
}
}

With my code I can change background colour of layout main.xml but I want change also the TextView colour of listitem_row.xml. I'd like to change the colours together (example: black colour for background and white colour for the text or white colour for the background and black colour for the text, etc.). How can I proceed? Thanks to everyone who can answer.

A: I don't think I understood PreferenceActivity, PreferenceManager, or your question when I first answered.  Your problem is with styling your list, not with storing your preferences, right?
I think setting a theme on the activity might be a solution.  This post talks about how to update text colors when the theme is changed. Styles and Themes is probably the place to start reading about themes.


text:
Q: Fixing a class file This may be a problem with too narrow an audience for this forum, but I'm rather stuck at the moment.  I'm attempting to build my dissertation document.  My school's style guide is decidedly Word-centric, but I do have a LaTex class that was built by students some years ago that implements it.  Unfortunately they are no longer around to maintain it...
I successfully used this class file a couple of years ago to build my prospectus, but now even my old prospectus files throw an error.  I believe the problem has to do with a change to the acronym package.
The error that I get is

LaTeX Error: \bflabel undefined

\bflabel appears twice in the class file, both times in this block
\AtBeginDocument{%
  \if@AFITdraft\singlespace\else\afit@doublespace\fi
  % adjust the acronym package's list format to conform to the AFIT style guide
  \@ifpackageloaded{acronym}{%
    \newcommand\afit@acronymwidth{Acronym}
    \renewcommand{\bflabel}[1]{{#1\hfill}}%
    \newlength\afit@acronymlabelsep
    \settowidth\afit@acronymlabelsep{\qquad}%
    \renewenvironment{AC@deflist}[1]{%
      \ifAC@nolist\else
        \newwrite\aftfile
        \immediate\openout\aftfile=\jobname.aft%
        \immediate\write\aftfile{\string\renewcommand\string\afit@acronymwidth{#1}}%
        \immediate\closeout\aftfile
        \raggedright\begin{list}{}{%
          \singlespace
          \setlength{\topsep}{\afit@fracskip}%
          \setlength{\itemsep}{\afit@fracskip}%
          \setlength{\parsep}{0pt}%
          \setlength{\partopsep}{0pt}%
          \setlength{\parskip}{0pt}%
          \settowidth{\labelwidth}{#1}%
          \setlength{\labelsep}{\afit@acronymlabelsep}%
          \setlength{\leftmargin}{\labelwidth}%
          \addtolength{\leftmargin}{\labelsep}%
          \renewcommand{\makelabel}{\bflabel}%
        }%
      \fi%
    }{%
      \ifAC@nolist\else
        \end{list}%
      \fi
    }%
    \newcommand\listofacronyms[1]{%
      \IfFileExists{\jobname.aft}{\makeatletter\input{\jobname.aft}\makeatother}{}%
      \newlength\afit@acronymleftmargin
      \settowidth\afit@acronymleftmargin{\afit@acronymwidth}%
      \addtolength\afit@acronymleftmargin{\afit@acronymlabelsep}%
      \addlistof{Acronyms}{\makebox[\afit@acronymleftmargin][l]{Acronym}Definition}{#1}%
    }
  }{}%
}

I found this question on this site that provides an explanation for what's happening:

\bflabel is not being used in the newest implementation of acronym.sty, they introduced \aclabelfont and a few others to deal with formatting. No backward compatibility.

But that doesn't really help me in terms of fixing the problem.  So at this point, I'm not sure how to proceed.  Given what happens with bflabel in the class file, is there an easy "fix"?  I have no experience at all working with class files...any ideas at this point would be greatly appreciated.

A: Please consider producing a minimal working example which really narrows down the problem.
Basically, this error is LaTeX's way of telling you that, though you're asking it to \renewcommand the control sequence \bflabel, there is no control sequence \bflabel for it to renew.  Simple deleting the re will eliminate the error, though I don't know if the result is what you want.
\documentclass{article}
\usepackage{acronym}
\newcommand{\bflabel}[1]{{#1\hfill}}%
\begin{document}
Here I am \bflabel{what} now
\end{document}

So if you copy your cls file to your working directory, and remove that re from \renewcommand, you shouldn't throw this particular error.  (Probably; without the cls file to inspect, there could be some other strange things going on.  But it's worth a shot.)


text:
Q: Using KVC for setting inaccessible properties. Is this allowed? Using KVC for setting inaccessible properties. Is this advised ?
Say I want to change UIDatePicker text color which is not allowed by Apple framework.
Can I edit the properties using KVC?
datePicker.setValue(UIColor.whiteColor(), forKey: "textColor")

Is this a good programming practice? Because we are accessing private properties using KVC

A: By inaccessible, I assume you mean "private API".
There are two problems with this approach:

*

*Apple will reject your app if you submit it to the store; the main reason being that:

*Private APIs are private precisely so that developers don't rely on them: typically the API is still a work in progress inside Apple and therefore the spec might change at any future release of the OS. Apple can use the private APIs because -of course- they get a chance to update all their pre-installed apps every time the OS is updated. But third any party apps relying on them will likely break.
If you are planning to release your app in-house, B2B, Enterprise, jailbreak, etc. you don't have to worry about rejection; however, the likelyhood of your app breaking when (say) your users upgrade from iOS 9 to iOS 10 is still there.
EDIT: After thinking about it, I'm not sure if Apple can detect your KVC access of private properties; after all, you are not calling any private method (getters/setters included). But I don't know how they "scan" the apps they review, so...

A: Is this a good programming practice?
No.
Why?
It violates the basics of oop. An object is offering a set of methods and properties you can rely on. Behind it you can't know if the object will have that property inside. The object could be something completely different that just implements the methods that are available.


text:
Q: Кастомный ListView Доброго времени суток. Имеется код (сократил до рассматриваемых компонентов).
В коде идет парсинг статей с сайта, затем каждая статья помещается в массив arr и в onPostExecute загружается в listview lv: lv.setAdapter(adapter);. Тут проблем нет, все отлично. Хочу добавить время добавления статьи (тоже спарсеное соответственно) и отобразить в каждом списке listview справа ниже мелким шрифтом. Получается уже нужен кастомный listview. Вот тут то и начинаются проблемы. Ввиду моей малоопытности сам я новый адаптер не напишу, поэтому рассматривал примеры. Пробовал подстроить под себя вот этот пример. Все вроде ничего, но только там подгружается из уже готовых массивов, пробовал поставить свой - ругается, что якобы не соответствуют типы (наверно потому что у меня не обычный массив, а коллекция ArrayList<String>). Может кто знает, подскажите пожалуйста как на этом примере в одном элементе listview отобразить сразу два textview из данного массива arr. В данном примере я еще не реализовал парсинг времени статьи, пускай будет два одинаковых textview (с текстом статьи), дальше под себя подшаманю. Заранее очень благодарен кто поможет.
MainActivity.java
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Parser par;
    ListView lv;
    ArrayList<String> arr = new ArrayList<>();
    ArrayAdapter<String> adapter;

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

        lv = (ListView)findViewById(R.id.listView);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        par = new Parser();
        par.execute();

        adapter = new ArrayAdapter<String>(this, R.layout.list_item, arr);
    }

    class Parser extends AsyncTask<Void, Void, Void> {

        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void ... params) {

            Document doc = null;

            try {
                doc = Jsoup.connect("http://www.site.ru").get();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (doc != null) {
                Elements text2 = doc.select("div.entry-content");
                for (Element temp : text2) {
                    arr.add(temp.text().replaceAll("—", "\n —"));
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            lv.setAdapter(adapter);
        }
    }
}

list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textColor="@color/colorText"
    android:textSize="20sp"
    android:divider="@color/colorDivider"
    android:typeface="serif" >
</TextView>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:src="@drawable/logo"
        android:title="@string/app_name">

        <ImageView
            android:id="@+id/logo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/logo"
            android:layout_gravity="left"/>

    </android.support.v7.widget.Toolbar>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/listView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/button_next"
        android:choiceMode="none"
        android:scrollingCache="true"
        android:dividerHeight="1dp"
        android:divider="@color/colorDivider"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:stackFromBottom="false"
        android:smoothScrollbar="false"
        android:layout_below="@+id/toolbar"
        android:padding="16dp" />

</RelativeLayout>

A: Если проблема в том что  бы вместо одного TextView их  было два, то ваш
item.xml должен быть примерно таким:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/title_layout_mainToolbar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

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

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

</RelativeLayout>

Плюс кастомный адаптер:
public class BoxAdapter extends BaseAdapter {
  Context ctx;
  LayoutInflater lInflater;
  ArrayList<Product> objects;

  BoxAdapter(Context context, ArrayList<Product> products) {
    ctx = context;
    objects = products;
    lInflater = (LayoutInflater) ctx
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  }

  // кол-во элементов
  @Override
  public int getCount() {
    return objects.size();
  }

  // элемент по позиции
  @Override
  public Object getItem(int position) {
    return objects.get(position);
  }

  // id по позиции
  @Override
  public long getItemId(int position) {
    return position;
  }

  // пункт списка
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

    // используем созданные, но не используемые view
    View view = convertView;
    if (view == null) {
      view = lInflater.inflate(R.layout.item, parent, false);
    }

    Product p = getProduct(position);

      //заполнение TextView данными
    ((TextView) view.findViewById(R.id.textView_frist)).setText(p.name);
    ((TextView) view.findViewById(R.id.textView_second)).setText(p.price + "");

    return view;
  }

  // товар по позиции
  Product getProduct(int position) {
    return ((Product) getItem(position));
  }

}

Вместо объекта Product у вас может быть свой объект который содержит данные для заполнения айтема.
В итоге получаеться что:

*

*вы создаете сложный(больше одной вьюхи) элемент списка  -> item.xml

*создаете кастомный адаптер, в котором инфлейтите айтемы и для каждого айтема берете из списка объект с данными и заполняете этими данными вьюхи в айтеме.

A: Для меня, как для новичка, самым понятным все же оказался этот пример.
Правда там используются заранее проинициализированные массивы String [], у меня же была коллекция ArrayList<String>, инициализирующаяся в процессе работы приложения через Jsoup. Заменив соответствующие типы и поля setText() все заработало! Спасибо за подсказки.


text:
Q: How can I keep track of record number across multiple json objects in PHP I have an export of Customer Records that needed to be split up over several chunks of 500 records.  I grab each chunk through a REST request, save it to my server:
public function createImportFile($json)
{
    $filePath = storage_path().'/import/'.$this->getImportFileName($this->import->chunkNumber);
    $importFile = fopen($filePath, 'w');
    $array = json_decode($json);

    fwrite($importFile, $json);
    fclose($importFile);
    return $filePath;

}

Then after grabbing all of the chunks, I import all of the records.  I'm wondering what the best way would be to find the Nth record among all the chunks?
Currently, I divide the record number that I'm looking for by the total number of chunks to find out which chunk the record will be in.  Then, I get the total records for the previous chunks and subtract this number from the record number to get the record's position in the chunk.
while ($this->recordNumber <= $this->totalRecords) {
            $item = $this->getRecord($this->recordNumber);
            if (empty($item)) {
                $this->recordNumber++;
                continue;
            }
            $results = $this->translateItem($item);
            $this->recordNumber++;
 }
public function getRecord($recordNumber)
{
    if ($this->import->isChunkedImport()) {
        $chunkNumber = (integer) $this->returnChunkFromRecordNumber($recordNumber);
        $countInPrevChunks = intval($this->returnRecordCountForPrevChunks($chunkNumber));
        $chunkPosition = intval($this->getChunkPosition($recordNumber, $countInPrevChunks));
        $jsonObj = $this->getJsonObjectForChunkNumer($chunkNumber);
        return $jsonObj[$chunkPosition];
    }
    else {
        $chunkPosition = $this->getChunkPosition($recordNumber, 0);
        $filePath = storage_path().'/import/'.$this->getImportFileName();
        return (array) json_decode(file_get_contents($filePath))[$chunkPosition];
    }
}

private function &getJsonObjectForChunkNumer($chunkNumber)
{
    if ($this->currentFileArray == null || ($chunkNumber != $this->lastChunkNumber)) {
        $filePath = storage_path().'/import/'.$this->getImportFileName($chunkNumber);
        $this->currentFileArray = json_decode(file_get_contents($filePath), true);
        $this->lastChunkNumber = $chunkNumber;
    }
    return $this->currentFileArray;
}

public function getChunkCount()
{
    $filePath = storage_path().'/import/'.$this->getImportFileName();
    return count(json_decode(file_get_contents($filePath)));
}

public function returnChunkFromRecordNumber($recordNumber)
{

    if ($recordNumber >= $this->getChunkCount()) {
        if (is_int($recordNumber/$this->getChunkCount())) {
            if (($recordNumber/$this->getChunkCount()) == 1) {
                return intval(1);
            }
            return intval(($recordNumber/$this->getChunkCount())-1);
        }
        else {
            return intval($recordNumber/$this->getChunkCount());
        }
    }
    else {
        return intval(0);
    }
}

public function getChunkPosition($recordNumber, $countInPrevChunks)
{
    $positionInChunk = $recordNumber - $countInPrevChunks;
    if ($positionInChunk == 0) {
        return $positionInChunk;
    }
    return $positionInChunk - 1;
}

public function returnRecordCountForPrevChunks($chunkNumber)
{
    if ($chunkNumber == 0) {
        return 0;
    }
    else {
        return $this->getChunkCount() * $chunkNumber;

I try to account for the first key for both Chunks and Records in the Chunks being 0, but I'm still missing the last record of the import.  It also seems like I might be making this more complicated than it needs to be.  I was wondering if anyone had advice or a more simple way to grab the Nth record.  I thought about possibly just numbering the records as I bring them in with the REST request, then I could find the Chunk containing the record number as an array key and then return that record:
public function createImportFile($json)
{
    $filePath = storage_path().'/import/'.$this->getImportFileName($this->import->chunkNumber);
    $importFile = fopen($filePath, 'w');
    if ($this->import->chunkNumber == 0 && $this->recordNumber == 0) $this->recordNumber = 1;
    $array = json_decode($json);
    $ordered_array = [];
    foreach ($array as $record) {
        $ordered_array[$this->recordNumber] = $record;
        $this->recordNumber++;
    }
    fwrite($importFile, json_encode($ordered_array));
    fclose($importFile);
    return $filePath;
}

But I wasn't sure if that was the best approach.

A: With a lot of records, you could use a database table. MySQL would easily handle tens of thousands of records.  You wouldn't even need to store the whole records. Perhaps just:
record_no | chunk_no | position_in_chunk

*

*record_no: Primary key. Unique identifier for this record

*chunk_no: Which chunk contains the record

*position_in_chunk: Where within the chunk is the record located

Put a UNIQUE(chunk_no, position_in_chunk) index on the table.
Then as you pull records, assign them a number, build up the DB table, and save the table as you write records to disk.  In the future, to get a specific record, all you'll need is its number.
If you don't want to use a database, you can also store this data as a JSON file, though retrieval performance will suffer from having to open and parse a big JSON file each time.


text:
Q: Point around a square with javascript I was kindly given the code below by AtomicRobot on stackoverflow.
var x,y;

// amount of chairs
var totalChairs = 12;
// square size
var squareSize = 200;
var chairSize = 60;

// issues with 3,5,7,8,9,10,11

for(var i=0; i<totalChairs; i++){

    var angle = 2*Math.PI * i/totalChairs;

    if (angle > Math.PI/4 && angle <= Math.PI* 3/4){
        x = (squareSize/2) / Math.tan(angle);
        y = -squareSize/2 - chairSize/2;
    } else if (angle > Math.PI* 3/4 && angle <= Math.PI* 5/4){
        x = -squareSize/2 - chairSize/2;
        y = (squareSize/2) * Math.tan(angle);
    } else if (angle > Math.PI* 5/4 && angle <= Math.PI* 7/4){
        x = -(squareSize/2) / Math.tan(angle);
        y = -squareSize/2 + squareSize + chairSize/2;
    } else {
        x = -squareSize/2 + squareSize + chairSize/2;
        y = -(squareSize/2) * Math.tan(angle);
    }

    x -= Math.round(chairSize/2) - squareSize/2;
    y -= Math.round(chairSize/2) - squareSize/2;

    $("#square").append("

");
}

which is to plot chairs around a table with javascript it works great for the following amount of chairs 1,2,4,6,12 the distances are plotted equally.
But with the following amount of chairs 3,5,7,8,9,10,11 the seems to be of by the chair width.
Is their anyone that can let me know why this might be occurring maths isn't my strong point and would really appreciate some help with this, you can see a example here with 8 chairs.
http://jsfiddle.net/Ld769/4/
Thanks
Ive been making progress with this completely change how i am doing it now actually understand whats going on with this one and can expand the table to suit still having issue with the remander to for certain people numbers????
       var x,y;

// amount of chairs
var totalChairs = 18;
var chairSize = 60;
// square size
var squareSize = Math.round(totalChairs/4) * chairSize;

//alert("squareSize: " + squareSize);
// issues with 5,9,13,17,21
// works with 1,2,4,6,12
var remainder = Math.round(totalChairs/4);

var s1 = 0;
var s2 = 0;
var s3 = 0;
var s4 = 0;

for(var i=0; i<totalChairs; i++){

    var iter = i;
    if(iter+1 <= remainder){

         var s1i = s1++;
         console.log("s1i: " + s1i);

         x = s1i * chairSize;
         y = -chairSize;
         newr = remainder*2;

    } else if(iter+1 <= newr){
         var s2i = s2++;
         console.log("s2i: " + s2i);
         y = s2i * chairSize;
         x= squareSize;
         newe = remainder*3;

    } else if(iter+1 <= newe){

         var s3i = s3++;
         console.log("s3i: " + s3i);
         x =  - s3i * chairSize  + squareSize - chairSize;
         y = squareSize;

    }else{
         var s4i = s4++;
         console.log("s4i: " + s4i);
         y = - s4i * chairSize + squareSize - chairSize;
         x= -chairSize;

     }

    $("#square").css({"width":(squareSize) + "px","height":(squareSize) + "px"});
    $("#square").append("

"+i+"
x"+x+",y"+y+"

");
    $(".chair").css({"width":(chairSize) + "px","height":(chairSize) + "px"});
}

can see the jsfiddle version here
http://jsfiddle.net/isimpledesign/Ld769/19/

A: i'd figure how many need to fit on one of the 4 sides. 4*2 = 8, not sufficient, 4*3 = 12 OK!, that means 3 sides get three and one gets 2. that means the minimum width and height must be the same as the most packed side (so that the seated fit comfortably)
if you want to have them evenly separated? Just figure out the number of chairs, say it's 11, divide into 360 to figure your angle of separation then project that onto the square


text:
Q: Can I restore just one schema from a pg_dump of the entire database? I have backups of my postgres database - the entire database instance in a single nightly backup. Is it possible to restore just one of the database from within that backup? Or if I want to access individual databases (for migration or restoring), do I need to change my database backup scheme to do individual dumps?

A: Yes, if your backup is "an archive created by pg_dump in one of the non-plain-text formats." - use the "--schema=" option to pg_restore.
On the other hand I'm not sure you're using the correct terminology here - you refer to a DB cluster as "entire database instance"; in the explanation you ask about "database" but in the title you wrote "schema", etc.
Edit: Now, after some deliberation, I believe you have a cluster backup, created with "pg_dumpall". "pg_dumpall" creates only plain-text (SQL-commands) backups. In that case it's not possible to restore only one database (or only one schema from a database).
Then yes, you need to change your backup procedure to backup individual databases using non-plain-text format (--format=custom is the recommended one).
Actually the backup procedure I use on my DB servers does just that.

A: You can access individual databases from a full database cluster dump in text format (pg_dumpall) by using some text processing like this:
awk '/^\\connect database_name/ {flag=1;print;next}
     /^\\connect/ {flag=0}
     flag { print }' \
   < all_databases.sql \
   > database_name.sql

This would get from pg_dumpall file everything between "\connect database_name" and next "\connect". But it is not very efficient.
But I'd recommend dumping every database separately like this:
# Dumping global data (for example roles)
pg_dumpall -g > /var/lib/pgsql/backups/globals.sql

#Dumping indidual databases in tar (uncompressed binary) format
for dbname in
  `
    psql -qXtc "
      select datname from pg_catalog.pg_database
      where datname<>'template0'" template1
  `
do
  pg_dump -b -F t "$dbname" > "/var/lib/pgsql/backups/$dbname.dump"
done

I'm assuming you mean "Can I restore just one database from a pg_dumpall of the entire database cluster?"


text:
Q: PHP: Destroying Object after reloading the page <?php $mView = new systemModuleView();?>
<?php $mView->nextPage(); ?>
<?= $mView->showTable()["table"]; ?>

I have this View Class to get some content out of my table. That works so far. But I want to call the method: nextPage after clicking a specific button. The page must not reload because this will destroy the Object...
I have tried several things:
Session
Ajax
But that doesn't work.

A: I suggest json encoding your object and then putting it in a session.
Then if you want to get your object again just read the sesion and json_decode it.


text:
Q: Show that $A\subseteq \overline {A}$ Definition. A subset of $\mathbb{R}$ is closed if it's complement is open.
Proposition. For any subset $A$ of $\mathbb{R}$ there is a unique subset $\overline {A}$ containing $A$ with the property that if $B$ is closed set containing $A$ then $\overline {A}\subseteq B$.
$\overline {A}=\bigcap${ $B\subseteq \mathbb{R}$ $B$ is closed and contains $A$}
Question. How can I show $A\subseteq \overline {A}$ to use the proposition? Can you give a hint?
My proof trying is: Let $A\subseteq \mathbb{R}$. Let $\overline {A}$ be closure of $A$. We will show that $A\subseteq \overline {A}$.

A: This property holds trivially by definition. Indeed, $\overline{A}$ is the smallest closed set containing $A$.

A: I claim that $$\overline{A}= \bigcap_{i \in I} B_i,$$
 where $I$ is just an index set and $B_i$ ranges over all closed sets that contain  $A$. Here, $\overline{A}$ is clearly closed (by DeMorgan's laws, or definition) and if $B$ is closed and contains $A$, then it is among the $B_i$ , so $\overline{A} \subseteq B_i$.
To show uniqueness, just note that if another set $B$ has this property, $\overline{A} \subseteq B$ by construction and $B \subseteq \overline{A}$ by hypothesis.

A: If $x\in A$ then $x\in B$ for every closed subset $B$ containing $A$. Therefore $x\in\overline A$ by (your) definition.


text:
Q: Unexpected type mismatch when using Scala generics I have a simple scenario that is yielding a type mismatch when using Scala generics, and it's not clear why or how to resolve it.
trait Foo
case class Bar() extends Foo

trait FooGetter[T <: Foo] {
  def get: T = Bar() // Error
}

The error:

type mismatch; found   :
  Bar  required: T

Any hints?

A: Here T <: Foo means Foo is the upper bound of type T.

As you can see, there is no relationship between Bar and T, so the casting cannot happen in an implicit way.
Of course, if you can guarantee the casting safety, you can cast it using asInstanceOf in an explicit way.
On the other hand, the following is fine when T is the super while Foo is the child.
trait FooGetter[T >: Foo] {
  def get: T = Bar()
}

A: You can simplify the code like this:
trait Foo
case class Bar() extends Foo

trait FooGetter {
  def get: Foo = Bar()
}

FooGetter is tightly linked to Foo anyway, there is no point in making FooGetter generic. (Note, Bar is a Foo for the scala type checker.)

A: What always works is asInstanceOf, in your Example:
trait Foo
case class Bar() extends Foo

trait FooGetter[T <: Foo] {
  def get: T = Bar().asInstanceOf[T]
}

So this works:
println(new FooGetter[Bar]{}.get) // Bar()

But as Seth Tisue points out:

there's no point in using generics at all if the resulting code isn't
  actually generic.


text:
Q: Not redirect to Authorize Action Result after successful login in Identity MVC I am trying create a login page that should redirect to an action result on successful login. I have user roles that should check. For now I can validate user but it does not redirect to Authorize Action result. Besides it provide return url to login page. Here is my Code for Account Controller
public ActionResult Login()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Login(string UserName, string Password)
    {
        if (new UserManager().IsValid(UserName, Password))
        {
            string userName = "Test Name"; //Hard coded for test purpose
            string[] userRoles = {"Admin"};//Hard coded for test purpose

            ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userName));

            userRoles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role)));

            identity.AddClaim(new Claim(ClaimTypes.Name, userName));

            AuthenticationManager.SignIn(identity);
            return RedirectToAction("Index","Home"); // auth succeed
            // auth succeed
        }
        // invalid username or password
        ModelState.AddModelError("", "invalid username or password");
        return View();

    }

    private IAuthenticationManager AuthenticationManager
    {
        get { return HttpContext.GetOwinContext().Authentication; }
    }

And Home controller
[Authorize]
    public ActionResult Index()
    {
        return View(); //Which contain Dashboard for admin panel
    }

But problem is when it appear to return RedirectToAction("Index","Home");it not redirect but URL change to ../Account/Login?ReturnUrl=%2fHome.
This is very new to me (Past I restrict user from database), Is there anything wrong with this code? Thanks in advance....


text:
Q: How I can forward port throught OpenVPN correctly? I'm trying to forward a port through OpenVPN (with Ethernet Bridging) but I can't.
Below is a "simple" network diagram. A server contains 2 virtual machines, the principal server is connected with OpenVPN to another server. I need forward a port from 10.10.10.2 (a Virtual Machine) to public IP of the external server with IP 10.10.10.11 (see diagram).
The bridge vmbr0 is including a three interfaces: tap0, eth0 (public IP) and vlan1 (10.10.10.0/24).

The rule I used in 10.10.10.11 server is

iptables -t nat -D PREROUTING -p tcp -d [public ip here] --dport 80 -j DNAT --to-destination 10.10.10.2:80

In the image below you can see that packets "enter" but not "exit" through the interface tap0.
This is a dump of tap0 interface:

The packets are entering correctly from tap0, but packets are routed to vmbr0 and never get to tap0.
How can I resolve this problem?

A: Bridges essentially turn a number of NICs into a virtual switch.
If you want devices to talk across a bridge, they need to be on the same subnet, as they would on a real switch.  If they are not on the same subnet, you need a router, not a switch or bridge.
So bridging your public IP eth0 and tap0 or vlan1 NICs won't work unless you have 2 public IPs from your ISP - allowing you to put both of them on the same subnet.
You can put both your virtual machines on a bridge - and they can talk since they'll be on the same subnet.
Your system then needs to route and do NAT, using eth0 as the "WAN" NIC and vmbr0 as the "LAN" NIC.  Any guide you find on doing iptables with NAT can be used, just substitute vmbr0 for eth1 or the LAN-facing NIC.


text:
Q: Convert pandas dtypes to BigQuery type representation I've just installed pandas and numpy, and don't have any experience with them. I'm trying to get a json data structure similar to what you need to pass to Google BigQuery. https://developers.google.com/bigquery/docs/reference/v2/jobs#configuration.load.encoding
Goal

*

*Determine data_types

*Return JSON where key is the column name and value is one of the data types: STRING, INTEGER, FLOAT, BOOLEAN, TIMESTAMP or RECORD
What I've tried
 import numpy as np
 import pandas as pd
 import config
 import boto
 from StringIO import StringIO

 k = boto.connect_s3(**config.AWS_PARAMS).get_bucket('xxxxxxx').get_key('DATA.csv')
 o = StringIO(k.get_contents_as_string())
 df = pd.read_csv(o)

 def map_dtype(dtype):
     if dtype.kind == 'i':
         # [int8, int16, int32, int64]
         return "INTEGER"
     elif dtype.kind == 'u':
         # [uint8, uint16, uint32, uint64]
         return "INTEGER"
     else:
         return "STRING"

 fields = []
 for c, d  in zip(df.columns, df.dtypes):
         field = {}
         field['type'] = map_dtype(d)
         field['name'] = c
         fields.append(field)

 print fields

Result
[{'type': 'INTEGER', 'name': 'VALUE'}, {'type': 'INTEGER', 'name': 'ID'}, {'type': 'STRING', 'name': 'Key'}, {'type': 'STRING', 'name': 'EmailAddress'}]

As you can see I'm getting the right result. but I don't like how I'm doing it. I feel there is an easier way to do this.
What I want to improve

*

*map_dtype() function, as you can see I have to manually map data types with there string representation in BigQuery

*For each loop, feels like there should be an easier way to get a data_type assigned to a column.

A: Good news! Since version 0.13 pandas officially (and experimentally) supports Google BigQuery.
Check read_gbq, and particularly to_gbq (to put data into BigQuery): http://pandas.pydata.org/pandas-docs/stable/api.html#google-bigquery.
Video and links to sample notebooks here:

*

*http://www.reddit.com/r/bigquery/comments/1xucma/video_bigquery_python_pandas_and_r_for_data/
(thanks Pearson!)

A: I'm not sure that the methods in pandas.io.gbq will help you much here. If I understand correctly, you have a CSV file and you are attempting to map the dtypes to the BigQuery types. As far as I found when working on pandas.io.gbq, there's not a really convenient way to do this.
For a helpful list of numpy types see:
http://docs.scipy.org/doc/numpy/reference/arrays.interface.html#arrays-interface

The basic type character codes are:

*

*t   Bit field (following integer gives the number of bits in the bit field).

*b   Boolean (integer type where all values are only True or False)

*i   Integer

*u   Unsigned integer

*f   Floating point

*c   Complex floating point

*O   Object (i.e. the memory contains a pointer to PyObject)

*S   String (fixed-length sequence of char)

*U   Unicode (fixed-length sequence of Py_UNICODE)

*V   Other (void * – each item is a fixed-size chunk of memory)

In this case, I feel like a dictionary is your best bet for the lookups, and you can replace the for loop with list comprehension:
df = DataFrame({'a' : [1,2], 'b' : [True, False], 'c' : [1.1, 2.1], 'd' : ['a', 'b']})
type_dict = {
    'b' : 'BOOLEAN',
    'i' : 'INTEGER',
    'f' : 'FLOAT',
    'O' : 'STRING',
    'S' : 'STRING',
    'U' : 'STRING'
}
[{'name' : col_name, 'type' : type_dict.get(col_type.kind, 'STRING')} for (col_name, col_type) in df.dtypes.iteritems()]

Yields:
[{'type': 'INTEGER', 'name': 'a'}, {'type': 'BOOLEAN', 'name': 'b'}, {'type': 'FLOAT', 'name': 'c'}, {'type': 'STRING', 'name': 'd'}]

In this case, I explicitly reference 'O','S', and 'U' in the dict - you can handle this any number of ways. Obviously one needs to be careful with the 'O' case, as the it may not have a useful string representation. Likewise, since I use the .get() method, I assume that the string representation of the unsupported types is better than nothing. This may not be the case for you (or you might wish to avoid possible type casting down the road), so it might be better to directly look up the value as type_dict[col_type] and handle the exceptions on a case by case basis.


text:
Q: Docker container port issue I've installed docker on raspbian jessie 8 (IP 192.168.2.2) . I created a docker container with raspbian base image with minecraft installed on in. I opened the port 25565 on the container
pi@raspberrypi ~ $ docker run -d -p 25565:25565 rpi_minecraft

pi@raspberrypi ~ $ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                              NAMES
b94381cdc3b6        rpi_minecraft       "supervisord -c /etc/"   About an hour ago   Up About an hour    80/tcp, 0.0.0.0:25565->25565/tcp   pensive_shockley

When I attempt to see if that port is opened I get this error
Andrews-iMac:~ Andrew$ telnet 192.168.2.2 25565
Trying 192.168.2.2...
telnet: connect to address 192.168.2.2: Connection refused
telnet: Unable to connect to remote host

What is causing this issue? All the relevant ports look open to me?

A: Because you opend port 25565 but tested for port 80 with telnet.
telnet 192.168.2.2 25565


text:
Q: Pass variable from plugin back to cordova The Cordova plugin I'm using plays a VR video file, and is called via GoogleVRPlayer.playVideo(videoUrl, fallbackVideoUrl).
Somewhere in the .java files of the plugin, there's:
@Override
public void onLoadError(String errorMessage) {
  // I want to know if this function is executed
  Log.e(TAG, "Error loading video: " + errorMessage);
}

Basically, when the video fails to load, I want to set a variable in my javascript in cordova to "error", for example var video_status = "error", so I can use this information later on in my app.
I've found some answers that would possibly solve my problem, but I can't seem to integrate it the right way. I have very little experience with native plugins and Java.
Anyone who can help me with this?

A: Since the Cordova plugin GoogleVRPlayer launches a new Activity (VrVideoActivity), I would use a Singleton class as an interstitial data bridge between the two Activites to hold the error message.
This is because, on launching the video player activity, your app (the Cordova activity) is paused in the background and will only resume execution once the video player activity is closed.
By using the intermediate class, both the Cordova plugin and the video activity are able to share data.
So I would do something like this:
Create a new file called CordovaBridge.java in cordova-vr-player/src/android/java/neotrino/
package com.neotrino;

public class CordovaBridge {
  private String errorMsg = null;
  public String getErrorMsg() {return errorMsg;}
  public void setErrorMsg(String errorMsg) {this.errorMsg = errorMsg;}

  private static final CordovaBridge holder = new CordovaBridge();
  public static CordovaBridge getInstance() {return holder;}
}

Modify GoogleVRPlayer.java as follows:
import com.neotrino.CordovaBridge;

@Override
public void onResume(boolean multitasking) {
    cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            String errorMsg = CordovaBridge.getInstance().getErrorMsg();
            if(errorMsg != null){
              webView.loadUrl("javascript:window.video_status = '"+errorMsg+"'");
            }
        }
  });
}

Modify VrVideoActivity.java as follows:
import com.neotrino.CordovaBridge;

@Override
public void onLoadError(String errorMessage) {
  // I want to know if this function is executed
  Log.e(TAG, "Error loading video: " + errorMessage);
  CordovaBridge.getInstance().setErrorMsg(errorMessage);
}

I haven't tested the above code, but in terms of an approach it should give you an approximation on which to base your solution.


text:
Q: Binomial Coefficients for $(x+1)^4$ Find $(x + 1)^4$ using binomial coefficients.
I'm confused as to how to start this, as I thought binomial coefficients were things like $9 \choose 2$.

A: Do you know the binomial theorem?
$$(a+b)^n = \binom n0 a^nb^0 + \binom n1 a^{n-1}b^1 + \binom n2 a^{n-2}b^2 +\cdots + \binom nn a^0b^n $$

A: HINT: $$\binom nr=\frac{n!}{(n-r)! r!}=\frac{n(n-1)\cdots(n-r+1)}{r!}$$
So, $\binom 92=\frac{9(9-1)}{2!}=\frac{9\cdot8}{2\cdot1}=36$
$$(x+1)^4=\sum_{0\le r\le 4}\binom  4r(1)^{4-r}x^r$$

A: Use this: $(x+y)^n=$ $n \choose 0 $ $x^n y^0$+$n \choose 1 $ $x^{n-1}y^1$+$n \choose 2 $ $x^{n-2}y^2$+ $\dots$ +$n \choose n $ $x^0y^n$
What's the $r^{th}$ term's coefficients using this?

A: Use  $$(x+y)^n=\sum_{r=0}^n T_r$$
$$T_r= \ ^nC_r\times  x^{r}y^{n-r}$$
so for $(1+x)^n $you come with $$T_r= \ ^nC_r x^r$$
$$^nC_r=\dfrac{n!}{(n-r)!r!}$$


text:
Q: Out Of Memory Exception when adding 3lakh rows in ASP DataGrid In my web application i want to show a table data in Data Grid for that i am using Entity Framework 4.0 while executing i am getting exception that out of memory.
Is there any limitation in ASP.NET Data Grid.
I am using Oracle DataBase.
Below is my code
        Entities obj = new Entities();
        GridView1.DataSource = obj.EQUIPMENTs.ToList();
        //Here i am getting exception
        GridView1.DataBind();

A: You have to check your memory consumption. Use a ProcessExplorer for easy check. If you are in limits, chech the amount of data you load into the collection.
Remember that CLR apart of the allocated RAM limitation has a limitation on LIst<T> size, I see obj.EQUIPMENTs.ToList(). For List<T>, limitation is 2GB (even on x64).
If one of these is true (or both), the solution is rearchitect your code.
Example:
It's hardly possible that your user need all that amount of data at once, may be you can slice it between different pages/tabs/whatever...
If you need some statistical information, some aggregation, or some calculation, do it on server and transfer only the results.


text:
Q: Изменение стилей при сравнении ворд документов c# Возникла необходимость реализовать версионность вордовских документов. С помощью Interop.Word удалось сравнить два вордовских документа и вернуть на выход третий - с изменениями/удалениями.
var doc = wordApp.CompareDocuments(file1, file2, MsWord.WdCompareDestination.wdCompareDestinationNew,
                    MsWord.WdGranularity.wdGranularityWordLevel, true, true, true, true, true, true, true, true, true, true, "", false);

Но возникла проблема, удаленные участки текста помечаются красным зачеркнутым стилем, а вставленный - просто красным. Найти решения по изменению стилей, чтобы удаленный текст помечался просто красным, а вставленный зеленым - не удалось. Поэтому прошу совета, как и в какую сторону копать)


text:
Q: How to 'bulk update' with Django? I'd like to update a table with Django - something like this in raw SQL:
update tbl_name set name = 'foo' where name = 'bar'

My first result is something like this - but that's nasty, isn't it?
list = ModelClass.objects.filter(name = 'bar')
for obj in list:
    obj.name = 'foo'
    obj.save()

Is there a more elegant way?

A: To update with same value we can simply use this
ModelClass.objects.filter(name = 'bar').update(name='foo')

To update with different values
ob_list = ModelClass.objects.filter(name = 'bar')
obj_to_be_update = []
for obj in obj_list:
    obj.name = "Dear "+obj.name
    obj_to_be_update.append(obj)
ModelClass.objects.bulk_update(obj_to_be_update, ['name'], batch_size=1000)

It won't trigger save signal every time instead we keep all the objects to be updated on the list and trigger update signal at once.

A: Update:
Django 2.2 version now has a bulk_update.
Old answer:
Refer to the following django documentation section

Updating multiple objects at once

In short you should be able to use:
ModelClass.objects.filter(name='bar').update(name="foo")

You can also use F objects to do things like incrementing rows:
from django.db.models import F
Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)

See the documentation.
However, note that:

*

*This won't use ModelClass.save method (so if you have some logic inside it won't be triggered).

*No django signals will be emitted.

*You can't perform an .update() on a sliced QuerySet, it must be on an original QuerySet so you'll need to lean on the .filter() and .exclude() methods.

A: Consider using django-bulk-update found here on GitHub.
Install: pip install django-bulk-update
Implement: (code taken directly from projects ReadMe file)
from bulk_update.helper import bulk_update

random_names = ['Walter', 'The Dude', 'Donny', 'Jesus']
people = Person.objects.all()

for person in people:
    r = random.randrange(4)
    person.name = random_names[r]

bulk_update(people)  # updates all columns using the default db

Update: As Marc points out in the comments this is not suitable for updating thousands of rows at once. Though it is suitable for smaller batches 10's to 100's. The size of the batch that is right for you depends on your CPU and query complexity. This tool is more like a wheel barrow than a dump truck.

A: Django 2.2 version now has a bulk_update method (release notes).
https://docs.djangoproject.com/en/stable/ref/models/querysets/#bulk-update
Example:
# get a pk: record dictionary of existing records
updates = YourModel.objects.filter(...).in_bulk()
....
# do something with the updates dict
....
if hasattr(YourModel.objects, 'bulk_update') and updates:
    # Use the new method
    YourModel.objects.bulk_update(updates.values(), [list the fields to update], batch_size=100)
else:
    # The old & slow way
    with transaction.atomic():
        for obj in updates.values():
            obj.save(update_fields=[list the fields to update])

A: If you want to set the same value on a collection of rows, you can use the update() method combined with any query term to update all rows in one query:
some_list = ModelClass.objects.filter(some condition).values('id')
ModelClass.objects.filter(pk__in=some_list).update(foo=bar)

If you want to update a collection of rows with different values depending on some condition, you can in best case batch the updates according to values. Let's say you have 1000 rows where you want to set a column to one of X values, then you could prepare the batches beforehand and then only run X update-queries (each essentially having the form of the first example above) + the initial SELECT-query.
If every row requires a unique value there is no way to avoid one query per update. Perhaps look into other architectures like CQRS/Event sourcing if you need performance in this latter case.

A: Here is a useful content which i found in internet regarding the above question
https://www.sankalpjonna.com/learn-django/running-a-bulk-update-with-django
The inefficient way
model_qs= ModelClass.objects.filter(name = 'bar')
for obj in model_qs:
    obj.name = 'foo'
    obj.save()

The efficient way
ModelClass.objects.filter(name = 'bar').update(name="foo") # for single value 'foo' or add loop

Using bulk_update
update_list = []
model_qs= ModelClass.objects.filter(name = 'bar')
for model_obj in model_qs:
    model_obj.name = "foo" # Or what ever the value is for simplicty im providing foo only
    update_list.append(model_obj)

ModelClass.objects.bulk_update(update_list,['name'])

Using an atomic transaction
from django.db import transaction

with transaction.atomic():
    model_qs = ModelClass.objects.filter(name = 'bar')
    for obj in model_qs:
       ModelClass.objects.filter(name = 'bar').update(name="foo")

Any Up Votes ? Thanks in advance : Thank you for keep an attention ;)

A:
IT returns number of objects are updated in table.

update_counts = ModelClass.objects.filter(name='bar').update(name="foo")

You can refer this link to get more information on bulk update and create.
Bulk update and Create


text:
Q: Remove file path from mac terminal prompt I am trying to get rid of the the file path that shows up in the command prompt in mac terminal.
Example: superuser@x-160-94-176-201:[~/dir1/dir2/dir3/dir4/]$
If you have longer directory names you will end up loosing the entire line. I know in cshrc I can do this, infact I have edited .cshrc in my ubuntu box to make this change.
  if ( $?tcsh ) then
    #set prompt="%n@%m (%/) % "
    set prompt="[%n@%m %c]% "
    #set prompt="%n@%B%m%b (%B%~%b) % "
    set prompt2 = "%R loop: "
    set prompt3 = "oops\041 %R (y|n|e)? "

I run bash on my mac and but I tried putting set prompt in my bash_profile but it didn't have any impact.

A: On bash (and other *sh-style shells) you set the prompt by setting the environment variable PS1.
For example, setting it to
% PS1=`hostname`':\W> '

Gives you a prompt:
host:pwd>

where host is your host name (as returned by the command hostname), and pwd is the last component of your path.
Look at man bash and search for PROMPTING for all the details, including how to do bold characters, include the time, and so on.
zsh (which is a nice shell) has more extensive support for fancy prompts.


text:
Q: proof of inner direct sum of projection operators I would like to understand part of a proof that is unclear to me.
Theorem:
Let $V$ be a $K$-vectorspace and $q_1, \dots, q_r$
a set of projection operators on $V$ such that $\sum_{i=1}^r{q_i} = 1_V$ and for all $i \neq j$, $q_iq_j = 0$.
Let $V_i =$ im $q_i$. Then $V = V_1 \oplus \dots \oplus V_r$.
Proof:
Since $1_V = \sum_{i=1}^r{q_i}$, then $v = \sum_{i=1}^r{q_i(v)}$. Therefore $V = \sum_{i=1}^r{V_i}$.
All that is left to prove is that this decomposition is unique.
Since $v = v_1 + \dots + v_r$, $v_i \in V_i$, then we must show that $v_i = q_i(v)$. Because $V_i =$ im $q_i$, then $v_i = q_i(w_i)$ with $w_i \in V$.
This implies $q_j(v) = q_j(\sum_{i=1}^r{q_i(w_i)}) = q_j^2(w_j) = q_j(w_j) = v_j$. Q.E.D.
Question:
How does showing that $v_i = q_i(v)$, imply that the decomposition is unique?

A: You made a transcription error, I think, the fourth senctence of the proof should not start with "Since" but with "Assume that". We know at that point that $v = \sum_{i=1}^r{q_i(v)}$ is one way to write $v$ as sum of elements of each of the $V_i$, and we assume that $v = v_1 + \dots + v_r$ is also a way to write $v$ as sum of elements of each of the $V_i$; showing uniqueness amounts to showing that these two ways must be one and the same. But that means precisely showing that $q_i(v)=v_i$ for $i=1,\ldots,r$, which is what is done in the last line of the proof.


text:
Q: NoMethodError in Users::RegistrationsController#new in Rails I messed something up, and I dont know where. When I run my rails server, it gives me : NoMethodError in Users::RegistrationsController#new , and : undefined method `configure_permitted_parameters' for #
The error message says the code error is :
        case filter
    when Symbol
      lambda { |target, _, &blk| target.send filter, &blk }
    when String
      l = eval "lambda { |value| #{filter} }"
      lambda { |target, value| target.instance_exec(value, &l) }

starting on line 430, error on 432 (line 3 in this). I cant find the file this is in.

A: I'm assuming you're on rails 4 ?
Try adding
before_action :configure_permitted_parameters, if: :devise_controller?

protected

def configure_permitted_parameters
  # Replace the keys to fit your needs
  devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
end

To your application_controller.rb
Please also read the following:
This will help you https://github.com/plataformatec/devise#strong-parameters


text:
Q: virtual function in derived class not getting called when testing with GoogleTest I am having trouble with GoogleTest calling a virtual function that I have defined in my derived class.
I have created a class MyServer using Qt that is derived from QTcpServer. When I run this code outside of GoogleTest the program behaves as expected. When I create a project with GoogleTest incomingConnection in my class never gets called. The socket is accepted as if QTcpServer::incomingConnection receives the call.
MyThread will emit a signal ReadySocket() which is normally connected to whomever created MyServer. When testing I created a MyServerTester Class that would receive the signal and set a flag that I could assert on.
I can simplify the problem down to the following code set a breakpoint in incomingConnection, start the server, connect to it with a client. The connection will be accepted, MyServer::incomingConnection will not be entered, therfore MyThread will never be created.
Project:Server File:MyServer.h
class MyServer : public QTcpServer
{
    Q_OBJECT

public:
    MyServer(QObject *parent = 0);

protected:
    void incomingConnection(qintptr socketDescriptor) Q_DECL_OVERRIDE;
}

Project:Server File:MyServer.cpp
#include "MyServer.h"

MyServer::MyServer(QObject *parent) : QTcpServer(parent) { }

void MyServer::incomingConnection(qintptr socketDescriptor)
{
    MyThread *thread = new MyThread(socketDescriptor, this);
    connect( thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
}

Project:Server_Test File:main.cpp
#include <QtCore/QCoreApplication>
#include "gtest\gtest.h"
#include "..\Server\MyServer.h"

TEST(MyServer, Successful_Connection)
{
    MyServer server;
    server.listen(QHostAddress::AnyIPv4, 4444);
    QThread::sleep(30);
}

int main(int argc, char*argv[])
{
    QCoreApplication a(argc, argv);
    ::testing::InitGoogleTest(&argc, argv);
    RUN_ALL_TESTS();

    return a.exec()
}

A: The first observation is that these are not Unit Tests, are more integration tests, since they use the network and the Qt event loop.
The problem is that you are testing Qt signals that need the Qt event loop (the a.exec() call) to be running. But in your main, you are actually running the tests before starting the event loop. I am not sure it is worthwhile to try to shoehorn the Qt event loop within gtest.
I suggest another approach: use Qt Test, which is perfectly adapted to the Qt event loop, and has, for example, a very handy signal spy to verify signal propagation.

A: the problem is that your server object is destroyed once TEST ends.
may be try
QTcpServer *server;
TEST(MyServer, Successful_Connection)
{
 server = new MyServer;
 server->listen(QHostAddress::AnyIPv4, 4444);
 QThread::sleep(30);
}

and delete server after the TEST is finished.


text:
Q: ActiveRecords: Search only on non empty parameters So I have to search on three fields. Age AND Sex AND Ethnicity
if only Age is given I have to return all records matching the age. If Age and Ethnicity are given but sex is empty then only return matching records for age and ethnicity. etc..
The naive way of solving this is like this:
class Profile

  def self.search_profile(search_params_array)
    if search_params_array.first != nil && search_params_array.second != null && search_params_array.third != null
      Profile.where("age = ?", search_params_array.first).where("sex = ?", search_params_array.second).where("ethnicity = ?", search_params_array.third)
    end
    ...
    ... # We can permutate between all possible conditions where one of the element is nil
    ...
  end
end

What is a better way to approach this?

A: class Profile

  def self.search_profile(search_params_array)
    params = %w(age sex ethnicity).zip(search_params_array).reject do |_, v|
      v.nil?
    end.to_h
    where(params)
  end

end

If you can pass the search params as a hash, things can get much easier.

A: You can create a if else block or a switch case statement based on your logic.

A: You can chain the conditions depending on the presence of the params.
class Profile
  def self.searchprofile(search_params_array)
    scope = Profile.all
    %w(age sex ethnicity).zip(search_params_array).each do |k, v|
      next if v.blank?
      scope = scope.where(k => v)
    end
  end
end

PS: I borrowed the zip trick from Aetherus' answer!


text:
Q: How can I select information where the condition is in multiple rows? How can I select some information from the User table (for example NAME and SURNAME) where, in the Option table, the user I want to select the information having the option 20 and also the option 25, for example ?
In this example, I want to select the NAME and SURNAME of user 1 because it's the only one to have both the option 20 and 25.
Option table:
+---------+---------+
| ID_USER | OPTIONS |
+---------+---------+
| 1       | 20      |
+---------+---------+
| 1       | 25      |
+---------+---------+
| 2       | 20      |
+---------+---------+
| 3       | 25      |
+---------+---------+

User table:
+---------+---------+----------+
| ID_USER | NAME    | SURNAME  |
+---------+---------+----------+
| 1       | Jean    | Baptiste |
+---------+---------+----------+
| 2       | Henry   | Charles  |
+---------+---------+----------+
| 3       | Jacques | François |
+---------+---------+----------+

The result table:
+------+----------+
| NAME | SURNAME  |
+------+----------+
| Jean | Baptiste |
+------+----------+

A: Not sure I understood your question, but I think that the following select would do:
SELECT NAME , SURENAME
  FROM User
 WHERE ID_User IN (SELECT ID_User
                     FROM Option
                    WHERE OPTIONS IN (20,25)
                  )

A: Try this:
SELECT u.name,u.surname

FROM user u, option o

WHERE u.id_user=o.id_user

AND o.options IN (20,25)

A: Do a JOIN to get the combinations, use WHERE to filter out the expected options. GROUP BY combined with HAVING COUNT DISTINCT to make sure both 20 and 25 values are there.
select u.NAME, u.SURNAME
from User u
join Option o on o.ID_USER = u.ID_USER
where o.options IN (20, 25)
group by u.NAME, u.SURNAME
having count(distinct o.options) = 2

Note: USER is a reserved word in ANSI SQL, so you may need to delimit it as "User".


text:
Q: Can't make Samba Share writeable This is my folder configuration from smb.conf
I can access this folder from my windows machine, but i don't have write privileges. I do need guests to be able to write to this folder. Forget security for a second... Why isn't this enough?
[Guest Share]
comment = Guest access share
path = /var/www/myFolder
browseable = yes
writable = yes
read only = no
guest ok = yes

A: Samba is ultimately limited by the underlying filesystem permissions.  What do the permissions on /var/www/myFolder look like?  Do they allow anyone write access?


text:
Q: Mixing SPF records I have the usual Google Apps SPF record in my DNS:
v=spf1 include:_spf.google.com ~all

and now, since we are using ZenDesk, I should also add:
v=spf1 include:support.zendesk.com ~all

Should they be merged into one like this:
v=spf1 include:_spf.google.com include:support.zendesk.com ~all

A: Yes, that is correct, unless _spf.google.com includes a redirect (which it doesn't). In that case, include:_spf.google.com should be moved to end of the list to avoid replacing all entries after the include with the redirect
Also, be aware that the RFC (IETF RFC4408) specifies that a maximum of 10 MX or PTR lookups should be allowed, after which, validation of a single record should be terminated. This is to ensure that an SPF parser doesn't get trapped in an endless lookup scenario (potential DoS'ing).
How does this apply in real life?
Let's say that both includes uses the "mx" mechanism, and that each has 6 distinct MX records. Now, when the first include (_spf.google.com) has been processed, you only have 4 lookups left, so to speak. If the MTA that is being validated is on of the last 2 distinct MX records for the second include (support.zendesk.com), the validation might actually fail even though you've include all the records correctly.
This is not the case for the above scenario, but it's worth taking into account, since not all companies think about this when designing their SPF structure. Just try to lookup, say, TXT for ebay.com and try to count the number of lookups that might result in ;-)

A: Yes, that will work. It's also the proper way to do it.