text:
Q: Change webpart name I have developed and deploy a webpart into SP2010. I would like make some changes to the webpart and show it to my clients but I need to keep the original webpart in case they dont like the new changes. So I would like to have 2 versions of my webpart on the server but use only one Visual Studio project.
In Visual Studio I made the following changes :
1. The solution name ( MyWebPart to MyWebPartNew)
2.  The assembly name (from the Properties window of the project)
3. The MyWebPart.webpart file to MyWebPartNew.webpart
    +
4. Element.xml
The 'new' webpart is successfully deployed on the server BUT it overwrote my old webpart :( . I looked into the debug output folder and see the dll and pdb file has changed to the new name but not the wsp file.
Have I missed something ? How do I add the new webpart without overwrite the old one from the same project ?
Thanks

A: The easieast way would probably be to add a new webpart next to your old one. In that case you can simply remove the old one if they prefer the new one.
But in your case, I think your problem is that you didn't change your wsp name (double click "package" in Visual studio) and that you didn't change you solution id (guid in properties window after you click package). What happens when you deploy (from Visual Studio) is that is first retract your old solution and then adds the new one resulting in that your old webpart is malfunctioning.
But as I wrote, I would suggest you instead create a new, identical webpart with your changes in it, and deploy it next to you old webpart.


text:
Q: Global Temporary tables I am trying my hands on global temporary table. As per my understanding global table should be accessible by other users and connection once it is created. Once all the references to the global temp table is closed then the table is dropped.
But in practice I can not see this happening. I opened two sql server sessions created a global temp table and then tried a select command from the other session so both of them are active.
Now once I close the session which was used to create the global temp table the table is dropped.
Why is that so even if there is another active session referencing the global temp table?

A:
Global temporary tables are visible to any user and any connection
  after they are created, and are deleted when all users that are
  referencing the table disconnect from the instance of SQL Server

The other session isn't actively referencing the temp table.
It takes locks whilst reading it and then releases them as soon as the table is read.
You would need to run it inside a transaction at at least REPEATABLE READ isolation level for the other session to be counted as referencing it and preventing the drop.
Session 1
CREATE TABLE ##T
(
X INT
)

Session 2
BEGIN TRAN
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ

SELECT *
FROM ##T;

RAISERROR('Waiting ...',0,1) WITH NOWAIT;
WAITFOR DELAY '00:00:10'; --Now can close the other session

SELECT *
FROM ##T;   --And the table should still be there

COMMIT

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connection timed out when connecting to a website (ubuntu only) I've been struggling with these problem for months. It happens randomly and it happens on Ubuntu only (12.04). It's about my hosted company website.
Some facts:

*

*I can ping it

*I can traceroute it

*I can dig it

*I can make a nslookup

But whenever I try to open it in Chrome it won't open. I also tried using polipo but got same connection time out issue.
I'm connected through a LAN network and I'm experiencing no problem with any other website.
Is there a more accurate debugging technique I'm missing other than pinging/tracerouting, etc.?

A: *

*Run tcpdump using something like this:
tcpdump -nieth0 -s0 -w/tmp/dump.pcap port 80 or icmp

or if you are not logged in as root
    sudo tcpdump -nieth0 -s0 -w/tmp/dump.pcap port 80 or icmp

*

*Attempt to access the website.

*Press Ctrl+C on tcpdump and then use the wireshark program to examine the capture file (/tmp/dump.pcap).  You can find Wireshark in the software centre.

*Do the same for a website that does work, and look for relevant differences.

*Do the same but at the hosting end.

A: Eliminate an MTU problem by pinging with increasingly large packets using ping's -s option, all the way up to 1492. If it turns out that large pings don't work, then something along your path cannot handle 1500-byte packets but is blocking the fragmentation needed packets from coming back.


text:
Q: How to select the association based on the Parent Class in Linq I am creating a web application where I need to fetch the order based on the orderId but they should be linked to the parent class.
public class StudentOrder
{
    public int Id { get; set; }
    public IList<Order> Orders { get; set; }
}

public class Order
{
    public int Id {get;set;}
    public string Name {get;set;}
}

public class EmployeeOrder
{
    public int Id { get; set; }
    public IList<Order> Orders { get; set; }
}

Now I have the OrderId and I need to fetch the details of the order.
NhSession.QueryOver<StudentOrder>()
    .Where(x => x.Orders.Any(y => y.Id == id)).SingleOrDefault();

How can I get by queryOver() and get the order details by Id. I dont want to query over directly over orders as they are linked with both different entity

A: QueryOver can navigate association paths using JoinQueryOver() as documented here. Example:
var studentOrder = NhSession.QueryOver<StudentOrder>()
                            .JoinQueryOver(so => so.Orders)
                            .Where(o => o.Id == orderId);


text:
Q: Ordering search of joined tables in 2 ways I am trying to search for the oldest outstanding invoice for each customer and then present the results in descending order of that invoice date however the result gives me the date of the most recent invoice. How can I ensure that it picks up the earliest invoice date? Many thanks in advance.
Here is my query:
$checkDebtors = "select
    a.accountNumber as accountNumber, a.balanceOutstanding as balanceOutstanding, a.companyName as companyName, b.invoiceDate as invoiceDate, b.netOutstanding as netOutstanding
from
    customersQQuote a
    Right JOIN invoices b ON a.accountNumber = b.accountNumber
WHERE   netOutstanding > 0 AND balanceOutstanding > 0
group by
    a.accountNumber
order by
     b.invoiceDate ASC";

A: Did you mean the result by following sql? Try it, if it does not work for you, leave a comment for me;)
select
    a.accountNumber as accountNumber,
    a.balanceOutstanding as balanceOutstanding,
    a.companyName as companyName,
    b.invoiceDate as invoiceDate,
    c.netOutstanding as netOutstanding
from
    (SELECT accountNumber, MIN(invoiceDate) AS invoiceDate FROM invoices GROUP BY accountNumber) b
    LEFT JOIN customersQQuote a ON a.accountNumber = b.accountNumber
    LEFT JOIN invoices c ON c.accountNumber = b.accountNumber AND c.invoiceDate = b.invoiceDate
WHERE   c.netOutstanding > 0 AND a.balanceOutstanding > 0
group by
    a.accountNumber
order by
     b.invoiceDate ASC

A: Above code has certain mistakes such as, alias name using in where clause and misuse of group by clause. you can apply this piece of code..
select a.accountNumber as accountNumber, a.balanceOutstanding as balanceOutstanding,
a.companyName as companyName, b.invoiceDate as invoiceDate, b.netOutstanding as netOutstanding
from customersQQuote a Right JOIN invoices b ON a.accountNumber = b.accountNumber
WHERE b.netOutstanding > 0 AND a.balanceOutstanding > 0 order by b.invoiceDate;

A: Your current code does not work as you have not specified which invoice to pull back. You have used GROUP BY accountNumber, so it will return one row for each accountNumber value. Other fields should be aggregate values (ie, the result of a aggregate function such as MIN() or MAX()). If fields are neither mentioned in the GROUP BY clause nor the result of an aggregate function then MySQL will return a value for that column, but which row that value comes from is not defined. It could be the first or the last rows value, or any in between (and could change between different versions of MySQL).
Most flavours of SQL do not allow a query like this and would error. MySQL has a feature that does allow this. But this feature can be configured to be turned off.
To do this in standard SQL and give you a consistent value you use a sub query to get the first invoiceDate for each accountNumber, using the MIN() aggregate function. Then you join this sub query against the invoices table to get the other columns.
SELECT a.accountNumber,
        a.balanceOutstanding,
        a.companyName,
        b.invoiceDate,
        b.netOutstanding
FROM
(
    SELECT accountNumber,
            MIN(invoiceDate) as invoiceDate
    FROM invoices
    GROUP BY accountNumber
) sub0
INNER JOIN invoices b ON sub0.account_number = b.account_number AND sub0.invoiceDate = b.invoiceDate
INNER JOIN customersQQuote a ON sub0.account_number = a.account_number

Note that if an accountNumber could have 2 identical first invoiceDate values then you will need to pick another field to minimise (ie, maybe your unique id field) for each date. Gets messy but something like this:-
SELECT a.accountNumber,
        a.balanceOutstanding,
        a.companyName,
        b.invoiceDate,
        b.netOutstanding
FROM
(
    SELECT accountNumber,
            MIN(invoiceDate) as invoiceDate
    FROM invoices
    GROUP BY accountNumber
) sub0
INNER JOIN
(
    SELECT accountNumber,
            invoiceDate,
            MIN(id) as id
    FROM invoices
    GROUP BY accountNumber, invoiceDate
) sub1 ON sub0.accountNumber = sub1.accountNumber AND sub0.invoiceDate = sub1.invoiceDate
INNER JOIN invoices b ON sub1.account_number = b.account_number AND sub1.invoiceDate = b.invoiceDate AND sub1.id = b.id
INNER JOIN customersQQuote a ON sub0.account_number = a.account_number

A: Thank you for your advice. I got some good tips from your answers which helped me solve the problem. The main thing being the use of MIN() and also that I was using Right join rather than Left. Additionally I just used the invoiceDate keyword in the ORDER BY rather than the b.invoiceDate. I guess this ensured the MIN rule was used here as well. Thanks to you I ended up getting the result I needed.
select
    a.accountNumber as accountNumber, a.balanceOutstanding as balanceOutstanding, a.companyName as companyName, MIN(b.invoiceDate) as invoiceDate, b.netOutstanding as netOutstanding
from
    customersQQuote a
    Left JOIN invoices b ON a.accountNumber = b.accountNumber
WHERE  netOutstanding > 0 AND balanceOutstanding > 0
group by
    a.accountNumber
order by invoiceDate ASC


text:
Q: Unwanted behaviour in phaser weapon plugin I am having difficulty in handling collision between asteroid and bullets.
The collision is never happening!!!
        <!doctype html>
        <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <title>My Game</title>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.6.2/phaser.min.js"></script>
            <style type="tex`enter code here`t/css">
                body {
                    margin: 0;
                }
            </style>
        </head>
        <body background-color = "#6666ff">

        <script type="text/javascript">

        var game = new Phaser.Game(1090, 525, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render });

        function preload() {

            game.load.image('neb', 'nebu.jpg');
            game.load.image('ship', 'thrust_ship5.png');
            game.load.spritesheet('bullet', 'rgblaser.png', 4, 4);
            game.load.image('asteroid', 'asteroid1.png');
            game.load.audio('boden', 'war1.mp3');
            game.load.audio('fire', 'fire1.wav');

        }

        var sprite;
        var weapon;
        var cursors;
        var fireButton;
        var fx;
        var asteroid;

        function create() {

            back = game.add.image(-400, -400, 'neb');
            weapon = game.add.weapon(40, 'bullet');
            asteroid = game.add.image(800,200,'asteroid');
            music = game.add.audio('boden');
            music.loop = true;
            fx = game.add.audio('fire',0.1);

            back.smoothed = false;

            music.play();

            weapon.setBulletFrames(0, 80, true);

            weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;

            weapon.bulletSpeed = 400;

    //  Speed-up the rate of fire, allowing them to shoot 1 bullet every 50ms
            weapon.fireRate = 50;

Wrap bullets around the world bounds to the opposite side
            weapon.bulletWorldWrap = true;

            sprite = this.add.sprite(400, 300, 'ship');
            game.physics.enable(sprite, Phaser.Physics.ARCADE);
            game.physics.enable(asteroid, Phaser.Physics.ARCADE);
            game.physics.enable(weapon, Phaser.Physics.ARCADE);
            sprite.physicsBodyType = Phaser.Physics.ARCADE;
            sprite.anchor.set(0.5);

            game.physics.arcade.enable(sprite);

            sprite.body.drag.set(70);
            sprite.body.maxVelocity.set(200);

Tell the Weapon to track the 'player' Sprite
With no offsets from the position
But the 'true' argument tells the weapon to track sprite rotation
            weapon.trackSprite(sprite, 0, 0, true);

            cursors = this.input.keyboard.createCursorKeys();

            fireButton = this.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR);

        }

        function update() {

            game.physics.arcade.collide(asteroid,weapon, collision_handler, null, this);

            if (checkOverlap(asteroid, sprite))
            {
                console.log("Hi, overlap occured!");
                asteroid.kill();
            }

            if (checkOverlap1(weapon, asteroid))
            {
                console.log("Hi, overlap occured in iffffffffffffffff!");
                asteroid.kill();
                //weapon.kill();
            }

    //game.physics.arcade.collide(weapon, asteroid);
    //game.physics.arcade.overlap(weapon, asteroid, collisionHandler, null, this);

            game.physics.arcade.overlap(sprite, asteroid, hitEnemy, null, this);

            if (cursors.up.isDown)
            {
                game.physics.arcade.accelerationFromRotation(sprite.rotation, 300, sprite.body.acceleration);
            }
            else if (cursors.down.isDown)
            {
                game.physics.arcade.accelerationFromRotation(sprite.rotation, -300, sprite.body.acceleration);
            }
            else
            {
                sprite.body.acceleration.set(0);
            }

            if (cursors.left.isDown)
            {
                sprite.body.angularVelocity = -300;
            }
            else if (cursors.right.isDown)
            {
                sprite.body.angularVelocity = 300;
            }
            else
            {
                sprite.body.angularVelocity = 0;
            }

            if (fireButton.isDown)
            {
                weapon.fire();
                fx.play();
            }

            game.world.wrap(sprite, 16);

        }

        function render() {

           // weapon.debug();

        }

        function hitEnemy (one, two) {
                one.kill();
                two.kill();
                console.log("Hit");
         }

         function checkOverlap(spriteA, spriteB) {

            var boundsA = spriteA.getBounds();
            var boundsB = spriteB.getBounds();

            return Phaser.Rectangle.intersects(boundsA, boundsB);

        }

         function checkOverlap1(spriteA, spriteB) {

            var boundsA = spriteA.bounds;
            var xcor = spriteA.x;
            var ycor = spriteB.y;
            var boundsB = spriteB.getBounds();
            //console.log(xcor + "" + ycor);
            //console.log("Inside Collision 1");

            //console.log(Phaser.Rectangle.contains(spriteB,xcor, ycor));
            return Phaser.Rectangle.contains(spriteB,xcor, ycor);

        }

        function collision_handler (object1, object2) {
                 //object1.kill();
                 object2.kill();
        }

        </script>

        </body>
        </html>


text:
Q: Deep link is not working at chrome expo react native project Am integrated Deeplink in my expo project and i tried to open app with deeplink in chrome its not working. Actually i need to send the link in mail, when user click the link then i want app should open. Androidmainfest file
 <activity
        android:name=".MainActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:launchMode="singleTask"
        android:theme="@style/Theme.Exponent.Splash"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <data android:scheme="mychatapp" android:host="inbox" />

            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

i Added same scheme to my React native app.json
  "scheme": "mychatapp" and App.js i added
this is my code. I tried all the way to run deep link in chrome but its not working. Please tell where am doing mistake on it.

A: good example
Very easy... try...
In my case works... but not open the correct screen


text:
Q: eager loading deeply nested relationships? I have a series of tables related like so;
trainers -> hasMany -> programs
programs -> hasMany -> weeks
weeks -> hasMany -> days
days -> hasMany -> sessions
sessions -> hasMany -> phases
phases -> hasMany -> excersises

the relationships in the opposite direction are all has one accept for excersises to phases which is also hasMany with a pivot table
getting relationships one deep like this per the documentation works fine obviously
$programs = $this->program->orderBy('trainerId', 'asc')->take(1)->with('weeks.days')->get();

I need to be able to retrieve the contents of an entire program and I thought that I could eager load each nested relationship something like this
$programs = $this->program->orderBy('trainerId', 'asc')->take(1)->with('weeks.days', 'weeks.days.sessions')->get();

or
$programs = $this->program->orderBy('trainerId', 'asc')->take(1)->with('weeks.days.sessions')->get();

but both return a FatalErrorException

Call to undefined method
  Illuminate\Support\Facades\Session::newQuery()

whats the correct way to do this?

A: From your question, I can see you have nested relationship like the following.
programs -> hasMany -> weeks
-----------------------------weeks -> hasMany -> days
----------------------------------------------------days -> hasMany -> sessions

It is very hard to know what data should load for days if we do not know the weeks. Similarly for the sessions as well. So, we have to load the weeks data first then days, then sessions.
From Laravel documentation, we can see, Eager loading using the following approach:
select * from books

select * from authors where id in (1, 2, 3, 4, 5, ...)

Laravel loading author data based on books data.
http://laravel.com/docs/eloquent#eager-loading
Try to load weeks first
$programs = $this->program->orderBy('trainerId', 'asc')
   ->take(1)
   ->with('weeks', 'weeks.days', 'weeks.days.sessions')
   ->get();

or:
Lazy Eager Loading:
 $programs = $this->program->orderBy('trainerId', 'asc')->take(1)->get();

 $programs->load('weeks', 'weeks.days', 'weeks.days.sessions');

A: So I found the problem and it might help someone else to know the answer.  this thread gave me the aha moment laravel forums
I have a model called Session, laravel uses that name elsewhere in the framework, duh, so when it tries to call my model it is actually calling the other session class from somewhere deep in the framework.  some of the solutions i found suggest namespaces but I dont think that will work for me because the relationship declaration simply passes a string with the class name to the framework.  I think this means that the calling of the class happens elsewhere and I would need to put the namespace /use there correct me if I am wrong please.
either way changing the session class to Sessionss and changing the relationships to suit has resolved my issue.
i hope this helps someone else not waste 36 hours trying to figure this out :p


text:
Q: PostgreSQL Copy to FTP Server we can use
copy (select * from mytbl) to 'D:/products.csv' with csv header

to import data in mytbl to local disk D
so is it possible to use the same method to upload the file directly into a FTP-Server ?
i tried like this
copy (select * from mytbl) to 'ftp://usrname:mypasswrd@ftp.drivehq.com/masters/3/product/products.csv' with csv header

but got this error
ERROR: relative path not allowed for COPY to file
SQL state: 42602

using PostgreSQL 9.2

A: PostgreSQL does not support any source/destination for COPY other than a file or stdin/stdout.
What you can do is COPY to stdout and pipe that to a program that writes the data to the ftp dir. psql's \copy is useful for this:
psql -c "\copy mytable to stdout with (format csv, header)" | ncftpput -c my.ftp.host /path/on/host

You can use any tool that accepts the input data on a pipe to write to the remote ftp file; ncftpput is just one option.
A future PostgreSQL version may add support for invoking COPY with a pipe, e.g. COPY ... TO '|/some/command', but there are serious security concerns with running programs under the PostgreSQL user that would make this a superuser-only operation and of questionable safety even then. It's much safer to run the program client-side, and psql is ideal for that.


text:
Q: Git revert a commit that has some other commit depending on it Let's say we have commit A and B, and B depends on A's modification.
We want to revert A, will that be successful? Also, what would happen if a line added by 'A' is no longer present?

A: git will report that the revert resulted in a conflict.  git status will show the unmerged paths.
You can resolve the conflict like any other.

Edit with example:
$ mkdir foo
$ cd foo
$ git init
$ echo "this is a line in a file" > blah
$ echo "this is a second line in a file" >> blah
$ echo "this is a third line in a file" >> blah
$ git add blah
$ git commit -m "first commit"
# edit the second line in blah
$ git commit -am "second commit"
# remove the second line from blah
$ git commit -am "third commit"
$ git revert HEAD^ #revert the second commit
error: could not revert 4862546... another change
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'
$ git status
# On branch master
# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add <file>..." to mark resolution)
#
#   both modified:      blah
#
no changes added to commit (use "git add" and/or "git commit -a")

In the case that the first commit added the file and the second modified that file, git status will show this:
$ git status
# On branch master
# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add/rm <file>..." as appropriate to mark resolution)
#
#   deleted by them:    blah
#


text:
Q: C++: Erasing an iterator from a map and then incrementing to the next iterator This method causes an abort error: "map/set iterator not incrementable."
Due to that after the if fails and a vaild iterator that should be erased is determined, (and is), continuing to the next iterator in the map via ++_iter fails because _iter is no longer a valid object/pointer.
What is the correct procedure for iterating through a map AND having the ability to remove individual items throughout?
typedef std::map<std::string, BITMAP*> MapStrBmp;
typedef MapStrBmp::iterator MapStrBmpIter;
\\...
void BitmapCache::CleanCache() {
    //Clean the cache of any NULL bitmaps that were deleted by caller.
    for(MapStrBmpIter _iter = _cache.begin(); _iter != _cache.end(); ++_iter) {
        if(_iter->second != NULL) {
            if((_iter->second->w < 0 && _iter->second->h < 0) == false) continue;
        }
        _cache.erase(_iter);
    }
}

A: You just have to be a bit more careful:
void BitmapCache::CleanCache() {
    //Clean the cache of any NULL bitmaps that were deleted by caller.
    for(MapStrBmpIter _iter = _cache.begin(); _iter != _cache.end(); ) {
        if(_iter->second != NULL) {
            if((_iter->second->w < 0 && _iter->second->h < 0) == false)
            {
                ++_iter;
                continue;
            }
        }

        _cache.erase(_iter++);
    }
}

A: map::erase(iterator) gives you an iterator pointing to the next element in the map (if any) after erasing. Therefore, you can do:
for(MapStrBmpIter _iter = _cache.begin(); _iter != _cache.end(); ) {
    if(_iter->second != NULL) {
        if((_iter->second->w < 0 && _iter->second->h < 0) == false) {
           ++_iter;
           continue;
        }
    }
    _iter = _cache.erase(_iter);
}

A: The standard erase loop for an associative container:
for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
    if (delete_condition)
    {
        m.erase(it++);
    }
    else
    {
        ++it;
    }
}

A: The canonical way to safely erase iterators during an iteration is to use the result of container::erase:
void BitmapCache::CleanCache() {
    //Clean the cache of any NULL bitmaps that were deleted by caller.
    MapStrBmpIter _iter = _cache.begin();
    while (_iter != _cache.end()) {
        bool erase_entry= true;
        if(_iter->second != NULL) {
            if((_iter->second->w < 0 && _iter->second->h < 0) == false)
                erase_entry= false;
        }

        if (erase_entry)
            _iter= _cache.erase(_iter);
        else
            ++_iter;
    }
}


text:
Q: how to loop through object and check if it has another object as an attribute with a name "test__c" I have an object as below which contains 3 other objects
var masterObject = {
                     test__a:{},
                     test__b:{},
                     test__c{}
                   }

Here i want to check if my marsterObject contains test__c. Please let me know how can i check it in Javascript.

A:

var masterObject = {
  test__a: {},
  test__b: {},
  test__c: {}
}

console.log(masterObject.hasOwnProperty("test__c"));
console.log(masterObject.hasOwnProperty("test__d"));

A: test__c is a property of masterObject and can be accessed with the dot notation,
if(masterObject.test__c !== undefined && masterObject.test__c !== null){
 // do something ith test__c
}

if, the property, that you want to check, itself could vary, then use the associative array synxtax,
if(masterObject[test__c] !== undefined && masterObject[test__c] !== null){
     // do something ith test__c
 }


text:
Q: JS Using data-attributes inside conditionals I have a bootstrap modal with 3 options users can select.  If they choose the 3rd option (Search by service), it takes you to a new panel (#service-box) with a list of service options.  I'm trying to add functionality so that when the user clicks once of the services it shows the #service-options panel with locations that offer that service.
I have it hard coded now to show all three locations on the #service-options panel, but I'm trying to figure out a way that I can add an attribute to each service so that when clicked It takes them to  #service-options panel with buttons for only the locations with that attribute.
Here is a code pen with what I have so far...
https://codepen.io/aaron4osu/pen/poyKvjQ?editors=1010
here are the two panels

 Back

Service 1

Service 2

Service 3

Service 4

Service 5

Service 6

Service 7

Service 8

 Back

 Back

Location 1

Location 2

Location 3

 Back

        $(document).ready(function () {
          $(".btn-toggle").click(function () {
            //var destination = $(this).attr("href");
            var destination = $(this).data("destination");
            $(".search-box").slideUp("slow");
            $(destination).slideDown("slow");
          });

          $(".close").click(function () {
            $(".search-box").slideDown("slow");
            $(".toggleSearch").slideUp("slow");
          });
        });

Any help would be greatly appreciated.

A: Based on your requirement, you can define an event to catch when a service button is clicked.
You will get the value from there: $(this).data('locations').
Since you have multiple locations, you can split them by , character and cut the white space ahead.
Lastly, inside service-options modal, you select all location buttons and filter them based on the text inside. You hide all of them first, then showing the matched locations after filtering.
$('.service.btn-toggle').click(function () {
    var locations = $(this).data('locations').split(',').map(function (location) {
      return location.trim();
    });

    $('#service-options .btn-block').hide().filter(function () {
       return locations.indexOf($(this).text().trim()) > -1;
    }).show();
});


text:
Q: How can prevent a space from being appended to the tab-completed word using Perl's Term::Readline? I am using tab completion support of Term::ReadLine::Gnu module. Every time I do a tab, I get a space after the completed word.
For example:
If i have a word "complete" as a possible completion. After prompt I pressed tab and I am
getting it like:
"complete "
where these is a space at the end of the completed word. What I want is:
"complete"
Is there any way to remove that space?

A: Try this (untested) in your completion function:
my $attribs = $term->Attribs;
$attribs->{completion_suppress_append} = 1;

This corresponds to the rl_completion_suppress_append variable in GNU readline.


text:
Q: C# Web Proxy request I am trying to make a web proxy. Here is what I have so far:
    IPHostEntry IPHost = Dns.GetHostEntry(sURL);
    Console.WriteLine("Resolved:{0}", IPHost.HostName);
    string[] aliases = IPHost.Aliases;
    IPAddress[] address = IPHost.AddressList;
    Console.WriteLine(address[0]);

    IPEndPoint sEndpoint = new IPEndPoint(address[0], 80);
    Socket IPsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,   ProtocolType.Tcp);
   IPsocket.Connect(sEndpoint);
   if (IPsocket.Connected)
   {
      Console.WriteLine("Socket OK");
   }

   NetworkStream ns = new NetworkStream(IPsocket);
   StreamWriter sw = new StreamWriter(ns);
   StreamReader sr = new StreamReader(ns);

   for (int i = 0; i < lista.Count; i++)
   {
      sw.WriteLine(lista[i]);
      Console.WriteLine(lista[i]);
   }
   sw.Flush();
   string response = sr.ReadToEnd();</pre>

And how I read the request:
StreamReader sr = new StreamReader(s);
string plusz = "";
plusz = sr.ReadLine();
while (plusz != "")
{
    lista.Add(plusz);
        plusz = sr.ReadLine();
}
return lista;

The request looks like this:
GET http://google.com/ HTTP/1.1
Host: google.com
Proxy-Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: hu-HU,hu;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.3
Cookie: rememberme=true; NID=54=l
(...)
 pY

And as you can see I sent this exactly. The problem is that the program stops at the sr.ReadToEnd() method. It is just waiting for the data to arrive, but nothing happens. If I send a wrong request, then it works, so the browser displays the wrong request page (400).

A: namespace ProxyTester
{

class Program
{
    static void Main(string[] args)
    {
        var htmlResponse = new StringBuilder();
        var RequestPage = BuildHttpRequest("https://google.com/");
        GetHttpResponse(RequestPage, htmlResponse);
    }

    public static HttpWebRequest BuildHttpRequest(string url)
    {
        try
        {
            var getPage = (HttpWebRequest)WebRequest.Create(url);
            WebProxy proxyHTTP = new WebProxy("201.38.194.50", 53128);

            getPage.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            getPage.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.19) Gecko/20110707 Firefox/3.6.19";
            getPage.ProtocolVersion = HttpVersion.Version11;
            getPage.Method = "GET";
            getPage.Proxy = proxyHTTP;
            getPage.Timeout = 10000;
            getPage.ReadWriteTimeout = 10000;
            return getPage;
        }
        catch (WebException ex)
        {
            Console.WriteLine(ex.ToString());
        }

        return null;
    }

    public static bool GetHttpResponse(HttpWebRequest page,  StringBuilder htmlResponse)
    {
        htmlResponse.Length = 0;
        try
        {
            Console.WriteLine("A");
           // var pageResponse = page.GetResponse();
            page.Timeout = 10000;
            var pageResponse = (HttpWebResponse)page.GetResponse();
            Console.WriteLine("5 minutes!");
            if (pageResponse.StatusCode == HttpStatusCode.OK)
            {

                var reader = new StreamReader(pageResponse.GetResponseStream());
                htmlResponse.Append(reader.ReadToEnd());
                pageResponse.Close();
                reader.Close();
                return true;
            }
            Console.WriteLine(pageResponse.StatusCode.ToString());
            pageResponse.Close();
            return false;
        }
        catch (WebException ex)
        {
            Console.WriteLine(ex.ToString());
        }

        return false;
    }
}

}


text: Q: need help on font rendering from website to safari, preview and adobe I am on an iMac with high Sierra 10.13.6.  Have been having this issue over multiple os for a long time.  When i go to my financial website and view A monthly statement I n safari pop up, the font is hard to read and too close.  Same in Adobe reader when opened in the downloaded .pdf.  If I do the same in Firefox it looks good until I download it then its too close again.  No issues on a pc.  ive tried to change the screen resolution with no effect.  also checked the Mac fonts and all seem to be good - no corruption.  any ideas on what to check.  the attached is a small sample of adobe / safari too close together and what I would expect and like to see form firefox.  Still troubleshooting this one. Spent another hour on the phone with the bank - no luck. Have now discovered that while the file can be viewed ok with Firefox, I get the messed up fonts when printing from there.  Also have tried to export from Firefox as .pdf file with no luck either - then the fonts stagger between small-normal to oversized. Still trying to figure it out.


text:
Q: How can i rotate an Cube I'am new to OpenGL  and i have a Question about how can i rotate my Cube around the Y-Axis.
I have an Model,Projection and View Matrix,with which i display my Cube.But i dont understand how i can animate my Cube.What i thought of was, that i use the Model-Matrix for that.
For Example :mat4 model = rotate(mat4(1.0f),(float)currenttime*45.0f,vec3(0.0f,1.0f,0.0f));
Actually this changes nothing ;)
The other thing is, that i often read about glRotatef etc.For what are these Calls, when i use Matrices to translate or rotate my Objecct?
I use GLFW,GLEW and GLM.
Hope someone can help me out with this.(I know there are plenty Threads about this, but most of them are using other Librarys or are deprecated)


text:
Q: By mistake, I called a Sinatra Ruby file app.py and it still worked, why? I named a Ruby file app.py and it worked. I only noticed later. Why is that possible. It wasn't anything complicated, just a small Sinatra recipe but still, I don't understand.

A: Under Unix (say, Linux or similar), the first line of a script contains the path to its interpreter. The line's called Shebang or Crunchbang and looks like that: #! /usr/bin/ruby
If you rename you file, the path to the interpreter still remains unchanged and therefore the script will be executed as before.


text:
Q: Calling JavaScript async function in for loop I have a for loop and I want to call an async function on each iteration. But I am getting a JS stack trace error. Below is the prototype of my code. I have also used IIFE pattern but it's not working.
for(let i = 0; i<99999;i++){
  getData(i, function(err, result){
      if(err) return err;
      else{
       console.log(result);
      }
  });
}
function getData(number, callback){
  request('http://someapiurl'+number, function(err, response){
     if(err) callback(err, null);
     else{
      callback(null, response)
     }
  })
}

A: You re trying to make 99999 at the same time, this just won t work on most browsers.
Use promises instead, push them in an array, then use Promise.all to let the browser handle the request, simply handle the final resolved response.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([p1, p2, p3]).then(values => {
  console.log(values); // [3, 1337, "foo"]
});

A: First of all I highly suggest that you debug your code to see exactly what happens with the for loop.
Its very likely that the loop runs completely before its contents (the getData function) executes, asynchronous behavior of via a fetching data request. If you tried using the IIFE pattern you'd have at least wrapped the contents inside your for loop in a way that guarantees its contents to execute. An example of an implementation looks like so:
for(let i = 0; i<99999;i++){
  (function(){ // <-- IIFE used to represent a closure.
    getData(i, function(err, result){
      if(err) return err;
        else{
          console.log(result);
        }
    });
  })(i);
}

To let @mika sit on the subject of promises for you, which you can read on their answer; just keep in mind the promise anti-pattern and you'll be fine. It is especially tricky if you are not used to promises and want to use them in a for loop.


text:
Q: Upper case file code templates CLion How to put my filename variable ${NAME} in the file and code template section into upper case when I create a file ?
The only way i found is to press the combination cmd + shift + U in the files but when I have a lot of then it takes pretty much time !
For exemple when i create a test.hpp file, I want to have #ifndef TEST_HPP_ in it, here is my template for now : #[[#ifndef]]# ${NAME}_HPP_

A: If you go to File and Code Templates Help on Jetbrains website (https://www.jetbrains.com/help/clion/file-and-code-templates.html).

File and code templates are written in the Velocity Template Language
(VTL)
...
Create custom template variables and define their values right in the
include template using the #set VTL directive. For example, to insert
your full name in the file header instead of your login name defined
through the ${USER} variable, write the following construct:
#set( $MyName = "John Smith" )

Meaning that you can use this syntax for putting your string in uppercase.
Here is an example for your problem (from Velocity string function):
#set($nameUpper = ${NAME})
#set($nameUpper = $nameUpper.substring(0).toUpperCase())

Then, you can then use your new variable for your ifndef.
#[[#ifndef]]# ${nameUpper}_HPP_
#[[#define]]# ${nameUpper}_HPP_

#[[#endif]]# //${nameUpper}_HPP_

Woking on CLion 2017.3.3


text:
Q: How to reload a panel without using CardLayouts? TLDR; :
I'm looking for a way to reload JPanels and its components.
I'd like to implement a dynamically changing JComboBox.
This is the situation:

There is a button, which generates data in background ("generate content") here it is just some random numbers. After the data is generated, this data should be selectable inside a JComboBox.
/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new JPanel();
    frame.getContentPane().add(panel, BorderLayout.CENTER);
    panel.setLayout(null);

    comboBox = new JComboBox<String>();

    comboBox.setBounds(39, 63, 144, 20);
    panel.add(comboBox);

    btnGenerateContent = new JButton("generate content");
    btnGenerateContent.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            comboContent = fillrandoms();
            comboBox = new JComboBox<>(fillrandoms());

        }
    });
    btnGenerateContent.setBounds(39, 11, 117, 23);
    panel.add(btnGenerateContent);
}

private static String[] fillrandoms() {
    String[] array = new String[10];
    for (int i = 0; i < 10; i++) {
        array[i] = "" + Math.random() * 100;

    }

    return array;
}

now when I execute the program, it will declare and initalize the combobox before there is data to display. My idea was now that when I hit the "generate content" button, this will also update the UI for the panel or the ComboBox. but when I insert panel.updateUI() or comboBox.updateUI() nothing happens.
After researches I found some ways to do it with CardLayouts, but I do not use them for my JComboBox, so I propably need another way.
I don't even know if this is the common way or is there any other better way.

A: To update UI use method panel.revalidate(), panel.repaint(), or revalidate().
revalidate() and repaint() method are proper way to reflect UI update task.


text:
Q: Web-app version is overridden when launching Tomcat 7 from Eclipse I'm developping a web application that is using web-fragment.xml files.
AFAIK, the web-framgent.xml files of the JAR in WEB-INF/lib should be merged and resolved to an effective web.xml.
So, I activate the logEffectiveWebXml option of my Tomcat 7 server to see the resulting file.
Hereby the beginning of the effective web.xml file:
Case 1: When the application is deploy on a standalone Tomcat 7:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0"
         metadata-complete="true">

Case 2: When the application is deploy on a Tomcat 7 in Eclipse IDE:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="2.5"
         metadata-complete="true">

You notice that the version attribute is replaced with "2.5".
Besides, the effective web.xml is correct when deploying the app on the standalone Tomcat (the content of web-fragments.xml files are merged) whereas these contents are absent when launching Tomcat from Eclipse.
I think this is due to the version override.
Do you know why the version attribute is overriden when launching in Eclipse?
I inspect Eclipse configuration, projects configuration (they all use dynamic web module 3.0) and workspace directory ".metadata.plugins\org.eclipse.wst.server.core" but I don't manage to find something wrong...
NOTE: I also notice that the version is overridden even if I don't deploy my application (= fresh Tomcat install).
Thanks for your help.


text:
Q: Remove stopwords from dataframe dataframe['Text'] = dataframe['Text'].apply(lambda x : ' '.join([item for item in string.split(x.lower()) if item not in stopwords]))

I am removing the stop words from the dataframe. Logic is working fine, but when there is some empty row comes it gives error.
I have used dropna() but it will drop the whole line instead there is data in other column.
How to add condition in above logic that column Text should not null

A: use before your logic,
dataframe.dropna(subset=['Text'], how='all')

A: You can replace NaN to empty list what is not easy - use mask or combine_first by Series created by empty lists:
pos_tweets = [('I love this car', 'positive'),
('This view is amazing', 'positive'),
('I feel great this morning', 'positive'),
('I am so excited about the concert', 'positive'),
(None, 'positive')]

df = pd.DataFrame(pos_tweets, columns= ["Text","col2"])
print (df)
                                Text      col2
0                    I love this car  positive
1               This view is amazing  positive
2          I feel great this morning  positive
3  I am so excited about the concert  positive
4                               None  positive

stopwords =  ['love','car','amazing']
s = pd.Series([[]], index=df.index)
df["Text"] = df["Text"].str.lower().str.split().mask(df["Text"].isnull(), s)
print (df)
                                        Text      col2
0                       [i, love, this, car]  positive
1                  [this, view, is, amazing]  positive
2            [i, feel, great, this, morning]  positive
3  [i, am, so, excited, about, the, concert]  positive
4                                         []  positive

df['Text']=df['Text'].apply(lambda x:' '.join([item for item in x if item not in stopwords]))
print (df)
                                Text      col2
0                             i this  positive
1                       this view is  positive
2          i feel great this morning  positive
3  i am so excited about the concert  positive
4                                     positive

Another solution:
stopwords =  ['love','car','amazing']
df["Text"]=df["Text"].str.lower().str.split().combine_first(pd.Series([[]], index=df.index))
print (df)
                                        Text      col2
0                       [i, love, this, car]  positive
1                  [this, view, is, amazing]  positive
2            [i, feel, great, this, morning]  positive
3  [i, am, so, excited, about, the, concert]  positive
4                                         []  positive


text:
Q: How to skip a callback in a dependent model on destroy I have providers and positions. When the provider is destroyed, I need to destroy any positions. However, my check_primary method, in position.rb is crashing when I try and destroy a provider.
provider.rb
  has_many :positions, dependent: :destroy

position.rb
  after_destroy :check_primary

  def check_primary
    unless provider.primary_position # this shouldn't run when destroying a provider
      if provider.positions.present?
        provider.positions.first.update_column(:primary, true) # crash here
      end
    end
  end

Error on provider destroy: cannot update a destroyed record
My Question
I would like to put a skip_callback in provider.rb which skips check_primary in position.rb whenever the provider.destroy method is called. How can I accomplish this?
When analyzing the parent object with pry from within :check_primary I see:
>> provider.destroyed?
=> false
>> provider.frozen?
=> false
>> provider.marked_for_destruction?
=> false

UPDATE
I can't figure this out for now... So here's a really bad workaround:
  def check_primary
    unless provider.primary_position
      begin
        provider.positions.first.update_column(:primary, true)
      rescue
        nil
      end
    end
  end

A: Try skipping it in the context of destroy. In position.rb:
skip_callback :check_primary, on: destroy

EDIT to resolve my misunderstanding. I had more confidence in my original, off-point answer but I believe you can simply pass it a condition as follows:
skip_callback :check_primary, if: -> { #conditions }

A: I believe Rails has a callback for this:  after_remove, which in this case would be used like (in Provider.rb) -
  has_many :positions, dependent: :destroy, after_remove: :check_primary

and then move check_primary into the Provider model and modify it to act from within that class rather than the Position class.


text:
Q: Multithreading problems with xmlrpclib.ServerProxy under python 2.7 I have an application which instantiates an xmlrpclib.ServerProxy once, and then passes it to several threads (web application requests), which all perform XML/RPC calls simultaneously. This works well with python 2.6. With python 2.7, we're getting a lot of errors (ResponseNotReady, CannotSendRequest) as soon as we're in a multi-threaded environment.
# This code works well in python 2.6, and breaks in python 2.7.

import xmlrpclib
import thread

proxy = xmlrpclib.ServerProxy("http://localhost:5000/")

def fetch_users():
  print proxy.getUsers()

for _ in range(10):
  thread.start_new_thread(fetch_users, ())

while(1):
  pass

What is the problem here, and is there a thread-safe way of re-using the ServerProxy-object?

A: We found the cause for the problem: In python 2.6, a TCP connection is created on every XML/RPC method call. Python 2.7, on the other hand, opens a single TCP connection for each ServerProxy-object, and keeps it open (with servers that support keep-alive). Furthermore, the class is not thread-safe, so that concurrent requests may interfere with each other.
Apparently, the 2.6 version was thread-safe implicitely, as TCP connections do not get reused and all the connection-specific data seems to be kept in non-shared stack variables.
So possible solutions would be:

*

*Create a ServerProxy object (and implicitely open a TCP connection) for each thread

*Lock the access to a single, shared ServerProxy object

*Implement a request queue

A: Most code isn't threadsafe. However I don't know why the code would work in 2.6 but raise errors in 2.7.
Here's another take on the problem:

*

*uses higher-level threading module

*proxy is per-thread, not global. This is safer, so the threads don't mess each other up by overwriting a shared global object.

*threads are explicitly join()ed at the end, to make sure they all completed
source
import xmlrpclib
import threading

def fetch_users():
    proxy = xmlrpclib.ServerProxy("http://localhost:5000/")
    print proxy.getUsers()

for _ in range(10):
  threading.Thread(target=fetch_users, args=()).start()

# wait for all threads to exit
for th in threading.enumerate():
    th.join()


text:
Q: .Net Remoting - How to recover from server crash I have looked all over the place and have never seen an example of how to do this, even tho it's alluded to in blogs. But examples are never given.
I have a .Net remoting client that is connected to a server which is published as a well known type over tcp/ip. It holds an object reference to the server and instantiates it via the new operator.
If the server crashes, the easy part is detecting this, just catch the error.
Looping and waiting for the server to come back up will again be no problem.
But how to reset / reboot / unregister then re-register the remoting stack on the client?!?
If the client is restarted after the server comes back up, it works again, but obviously I want to just reconnect within the client application and not have to reboot it.

A: Windows Communication Foundation does not have the same issue. When the server goes down, the connection can be programatically re-established.


text:
Q: Does Facebook Realtime API with webhook works with Page comments and User Posts as well? Does facebook realtime api works when someone comments on a post or create a post on the page?

A: Yes!
Use feed you wil get comments, like and posts.
Webhook for Facebook with Subscriptions


text:
Q: Add column with a sum total to crosstab() query in PostgreSQL 9.0 Following on from my previous question:
Creating crosstab() pivot table in PostgreSQL 9.0
I managed to create a pivot table for ageband using the crosstab() function. I can use this to either create a view or table of the base geometry-less table.
However, this still isn't much use as I need to link it to the gazetteers_and_addresses.unit_postcode table in order to assign geometries for further analysis.
I will attach the table structure for both tables and the original code that worked to create my crosstab.
CREATE OR REPLACE VIEW adult_social_care.vw_ageband AS (
    SELECT * FROM crosstab(
        'SELECT postcode_nospace_, ageband, count(ageband) as total_count
         FROM adult_social_care.activities_in_localities_asc
         GROUP BY postcode_nospace_, ageband
         ORDER BY postcode_nospace_'

         ,$$VALUES ('18-24'::text), ('25-34'), ('35-44'), ('45-54'), ('55-64'), ('65-74'), ('75-84'), ('85-94'), ('95 AND OVER')$$)
    AS ct("postcode" text, "18-24" numeric, "25-34" numeric,"35-44" numeric, "45-54" numeric, "55-64" numeric, "65-74" numeric, "75-84" numeric, "85-94" numeric, "95 AND OVER" numeric));

Table defintions:
activities_in_localities_asc:
CREATE TABLE adult_social_care.activities_in_localities_asc (
  ogc_fid integer NOT NULL,
  sort numeric(5,0),
  ageband character(12),
  postcode_nospace_ character(8),
  wkb_geometry geometry,
  CONSTRAINT activities_in_localities_asc_pkey PRIMARY KEY (ogc_fid)
);

unit_postcode:
CREATE TABLE gazetteers_and_addresses.unit_postcode (
  oogc_fid serial NOT NULL,
  pc_area character(10),
  postcode_nospaces text,
  wkb_geometry geometry
);

If possible too, assign another field at the end which states a sum of all the fields to give a total_count.
If this can be done then I can create dynamic views on different factors using one geometry-less table and unit_postcode.

A: Proper crosstab query
First of all, the presented query would not work while you still have char(n) in your table definition - like we discussed under your previous question. You would need to convert to text or varchar first.
This works with your current table definition:
SELECT * FROM crosstab(
   'SELECT postcode_nospace_::text, ageband::text, count(ageband) AS ct
    FROM   adult_social_care.activities_in_localities_asc
    GROUP  BY 1, 2
    ORDER  BY 1'

   ,$$VALUES ('18-24'::text), ('25-34'), ('35-44'), ('45-54'), ('55-64')
           , ('65-74'), ('75-84'), ('85-94'), ('95 AND OVER')$$
   )
AS t("postcode" text
   , "18-24" bigint, "25-34" bigint,"35-44" bigint, "45-54" bigint, "55-64" bigint
   , "65-74" bigint, "75-84" bigint, "85-94" bigint, "95 AND OVER" bigint);
I am also using bigint instead of numeric to save another unnecessary type conversion (count() returns bigint).
Detailed explanation:

*

*PostgreSQL Crosstab Query
Better table definition
But better ALTER the data type in your table to text like @dezso suggested. Or, if you want to keep the length limit, add a CHECK constraint or use varchar(n). Never use char(n).
ALTER TABLE activities_in_localities_asc
   ALTER COLUMN ageband TYPE varchar(12)
 , ALTER COLUMN postcode_nospace_ TYPE varchar(8);

 ALTER TABLE gazetteers_and_addresses.unit_postcode
   ALTER COLUMN pc_area TYPE varchar(10);

Then you don't need to cast original column values any more:
SELECT * FROM crosstab(
   'SELECT postcode_nospace_, ageband, count(ageband)
    ...

Ideally, though, ageband should be an enum or (my preference) an ID referencing a lookup table, not plain, error-prone text ... key word: normalization.
Add total count
Building on your table, but with text or varchar() columns.
Wrap your original query into a CTE and call the the result twice in a UNION query - the 2nd call adds totals per postcode:
SELECT * FROM crosstab(
  $$WITH cte AS (
      SELECT postcode_nospace_, ageband, count(ageband) AS ct
      FROM   adult_social_care.activities_in_localities_asc
      GROUP  BY 1, 2
      )
   TABLE  cte  -- original results
   UNION ALL   -- add total per postcode
   SELECT postcode_nospace_, 'total' AS ageband, sum(ct) AS ct
   FROM   cte
   GROUP  BY 1
   ORDER  BY 1$$  -- dollar-quotes to include single quotes easily

   ,$$VALUES ('18-24'::text), ('25-34'), ('35-44'), ('45-54'), ('55-64')
           , ('65-74'), ('75-84'), ('85-94'), ('95 AND OVER'), ('total')$$
   )
AS t("postcode" text
   , "18-24" bigint, "25-34" bigint,"35-44" bigint, "45-54" bigint, "55-64" bigint
   , "65-74" bigint, "75-84" bigint, "85-94" bigint, "95 AND OVER" bigint, "total" bigint);
About the TABLE command:

*

*Is there a shortcut for SELECT * FROM in psql?
Related CTE examples:

*

*Combine results of two queries, where the second relies on the first

*Get n grouped categories and sum others into one


text:
Q: How to find a specific element inside the arrays which is surrounded by an object? This is my contents of a document in the MongoDB. It has an object timestamps and a lot of arrays.
{
   "timestamps":{
      "1200":[
         "390.288",
         "390.818",
         "So"
      ],
      "1175":[
         "381.778",
         "382.248",
         "so"
      ],
      "1183":[
         "383.668",
         "383.928",
         "a"
      ],
      "1144":[
         "372.588",
         "372.718",
         "up"
      ],
      "1162":[
         "377.638",
         "377.928",
         "rial"
      ],
      "1218":[
         "395.798",
         "395.868",
         "me"
      ],
      "1145":[
         "372.718",
         "373.188",
         "So"
      ]
   }
}

How can I find the word So which is in 1200th index and their timestamps which is in the 0th and the 1st index of that array?

A: Since your object keys are unknown you should start with $objectToArray operator which can transform timestamps into an array of keys and values like below:
{
    "k" : "1144",
    "v" : [ "372.588", "372.718", "up"]
},
{
    "k" : "1145",
    "v" : [ "372.718", "373.188", "So"]
},
...

Then you can use $filter to get only those documents where v contains your input phrase. Entire aggregation could look like this:
var input = "me";
db.col.aggregate([
    {
        $project: {
            foundElements: {
                $filter: {
                    input: { $objectToArray: "$timestamps" },
                    as: "ts",
                    cond: { $ne: [ { $indexOfArray: [ "$$ts.v", input ] }, -1 ] }
                }
            }
        }
    },
    {
        $project: {
            foundElements: {
                $map: {
                    input: "$foundElements",
                    as: "element",
                    in: { $slice: [ "$$element.v", 2 ] }
                }
            }
        }
    }
])

$indexOfArray returns -1 if array doesn't contain specified phrase. To reshape your results you can use $map with $slice which will take first two elements from your array (0th and 1st).
Output:
{ "_id" : ..., "foundElements" : [ [ "395.798", "395.868" ] ] }


text:
Q: Every open set $ G \subset \mathbb{R}^n$ can be approximated by finite union of non-degenerate compact intervals contained in $G$? For every open set $ G \subset \mathbb{R}^n$ and $ \epsilon > 0 $ there exist a finite collection of compact intervals $\{ I_j \quad|\quad j=1,2,...m\}$ in $ \mathbb{R}^n $ such that $\cup^{j=1}_{m}I_j \subset G $ and  $ m(G\backslash \cup^{j=1}_{m}I_j)< \epsilon $ where m denotes lebesgue measure.
NOTE : compact interval in $\mathbb{R}^n$ is $[a_1,b_1]\times[a_2,b_2]\times...\times[a_n, b_n]$ where $[a_i,b_i] $ are real closed intervals for each i.
EDIT: $m(G)$ is finite. sorry, I forget to write.

A: This follows from the fact that every open set in $\mathbb{R}^n$ is a countable disjoint union of compact intervals. Indeed, if $G = \cup_{k=1}^\infty I_k$, then since $\sum_k m(I_k) = m(G) < \infty$, we may take $K$ so that $\sum_{k > K} m(I_k) < \epsilon$. Then $\cup_{k=1}^K I_k$ does the trick.
See page 7 for the proof of the first fact I stated
http://assets.press.princeton.edu/chapters/s8008.pdf

A: This is false. For example take $G= \mathbb R^n$.


text:
Q: Grouping a row into multiple groups with pandas I have a set of sentences, and I want to group them such all the rows in a group should share one particular word. However a sentence can belong to many groups because it has many words in it.
So in the example below, there should be a groups like this:

*

*A 'temperature' group that includes all the rows (0, 1, 2, 3 and 4)

*A 'freezes' group which includes rows 2 and 4

*A 'the' group that includes rows 0, 1, 2, and 3

*A 'metal' group that only contains row 0.

*Groups for every other word in the dataset

import pandas as pd

# An example data set
df = pd.DataFrame({"sentences": [
    "two long pieces of metal fixed together, each of which bends a different amount when they are both heated to the same temperature",
    "the temperature at which a liquid boils",
    "a system for measuring temperature that is part of the metric system, in which water freezes at 0 degrees and boils at 100 degrees",
    "a unit for measuring temperature. Measurements are often expressed as a number followed by the symbol °",
    "a system for measuring temperature in which water freezes at 32º and boils at 212º"
]})

# Create a new series which is a list of words in each "sentences" column
df['words'] = df['sentences'].apply(lambda sentence: sentence.split(" "))

# Try to group by this new column
df.groupby('words').count()

# TypeError: unhashable type: 'list'

However my code throws an error as shown. (see below)
Since my task is a bit complicated I know it probably involves more than just calling groupby(). Can someone help me to make word groups with pandas?
edit After solving the error by returning tuple(sentence.split()) (thanks ethan-furman), I try printing the result, but it doesn't seem to have done anything. I think it probably just put each row in a group:
print(df.groupby('words').count())

# sentences    5
# dtype: int64

A: You can use a set collection so that each word is unique.  First, we need to get a list of all words in all of the sentences.  To do this, we initialize words to an empty set, then use a list comprehension to add each lower case word in each sentence (after splitting the sentence).
Next, we use a dictionary comprehension to build a dictionary keyed off of each word in the word set.  The value is the dataframe containing each sentence that contains that word.  These were obtained by grouping on a function, groupby(df.sentences.str.contains(word, case=False)), and then getting each group where this condition is True.
words = set()
_ = [words.add(word.lower()) for sentence in df.sentences for word in sentence.split()]

word_dict = {word: df.groupby(df.sentences.str.contains(word, case=False)).get_group(True)
             for word in words}

>>> word_dict['temperature']
                                           sentences
0  two long pieces of metal fixed together, each ...
1            the temperature at which a liquid boils
2  a system for measuring temperature that is par...
3  a unit for measuring temperature. Measurements...
4  a system for measuring temperature in which wa...

>>> word_dict['freezes']
                                           sentences
2  a system for measuring temperature that is par...
4  a system for measuring temperature in which wa...

>>> words
{'0',
 '100',
 '212\xc2\xba',
 '32\xc2\xba',
 'a',
 'amount',
 'and',
 'are',
 'as',
 'at',
 'bends',
 ...

To get a dictionary of index values for each word:
>>> {word: word_dict[word].index.tolist() for word in word_dict}
{'0': [2],
 '100': [2],
 '212\xc2\xba': [4],
 '32\xc2\xba': [4],
 'a': [0, 1, 2, 3, 4],
 'amount': [0],
 'and': [2, 4],
 'are': [0, 3],
 'as': [2, 3, 4],
 'at': [0, 1, 2, 3, 4],
 'bends': [0],
 'boils': [1, 2, 4],
 'both': [0],
 'by': [3],
 'degrees': [2],
 'different': [0],
 'each': [0],
 'expressed': [3],
 'fixed': [0],
 'followed': [3],
 'for': [2, 3, 4],
 'freezes': [2, 4],
 ...

Or a matrix of boolean indicators.
>>> [df.sentences.str.contains(word, case='lower').tolist() for word in word_dict]
[[False, False, True, False, True],
 [False, False, False, True, False],
 [True, False, False, False, False],
 [False, False, True, False, False],
 ...

A: My current solution uses pandas' MultiIndex feature. I'm sure it can be improved with some more efficient use of numpy, but I believe this will perform significantly better than the other python-only answer:
import pandas as pd
import numpy as np

# An example data set
df = pd.DataFrame({"sentences": [
    "two long pieces of metal fixed together, each of which bends a different amount when they are both heated to the same temperature",
    "the temperature at which a liquid boils",
    "a system for measuring temperature that is part of the metric system, in which water freezes at 0 degrees and boils at 100 degrees",
    "a unit for measuring temperature. Measurements are often expressed as a number followed by the symbol °",
    "a system for measuring temperature in which water freezes at 32º and boils at 212º"
]})

# Create a new series which is a list of words in each "sentences" column
df['words'] = df['sentences'].apply(lambda sentence: sentence.split(" "))

# This is all the words in the dataset. Each word will be its own index (level of the MultiIndex)
names = np.unique(df['words'].sum())

# Create an array of tuples, one tuple for each row of data
# Each tuple contains True if the row has that word in it, and False if it does not
values = df['words'].map(
    lambda words: np.vectorize(
        lambda word:
            True if word in words else False)(names)
)

# Make a multindex
index = pd.MultiIndex.from_tuples(values, names=names)

# Add the MultiIndex without creating a new data frame
df.set_index(index, inplace=True)

# Find all the rows that have the word 'temperature'
xs = df.xs(True, level='temperature')

print(xs.to_string(index=False))

A: To fix your TypeError you can change your lambda to
lambda sentence: tuple(sentence.split())

which will return a tuple instead of a list (and tuples and hashable).


text:
Q: Search inside an array and return multiple results I have made this simple search snippet. I made it to search throughout my array(elements array) and if the input value is exactly equal to one of the element's names and that element will return.
So here if we search 'apple' in the input field the below result will return
{
color: "red",
name: "apple"
}
My question is: Without returning according to the exact value of the input, can we return a value like the input value. For example, instead of typing 'apple' word when we type the starting letters of the 'apple' word like 'ap' I'm expecting to return apple object and apex object which includes 'ap' (I want to return all the objects which contain the name like 'ap' from the array) like a normal search function does. Thank you if somebody likes to help me.Below is my code.

//array
const elements = [{name: 'apple',color: 'red'},{name: 'apex', color: 'white'},{name: 'bat', color: 'black'}];

//find function
const searchElement = (elementsArray,keyword) => {
   const returnedElement = elementsArray.find((element,index) => {
      return element.name.toLowerCase() === keyword.toLowerCase();
   });

   return returnedElement;
}

//keyup event
document.getElementById('myInput').addEventListener('keyup', () => {
  const keyword = document.getElementById('myInput').value;
  const result = searchElement(elements,keyword);
  console.log(result);
});
<input type="text" placeholder="Search" id="myInput">

A: Based on your question, I think my solution can help you
const elements = [{name: 'apple',color: 'red'},{name: 'apex', color: 'white'},{name: 'bat', color: 'black'}];

//find function
const searchElement = (elementsArray,keyword) => {
   var result = [];

   elementsArray.forEach((element,index) => {
      if (element.name.toLowerCase().includes(keyword.toLowerCase())) {
            result.push(element);
      }
   });

   return result;
}

//keyup event
document.getElementById('myInput').addEventListener('keyup', () => {
  const keyword = document.getElementById('myInput').value;
  const result = searchElement(elements,keyword);
  console.log(result);
});

A: I think this is what you want. Use filter instead of it.

//array
const elements = [
    { name: "apple", color: "red" },
    { name: "apex", color: "white" },
    { name: "bat", color: "black" }
];

//find function
const searchElement = (elementsArray, keyword) => {
    const returnedElement = elementsArray.filter((element, index) => {
        return element.name.toLowerCase().includes(keyword.toLowerCase());
    });

    return returnedElement;
};

//keyup event
document.getElementById("myInput").addEventListener("input", () => {
    const keyword = document.getElementById("myInput").value;
    const result = searchElement(elements, keyword);
    result.forEach((item) => console.log(item.name));
});
<input type="text" placeholder="Search" id="myInput">

A: You can do:

const elements = [{name: 'apple',color: 'red'},{name: 'apex', color: 'white'},{name: 'bat', color: 'black'}]
const myInput = document.getElementById('myInput')

myInput.addEventListener('keyup', () => {
  const keyword = myInput.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  const filterFn = ({ name }) => name.match(new RegExp(keyword, 'i'))
  const result = elements.filter(filterFn)

  console.clear()
  console.log(result)
})
<input type="text" placeholder="Search" id="myInput">

A: You could use a RegExp expression:
const searchElement = (elementsArray, keyword) => {
    const returnedElement = elementsArray.find((element) => {
        return element.name.toLowerCase().match(new RegExp('.*' + keyword.toLowerCase() + '.*','i')) !== null;
    });
    return returnedElement;
}

If you use the RegExp expression RegExp('.*' + keyword.toLowerCase() +'.*', 'i'), pp will match 'apple'. If you use RegExp('^' + keyword.toLowerCase() + '.*', 'i') pp will not match apple but app will.

A: *

*Use the "input" EventName (instead of "keyup") - since an input value can change not only on some key event, but also when copy/pasting values into it, etc. The "input" event will handle all those cases.

*Inside the handler function, don't query again the DOM for your input element, simply use the Event.currentTarget like: evt.currentTarget.value

*Create a reusable function namely filter() that accepts four arguments: the Array to search, the Property name (key) to lookup, the String to search for, and an optional Object of options for case sensitive and match criteria (any position, full match, start or end of string)

*Use RegExp.prototype.test() inside of your Array.prototype.filter()

/**
 * @param {string} str String to escape
 * @returns {string} String with escaped regex special characters
 */
const regEscape = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

/**
 * @param {array} arr Array (of objects) to filter
 * @param {string} key Property name
 * @param {string} val Value to match
 * @param {object} opt Options for case sensitive and match criteria
 * @returns {array} Filtered array of objects
 */
const filter = (arr, prop, val, opt = {sensitive: false, match: "any"}) => {
  val = regEscape(val);
  const criteria = {
    any: val,
    start: `(?<=^| )${val}`,
    end: `${val}(?=$| )`,
    full: `(?<=^| )${val}(?=$| )`,
  }[opt.match];
  const reg = new RegExp(criteria, opt.sensitive ? "g" : "ig");
  return arr.filter(ob => reg.test(ob[prop]));
};

// Task: Search objects by "name" property

// Data:
const data = [
  {name: "apple", color: "red"},
  {name: "apexx", color: "white"},
  {name: "batle", color: "black"},
];

// Search input handler:
document.querySelector("#myInput").addEventListener("input", (evt) => {
  const results = filter(data, "name", evt.currentTarget.value, { match: "start" });
  console.clear()
  console.log(results)
});
<input id="myInput" type="text" placeholder="Search">

as you can see above the option { match: "start" } is used - which will make sure that the match should start at the beginning of string.
If you want to search from "any" position, use { match: "any" } or remove the options, since "any" is by default.
To search case-sensitive use: { match: "start", sensitive: true }
PS: Some of the used logic is taken from: Hilite


text:
Q: Build vNext CodedUI Item Deployment - items specified in .testsettings not being copied I have a CodedUI test suite. I'm attempting to use a B-D-T workflow in TFS 2015 R2 to deploy the test .dlls to a machine group and execute them.
The tests rely on a couple files - an html start page and an XML file.
First, I attempted to have the tests just run from the bin folder OR where they're deployed onto the machines in the machine group. No suggestions I found on SO or on the first 3 pages of google worked. Whenever I ran a test locally it would copy the test dlls to the TestResults folder and execute from there.
Then, I attempted to use a .testsettings file to deploy the files with the .dlls into the TestResults folder. I still truly don't understand why this is the best or only solution - if I can just execute from the Bin please let me know how, but it does work - locally.
Now in TFS 2015 when I deploy my testing software to the test agent(Member of the machine group), I can see my supporting files exactly where they should be in the test drop location. Then, the test starts. A temp folder is created in a byzantine region of AppData, where only the .dlls and config are copied - not the files specified in the .testsettings file! The testsettings file is specified in the "Run Functional Tests" task, which I reached by browsing to the correct file in source control.
I can provide any information you require. This should be so simple but it has been an enormous headache.

A: In the configuration you need to setup where you copied the files to on the remote machine using a "Windows Machine File Copy" task executed by the agent. You need to make sure all the files needed to run are copied to the server.

Then in your .testsettings file specify which of the files you copied over you want to deploy to the temporary test context directory. Only files already copied to the test agent can be selected here.
The File copy task would look something like:


text:
Q: specifying a list (vector) of arbitrary length When trying to do symbolic calculations in mathematica involving a space of dimension n, which is arbitrary but fixed, I'd often like to work with vectors that have arbitrary but fixed length n. So I'd like to have a vector defined like vec = Array[v,n], which of course does only work if n has been initialized with an integer value before. I'd then like to apply some differential operators like let's say D[vec,v[2]]. Does anybody know an elegant way to do that (maybe using the new Inactive construct in Mathematica 10)?
p.s.: Interestingly enough mathematica supports sums of arbitrary length, which for example enables the following kind of symbolic computation:
x /: D[x[i_], x[j_], NonConstants -> {x}] := KroneckerDelta[i, j];
D[Sum[x[i], {i, 1, n}], x[2], NonConstants -> x];

which yields the correct result:

Piecewise[{{1, n > 1}}, 0]


text:
Q: How to make button that will go to a different screen in Objective C without storyboard? I have this so far:
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(50, 200, 200, 50);
        [btn setTitle:@"Button 1" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(someAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];

Now I have someAction.. where do I put it and how do I do this? I'm sorry.. I hate asking questions.. but I looked over this everywhere and spent hours..

A: If you're using storyboards, and created a push segue, then the code looks like this
- (void)someAction
{
    [self performSegueWithIdentifier:@"SomeSegueName" sender:nil];
}

If you're using storyboards, but don't have a segue, then the code looks like this
- (void)someAction
{
    MyViewController *vc;

    vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SomeVC"];
    [self.navigationController pushViewController:vc animated:YES];
}

If you aren't using storyboards at all, then I expect your head will eventually start hurting from banging it against the wall.


text:
Q: Add days to element inside array in PySpark Dataframe I have a PySpark dataframe with three columns. The first two column have arrays as their elements, while the last column gives the length of arrays of the last column. Following is the PySpark dataframe:
+---------------------+---------------------+-----+
|                   c1|                   c2|lenc2|
+---------------------+---------------------+-----+
|[2017-02-14 00:00:00]|[2017-02-24 00:00:00]|    1|
|[2017-01-16 00:00:00]|                   []|    0|
+---------------------+---------------------+-----+

The arrays contain timestamp dtypes. The column lenc2 denotes length of array in column c1. For all rows where lenc2==0, the column c1 has only one (timestamp) element.
For all rows where lenc2==0, I want to take the timestamp from the array in column c1 , add 5 days to it and put it inside the array in  row c2. How can I do this?
This is an example of the expected output:
+---------------------+---------------------+-----+
|                   c1|                   c2|lenc2|
+---------------------+---------------------+-----+
|[2017-02-14 00:00:00]|[2017-02-24 00:00:00]|    1|
|[2017-01-16 00:00:00]|[2017-01-21 00:00:00]|    0|
+---------------------+---------------------+-----+

Below is what I have tried till now:
df2 = df1.withColumn(
    "c2",
    F.when(F.col("lenc2") == 0, F.array_union(F.col("c1"), F.col("c2"))).otherwise(
        F.col("c2")
    ),
)

A: You've got the when(…).otherwise(…) already correct.
Given that you don't seem to be interested in subsecond accuracy, you can convert the timestamps to seconds since the Unix epoch and add for 5 days worth of seconds, then convert back to a timestamp:
from datetime import datetime

from pyspark.sql.functions import *

one_sec_before_leap_time = datetime(2016, 12, 31, 23, 59, 59)
seconds_in_a_day = 24 * 3600

df = spark.createDataFrame([
    ([one_sec_before_leap_time], [datetime.now()], 1),
    ([one_sec_before_leap_time], [], 0),
],
    schema=("c1", "c2", "lenc2"))

def add_seconds_to_timestamp(ts_col, seconds_col):
    return to_timestamp(unix_timestamp(ts_col) + seconds_col)

df2 = df.withColumn("c2",
                    when(col("lenc2") == 0,
                         array(
                             add_seconds_to_timestamp(
                                 col("c1").getItem(0),
                                 lit(5 * seconds_in_a_day))))
                    .otherwise(col("c2")))
df2.show(truncate=False)
# +---------------------+----------------------------+-----+
# |c1                   |c2                          |lenc2|
# +---------------------+----------------------------+-----+
# |[2016-12-31 23:59:59]|[2019-12-07 16:58:32.864176]|1    |
# |[2016-12-31 23:59:59]|[2017-01-05 23:59:59]       |0    |
# +---------------------+----------------------------+-----+

Be aware, this will most likely give you odd results when you have to take daylight savings into account. It's better to express everything in UTC and only at the inputs and outputs do a proper conversion from UTC timestamps to times expressed in local timezones. Similar to the Unicode sandwich, basically.
Additionally, this does not take into account leap seconds, as illustrated above (there's another second in 2016, making 2016-12-31T12:59:60Z technically valid). However, leap seconds are notoriously hard, because there's no exact formula for it (yet - who knows, maybe one day we can model geological and climatic events?).


text:
Q: How to develop a django->pylons file upload tool? I have a Pylons application that provides web services to a Django-based front end. I need to be able to provide file upload and download to the users of the application.
Basically, they upload a file in the front end (which might be literally anything, and often quite large). The file is transmitted from client => django web server => pylons app server => internal file server.
The internal file server does not provide an API; the only way to put the file on it is by scp. So, no streaming is relevant on the pylons => fserv step.  Moreover, the fserv cannot be accessed from the network tier that the django app lives on.
In the reverse process, the fserv provides an HTTP access method for its files, still inaccessible to the web server, so I need to connect a stream from fserv => pylons => django.
What does the Pylons side of this process look like? How can I minimize the latency of these file operations? I know I'm stuck on the write operation, given that I must send the whole file after receiving it.
Also, what does the Django side of this process look like? How do I upload a file to a streaming upload service, and how do I download the same?
For the sake of minimizing argument, please assume that I am unable to change the main components of my system, and that firewalls and admin policy prevent my use of shared network resources to move files around.

A: You're not neccessarily stuck with scp'ing the uploaded file all at once. scp can take data from standard input, and in python you have fine control over input, output and error pipes of subprocesses.
For the Pylons part, I guess, the question could read, "How to do streaming HTTP uploads/downloads with Pylons"?
Streaming downloads, where Pylons controller serves large file (or acts as a proxy in front of fileserver), are easy. See "Streaming Content to Browser" on Pylons Wiki about this (the link is to google cache because wiki seems to be down ATM).
Streaming uploads in Pylons is more tricky, the main problem again being buffers in middlewares. There's an article about that as well on Pylons Wiki: "Hacking Pylons for handling large file upload" (google cache again).


text:
Q: Write datas to csv file I am very new to python and I have csv problem.
I have a code to extract data from Futbin website but I don't find how to do to export these datas to a csv file.
The datas shown in Python are exactly what I need so the last step for me is to exctract them.
Here is the code :
import requests
import csv
from datetime import datetime

player_ids = {
  'Maguire OTW': 50534911,
  'Pulisic OTW' : 50559444,

}

for (name,id) in player_ids.items():
    r = requests.get('https://www.futbin.com/20/playerGraph?type=yesterday&year=20&player={0}'.format(id))
    data = r.json()

    print()
    print(name)
    #Change ps to xbox or pc to get other prices
    for price in data['ps']:
        #There is extra zeroes in response.
        date = datetime.utcfromtimestamp(price[0] / 1000).strftime('%Y-%m-%d')
        price = price[1]
        print(date,price)

Thanks a lot for your help

Copy Comment: When I add this at the end of the code :
with open('yesterdayok.csv', 'w') as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(date)

it creates the csv file but inside there's only 1 date, I need all the datas generated by the code.


text:
Q: Cordova Build.json password security I've had issues getting cordova to prompt me for the password to the storePassword and password fields in the build.json file when building and signing my apks. The solution I've turned to is to enter them in the build.json file.
My question: is there any security issue when manually entering passwords into build.json (such as the passwords somehow being included in the actual signed apk, etc.)?
I have build.json in the root of my cordova project so it is automatically detected and all I have to do is:
cordova build android --release

...which is why I've gone this route (it just works). I know this might seem like a silly question, but the Cordova docs state:

"For release signing, passwords can be excluded and the build system
  will issue a prompt asking for the password."

...which implies that for some reason passwords shouldn't be entered into build.json for release.

A: I believe the main reason is to avoid storing a password in a plain text in build.json and instead type it in console:
{
    "android": {
        "debug": {
            "keystore": "../android.keystore",
            "storePassword": "android",
            "alias": "mykey1",
            "password" : "password",
            "keystoreType": ""
        },
        "release": {
            "keystore": "../android.keystore",
            "storePassword": "",
            "alias": "mykey2",
            "password" : "password",
            "keystoreType": ""
        }
    }
}

or take from an environment variable:
cordova run android --release -- --keystore=../my-release-key.keystore --storePassword=%STORE_PASS% --alias=mykey2 --password=password.

A:
the passwords somehow being included in the actual signed apk

The build.json file won't get included in the final apk that gets built. You can verify this by unzipping the apk to cross-check.
Hope that helps.


text:
Q: mirror on-prem nexus repository to s3 We have a local on-prem nexus OSS repository for all of our maven builds.
In order to take advantage of some of the AWS offerings we would like to replicate the on-prem nexus repository over to s3.
The idea is that for example a build uploads a snapshot jar to nexus and then nexus subsequently mirrors the jar to s3 so that the snapshot jar also becomes available for services in AWS.
Is it possible to configure nexus OSS to replicate to s3 while also keeping the local nexus repositories and if so how?

A: *

*One way to do that would be having an ec2-s3 connection. The ec2 could host your Nexus OSS v3, which provides the capability to use s3 as the blob store. But using this you won't be able to view jar directly in s3, they will only be available in nexus to be viewed.

*Assuming you achieved this above task, once your jar is present in Nexus, you can then download and push the jar to s3, where it can be directly visible.


text:
Q: Heap overrun error is resolved by removing a heap allocated variable? While investigating a glibc crash I get this valgrind error:
Invalid write of size 8
   at 0x43A3D2: DataAudit::DataAudit(DataAuditModel*, QWidget*) (DataAudit.cpp:15)
   by 0x42D318: MainWindow::createNewDataAudit(DataAuditModel*) (MainWindow.cpp:191)
   by 0x48CA09: MainWindow::qt_static_metacall(QObject*, QMetaObject::Call, int, void**) (moc_MainWindow.cpp:65)

Invalid write of size 8 seems to indicate a heap block overrun.
Here are the two problem classes, pared down for conciseness:
class IAWidgetModelOwner : public IAWidget
{
public:
    explicit IAWidgetModelOwner(IAWidgetModel *model, QWidget *parent = 0) :
        IAWidget(model, parent),
        pointer1(MAIN_WINDOW),
        pointer2(MAIN_WINDOW) // See note below
        { }

private:
    MainWindow *pointer1;
    MainWindow *pointer2;  // See note below
};

class DataAudit : public IAWidgetModelOwner, public Ui::DataAudit
{
public:
    explicit DataAudit(DataAuditModel *dataAuditModel, QWidget *parent = 0) :
    IAWidgetModelOwner(dataAuditModel, parent),
    _dataAuditModel(dataAuditModel) // DataAudit.cpp:15
    { ... }
    ...

private:
    QList<RawLog*> _rawLogs;
    DataAuditModel *_dataAuditModel;
};

The puzzling thing, is that the valgrind error does not appear if I remove pointer2 from IAWidgetModelOwner by commenting out the indicated lines above. Removing all references to _dataAuditModel also resolves the error.
Since I am not actually calling new or malloc in this class, I don't understand how the automatic heap allocation could cause such an error. I feel like I'm at a dead end in investigating this bug.
What am I doing wrong, or where is a good place to look next?
Note: MAIN_WINDOW is a globally defined MainWindow pointer pulled in from Globals.h

A: Somehow,MainWindow::createNewDataAudit() is not allocating an object large enough for your DataAudit object. Focus your debugging efforts there.
Since not enough memory is allocated, initializing the pointer member _dataAuditModel causes the overrun. When you remove the member pointer2 from the base class, you are shrinking the size of the DataAudit object to fit in the memory allotted to it by MainWindow::createNewDataAudit().

A: Surprise surprise, the actual error was in code that I chose not to include:
class IAWidgetModelOwner : public IAWidget
{
    Q_OBJECT
public:

I used the Q_OBJECT macro, but it had no signal or slot declarations. Either of the following solved my problem:

*

*Remove Q_OBJECT

*Define a slot public slot: mySlot() {}
In reality, I thought I had declared one of the member functions as a slot.


text:
Q: Main site url removed from google despite re-submitting it I have a site www.megalim.co.il,
recently due to a version upgrade, I discovered that i have a robots.txt file that disallowed all Search engines.. my google ranking dropped , and I couldn't find the site's main page anymore
I changed the robots.txt file to one that allows all, and now the web master toolkit doesn't
write me that the site is blocked from google.
I did this about 5 days ago, I've also fetched as google
and submitted www.megalim.co.il to index with all related pages
but still, when i search this: "site:www.megalim.co.il"
i get a bunch of results from my site , but not the main page!
what else should I look for?
thanks!
Igal

A: You don't see your main page because of your old robots.txt. 5 days is nothing for Google bots to re-index all your website.
Just wait a little and you will see your website fully indexed in Google results.

A: Issue sorted out..
embarassing...
 apparently we (inexplicably) had a nofollow, noindex meta tag..
after a day we start reappearing in google
thanks :)


text:
Q: How to make distance between dot and text in a unordered list smaller? I am using list style image to show dots for an unordered list. They are appearing a little far from text and i want to make the distance between the list text and dot a little less. I have tried padding and margin but nothing seems to work. Can somebody please suggest something.

A: You could try a negative text-indent on the <li>:
li {
    text-indent: -5px;
}

For example: http://jsfiddle.net/ambiguous/QgNxw/
Browser support might be a bit dodgy (e.g. Opera and WebKit don't render that fiddle the same way). You could also try using the :before pseudo-element to add your own bullet:
.closer {
    list-style-type: none;
}
.closer:before {
    content: '•';
    margin-right: 3px;
}

For example: http://jsfiddle.net/ambiguous/eXxzH/
But then you'll have trouble with browsers that don't understand :before; but everyone but IE7 and older understand :before so that might not be an issue.
If CSS3 is okay, you might be able to do something with the ::marker pseudo-element.
There isn't that much fine grained control over how the bullets for a list item are rendered.

A: Try this
HTML:

*

*hi wolrd

*123

*pay

*see you

css:
ul {
margin:0px;
padding:0px;
}
ul li{ padding:0 0 0 10px; background:url(...) 0px 6px no-repeat; list-style-type:none;}

A: You could put divs inside your li elements and set their left margins to something negative:
li > div {
    margin-left:-4px;
}

A: I know this post is really old but you can use list-style-position: inside and then add whatever padding or margin you need on the list itself.


text:
Q: Magento solr search - how to add custom field to product search index I have enterprise magento 1.10 and I need to add custom field to solr index in order to to have better search results. This custom field should contain category names for indexed product.
I need to know which part of magento I need to amend. I modified method Enterprise_Search_Model_Resource_Index::_getCatalogCategoryData which actualy produces some category related data but my new field doesnt appear in message to sorl.
Have I miss something?
Also I have some notes here, maybe it would someone help http://docs.nostresscommerce.com:8090/pages/viewpage.action?pageId=2490371
My output of rewrited Enterprise_Search_Model_Resource_Index::_getCatalogCategoryData, and I need category_name_level_* in solr.
  [result] => Array
        (
            [12227] => Array
                (
                    [#categories] => Array
                        (
                            [0] => 2
                            [3] => 3235
                            [7] => 2765
                            [10] => 6672
                        )

                    [#show_in_categories] => Array
                        (
                            [1] => 6671
                            [2] => 6670
                            [4] => 3224
                            [5] => 3199
                            [6] => 3191
                            [8] => 2761
                            [9] => 2760
                        )

                    [#position_category_2] => 1
                    [#position_category_6671] => 120000
                    [#position_category_6670] => 120000
                    [#position_category_3235] => 0
                    [#position_category_3224] => 150000
                    [#position_category_3199] => 150000
                    [#position_category_3191] => 120000
                    [#position_category_2765] => 1
                    [#position_category_2761] => 250001
                    [#position_category_2760] => 250001
                    [#position_category_6672] => 0
                    [#visibility] => 4
                    [#category_name_level_1] => Array
                        (
                            [0] => BCC Root Category
                        )

                    [#category_name_level_4] => Array
                        (
                            [0] => Huishouden
                            [1] => Top wasmachines
                            [2] => Accessoires wasmachine
                        )

                    [#category_name_level_3] => Array
                        (
                            [0] => Beste Koop Shop
                            [1] => Top
                            [2] => Wasmachine
                        )

                    [#category_name_level_2] => Array
                        (
                            [0] => Acties
                            [1] => Speciale informatie pagina's
                            [2] => Huishouden
                        )

                    [#category_name_level_5] => Array
                        (
                            [0] => Wasmachines
                        )

                )

        )

Thanks a lot,
Jaro.
I found a solution
class Xyz_Solrsearch_Model_Resource_Engine extends Enterprise_Search_Model_Resource_Engine {
    public function __construct()
    {
        $this->_advancedDynamicIndexFields[] = '#category_name_level_';
        parent::__construct();
    }
}


text:
Q: Syntax error:  link not working by clicking, only opens by right click + "open link in new tab" command When I click the 'Download Full Menu' link in this page (http://www.brazenbbq.com/menus/restaurant/) it won't open unless I right click and 'Open link in a new tab'. I used Chrome and Firefox element inspector and I get the below Jquery error, but I'm not sure how can I fix it since I'm just a javascript newbie... Thank you for your help!

2jquery.js?ver=1.10.2:formatted:570

Uncaught Error: Syntax error, unrecognized expression: /wp-content/uploads/2013/11/Brazen_BBQ_Menu.pdf

fa.error @ jquery.js?ver=1.10.2:formatted:570

fa.tokenize @ jquery.js?ver=1.10.2:formatted:898

fa.select @ jquery.js?ver=1.10.2:formatted:1069

fa @ jquery.js?ver=1.10.2:formatted:339

find @ jquery.js?ver=1.10.2:formatted:1188

n.fn.init @ jquery.js?ver=1.10.2:formatted:1211

n @ jquery.js?ver=1.10.2:formatted:22

(anonymous function) @ VM266:43

dispatch @ jquery.js?ver=1.10.2:formatted:2128

r.handle @ jquery.js?ver=1.10.2:formatted:2007

A: in this line in the script ( animate scroll down to anchor script  ) you have
    $leftMenu(".fullMenuLeft a").on("click", function( e ) {

    e.preventDefault();

that's why your first link to pdf  doesn't work as you want. plus...in the continuation of the script you use the href of this ...which is the fullMenuleft a href to do something different than what you expect from pdf link to do
so change the above line to
  $leftMenu(".fullMenuLeft li:not(.menuTitle) a").on("click", function( e ) {

  e.preventDefault();

so you will select all the li a except the first one , the one with link to pdf

A: Try adding target="_blank" in your a tag
Some Link

A: You have javascript that is hooking into the nav, expecting a #Item to link to (scrolls down).
The link to the PDF is also in this nav, and so your jQuery plugin (or custom code) is trying to parse the "hash" (that it hasn't found) and then fails....

A: When clicking on 'download full menu' your sticky menu-navigation plugin tries to scroll to the according position on the page. But as this download-link is not an anchor, Javascript throws an error. Try to change your click-handler selector to something like this:
$leftMenu(".fullMenuLeft a[href~='#']").on("click", function( e ) { ... }

With the attribute selector and tilde you can filter your links by the hash in the href attribute.