text:
Q: Memory error in Networkx while drawing a graph I have a graph having
957267 Number of nodes ;
1860761 Number of edges and
Average degree is  3.8877
G=nx.from_edgelist(edge)
print(nx.info(G))
nx.draw_spring(G)
plt.draw()
plt.show()

till print function, every thing work, but after that when I draw graph, I got the error
All the values in edge list are integers.
I am getting memory error. Though I have 8 GB ram, and SSD hard disk Is there a way to deal with it or alternative of NetworkX
Traceback (most recent call last):
File "", line 1, in
    nx.draw_spring(G)
File "C:\ProgramData\Anaconda3\lib\site-packages\networkx\drawing\nx_pylab.py", line 965, in draw_spring
    draw(G, spring_layout(G), **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\networkx\drawing\layout.py", line 333, in fruchterman_reingold_layout
    pos = _fruchterman_reingold(A, k, pos_arr, fixed, iterations, dim)
File "C:\ProgramData\Anaconda3\lib\site-packages\networkx\drawing\layout.py", line 388, in _fruchterman_reingold
    distance = np.linalg.norm(delta, axis=-1)
File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\linalg\linalg.py", line 2198, in norm
    return sqrt(add.reduce(s, axis=axis, keepdims=keepdims))
MemoryError


text:
Q: Como fazer segurança de REST com Spring Security Pessoal estou tentando implementar segurança no meu servidor REST feito com SPRING 4. Estou trabalhando com anotações.
O basico do spring security para proteger páginas eu conheço.
Mas como proteger a requisições para o RESTful ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot show the list of items using JQuery Ajax Post call I have the following code in my ItemsController:
public PartialViewResult GetAllItems()
        {
            IEnumerable<ItemDetailsViewModel> listOfItemDetailsViewModels =
                    (from objItem in objVPPhamEntities.Items
                     select new ItemDetailsViewModel()
                     {
                         ImagePath=objItem.ImagePath,
                         CategoryId = objItem.CategoryId,
                         ItemId = objItem.ItemId,
                         ItemName = objItem.ItemName,
                         ItemPrice=objItem.ItemPrice,
                         Description=objItem.Description
                     }).ToList();
            return PartialView("_ItemDetailsPartial.cshtml", listOfItemDetailsViewModels);
        }

Then this in my javascript in index:
$(document).ready(function () {
        LoadItemDetails();
});
function LoadItemDetails() {
            $.ajax({
                async: true,
                data: 'GET',
                dataType: 'html',
                contentType: false,
                processData: false,
                url: '@Url.Action("GetAllItems","Items")',
                success: function (data) {
                    $("#divLoadItemDetails").html(data);
                },
                error: function () {
                    alert('Error.');
                }
            });
        }

This is my _ItemDetailsPartial
   @model IEnumerable<WebApplication3.ViewModel.ItemDetailsViewModel>

                Ảnh

                Mã hàng

                Mã sản phẩm

                Tên sản phẩm

                Giá

                Chi tiết

        @foreach (var item in Model)
        {

                    @item.CategoryId

                    @item.ItemId

                    @item.ItemName

                    @item.ItemPrice

                    @item.Description

        }

Then finally my html in index:

I want to show the list of Items from sql server
The add items function works well but I cannot show the Items list. It always says error when I run it instead of showing the Items list. Can anyone help me this???

A: You have to fix ajax. Try this
function LoadItemDetails() {
            $.ajax({
                type: 'GET',
                url: '/items/GetAllItems',
                success: function (data) {
                    $("#divLoadItemDetails").html(data);
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        }

And by the way  you are using a Get call, not  POST as it is written in your question header.Try this action header
[Route("~/Items/GetAllItems")]
public IActionResult GetAllItems()
{
.....your code here
}


text:
Q: Add class to child elements and start over for next container with the same parent class I want to assign classes to the elements inside each container.
I tried this script which gves the child elements its classes but it keeps going for each container, one, two, three, four and then for next container five, six, seven and eight.
$('.container span').each(function(i){
$(this).addClass('class'+i);
})

How do I do this and have the added classes starting over for the next parent container?
HTML:

     - assign class one
     - assign class two
     - assign class three
     - assign class four

     - assign class one
     - assign class two
     - assign class three
     - assign class four

A: You can do:
$('.container').each(function () {
    $(this).find('span').each(function (i) {
        $(this).addClass('class' + i);
    });
});

Iterate through every element with class .container and then find span inside it and add class..


text:
Q: Java : decode base64 string and create in-memory zip file and get files from that zip file java Java: decode base64 string and create in-memory zip file and get files from that zip file java
While am trying with
enter code here

try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(imageBytes))
OutputStream outputStream = new ByteArrayOutputStream()) {
======
====
}

while ((read = zipStream.read(bytesIn)) ==-1) {
baos.write(bytesIn, 0, read)
}

in while condition, it is giving an exception:
java.util.zip.ZipException: invalid distance too far back
Please help, thanks in advance


text:
Q: $_GET and $_POST is empty on rewriting urls I changed my server and in new server all query strings and forms values (with post methods) is empty.
I did rewrite all urls and handle the parameters in my application
this is my .htaccess codes:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

But in my new server $_POST and $_GET is empty.


text:
Q: $.each within $.each using JS multi-dimensional obj I have an object created for some footer content like so:
var $footerObj = {
    "one" : {
        "title" : "One",
        "links" : {
            "A" : {
                "title" : "One A",
                "url" : "#",
                "external" : true
            },
            "B" : {
                "title" : "One B",
                "url" : "#",
                "external" : true
            },
            "C" : {
                "title" : "One C",
                "url" : "#",
                "external" : false
            }
        }
    },
    "two" : {
        "title" : "Two",
        "links" : {
            "A" : {
                "title" : "Two A",
                "url" : "#",
                "external" : false
            },
            "B" : {
                "title" : "Two B",
                "url" : "#",
                "external" : false
            }
        }
    }
};

I am attempting to use jQuery's $.each to output this into some footer links.
$.each($footerObj, function(key, value) {

    $('.footer__links').append('

');

    var $footerList = $('.footer__list');

    $.each(value.links, function(subkey, subvalue) {

        $footerList.append('
' + subvalue.title + '
');

    });

});

This is what I have but this causes the data in "two" to be outputted twice. I believe it's value.links in the 2nd $.each which is wrong but I've been going mad trying all different variations with no luck - any help would be appreciated!
Thanks

A: When you append to a class it will append to every item that has that class, on the second object, there will be two with that calss, on the third there will be three, etc. The solution is to append to the one you created on that loop instead of every element with that class name. Do this in your outer each() loop instead:
var $footerList = $('

');
$('.footer__links').append($footerList);

So it looks like this:
$.each($footerObj, function(key, value) {

    var $footerList = $('

');

    $('.footer__links').append($footerList);

    $.each(value.links, function(subkey, subvalue) {

        $footerList.append('
' + subvalue.title + '
');

    });

});

A: In your second $.each you are calling $footerList to append your element.
This variable is set in the first $.each and retrieve all the element with the class footer__list. On the second iteration of your first $.each you will have two

Thus $('.footer__list'); will return 2 elements and you will append your
'
' + subvalue.title + '

to both of those elements, both of your


text:
Q: ASP.NET MVC authentication for iPhone application This is for an ASP.NET MVC application.  For browser based access on my normal controllers, I'm using standard forms authentication and auth cookies.
My question is how I do the same for an iPhone application.  I have a set of RESTful controllers that the iPhone application uses directly, but I'm not sure how to go about authentication...
I was thinking of having a special Login method that returns the auth cookie.  Then I can use the standard Authentication attribute on the ASP.NET MVC side, but I'm not sure how to handle this on the iPhone side?  Can I store this cookie and have it automatically sent with every request?
Perhaps there's a better approach altogether?

A: If it is RESTful you can use an NSURLConnection and send your server the appropriate HTTP headers the API requires.
http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html


text:
Q: Warning: require_once(Zend/Application.php): failed to open stream: No such file or directory in /var/w my index file is this
<?php
ini_set( "short_open_tag", 1 );
ini_set( "display_errors", 1 );
// Define path to application directory

defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

// Let 'er rip
$application->bootstrap()->run();

when i run that
Warning: require_once(Zend/Application.php): failed to open stream: No such file or directory in /var/www/Giftercity_backup/index.php on line 18 Fatal error: require_once(): Failed opening required 'Zend/Application.php' (include_path=':.:/usr/share/php:/usr/share/pear') in /var/www/Giftercity_backup/index.php on line 18

A: For Ubuntu.
If you install ZendFramework package. i.e. sudo apt-get install zend-framework
It will put zend library files in /usr/share/php/libzend-framework-php/Zend/ folder
you have to just copy and paste that Zend/ folder into /user/share/php/
Run the following command in terminal.
cd /usr/share/php
sudo cp -R libzend-framework-php/Zend/ Zend

A: Put your index file in "public" directory.
Or if you want or cannot include files from parent directory you need to change this line:
set_include_path(implode(PATH_SEPARATOR, array(
  realpath(APPLICATION_PATH . '/../library'),
  get_include_path(),
)));

To
set_include_path(implode(PATH_SEPARATOR, array(
  realpath(APPLICATION_PATH . '/library'), // Here we have change
  get_include_path(),
)));

Of course I assume that you have already putted your Zend Files into library/Zend
You also need to remember to put .htaccess file with "deny from all" to your application, library, and any other directory you don't want users to get access to.
Btw.
This method of including library is quite old and not recommended.

A: If your index.php file is located in /var/www/Giftercity_backup/index.php (according to the error output) then according to your code the library location should be in /var/www/library and application in /var/www/application which sounds wrong.
index.php should be in a public folder such as /var/www/Giftercity_backup/public, /var/www/Giftercity_backup/htdocs or similar and your VirtualHost DocumentRoot should point to that folder.
Additionally, your set_include_path didn't register library  (include_path=':.:/usr/share/php:/usr/share/pear').


text:
Q: How to sort value in a nested list? I have a list looks like this:
[[{'city': 'Denver',
   'name': 'Sushi Kashiba',
   'estimated_cost': 180,
   'user_rating': {'average_rating': 4.9, 'votes': 4175},
   'id': 31},
  {'city': 'Denver',
   'name': 'Peninsula Grand Hotel',
   'estimated_cost': 120,
   'user_rating': {'average_rating': 4.9, 'votes': 644},
   'id': 32},
  {'city': 'Denver',
   'name': 'Plum by Bent Chair',
   'estimated_cost': 180,
   'user_rating': {'average_rating': 4.9, 'votes': 1657},
   'id': 36},
  {'city': 'Denver',
   'name': "R' ADDA",
   'estimated_cost': 120,
   'user_rating': {'average_rating': 4.9, 'votes': 4255},
   'id': 39},
  {'city': 'Denver',
   'name': 'Lord of the Drinks',
   'estimated_cost': 150,
   'user_rating': {'average_rating': 4.8, 'votes': 2086},
   'id': 34}],
 [{'city': 'Denver',
   'name': 'Hitch',
   'estimated_cost': 120,
   'user_rating': {'average_rating': 4.8, 'votes': 3277},
   'id': 311},
  {'city': 'Denver',
   'name': 'Hi Lounge',
   'estimated_cost': 120,
   'user_rating': {'average_rating': 4.7, 'votes': 1687},
   'id': 315},
  {'city': 'Denver',
   'name': 'Vedge',
   'estimated_cost': 10,
   'user_rating': {'average_rating': 4.7, 'votes': 3837},
   'id': 320},
  {'city': 'Denver',
   'name': 'Social',
   'estimated_cost': 140,
   'user_rating': {'average_rating': 4.6, 'votes': 7838},
   'id': 313},
  {'city': 'Denver',
   'name': 'BKC DIVE',
   'estimated_cost': 10,
   'user_rating': {'average_rating': 4.6, 'votes': 5687},
   'id': 316}],
 [{'city': 'Denver',
   'name': 'Yauatcha',
   'estimated_cost': 280,
   'user_rating': {'average_rating': 4.8, 'votes': 5359},
   'id': 330},
  {'city': 'Denver',
   'name': "Joey's Pizza",
   'estimated_cost': 80,
   'user_rating': {'average_rating': 4.6, 'votes': 8289},
   'id': 321},
  {'city': 'Denver',
   'name': 'Fun Republic Social',
   'estimated_cost': 90,
   'user_rating': {'average_rating': 4.6, 'votes': 2914},
   'id': 323},
  {'city': 'Denver',
   'name': 'English Kitchen',
   'estimated_cost': 150,
   'user_rating': {'average_rating': 4.6, 'votes': 1887},
   'id': 324},
  {'city': 'Denver',
   'name': 'Pi Bar and Kitchen',
   'estimated_cost': 160,
   'user_rating': {'average_rating': 4.6, 'votes': 1927},
   'id': 325}],
 [{'city': 'Denver',
   'name': 'Palladium Social',
   'estimated_cost': 140,
   'user_rating': {'average_rating': 4.9, 'votes': 4892},
   'id': 332},
  {'city': 'Denver',
   'name': 'Bayroute',
   'estimated_cost': 300,
   'user_rating': {'average_rating': 4.8, 'votes': 1466},
   'id': 333},
  {'city': 'Denver',
   'name': 'HOP : House of Party',
   'estimated_cost': 160,
   'user_rating': {'average_rating': 4.7, 'votes': 813},
   'id': 331},
  {'city': 'Denver',
   'name': 'Jimis Burger',
   'estimated_cost': 70,
   'user_rating': {'average_rating': 4.6, 'votes': 3680},
   'id': 335},
  {'city': 'Denver',
   'name': 'Garage Inc. Public House',
   'estimated_cost': 150,
   'user_rating': {'average_rating': 4.5, 'votes': 684},
   'id': 334}]]

I want to compare the value for average_rating and return the highest top 5 (if the numbers are the same then display based on the original order)
Expected output:
Sushi Kashiba
Peninsula Grand Hotel
Plum by Bent Chair
R' ADDA
Palladium Social

A: If lst is your list from the question:
for val in sorted(
    [v for l in lst for v in l],
    key=lambda k: k["user_rating"]["average_rating"],
    reverse=True,
)[:5]:
    print(val["name"])

Prints:
Sushi Kashiba
Peninsula Grand Hotel
Plum by Bent Chair
R' ADDA
Palladium Social

A: You could flatten the list and then use sorted with the required key.
Solution:
#assuming your list is "my_list"
flattened = [i for lst in my_list for i in lst]
>>> [d["name"] for d in sorted(flattened,
                               key=lambda x: x["user_rating"]["average_rating"],
                               reverse=True)[:5]]
['Sushi Kashiba',
 'Peninsula Grand Hotel',
 'Plum by Bent Chair',
 "R' ADDA",
 'Palladium Social']

Explanation:

*

*Flatten your list of lists to a list using list comprehension
flattened = [i for lst in my_list for i in lst]

*Sort the list of dictionaries on "average_rating":
sorted_dicts = sorted(flattened, key=lambda x: x["user_rating"]["average_rating"], reverse=True)

*Keep only the top 5

A: You can use itertools
import itertools
# flattens list and take top 5. Negative sign because we want high->low
res = sorted(list(itertools.chain(*l)), key=lambda x: -x['user_rating']['average_rating'])[:5]
for r in res:
    print(r['name'])


text:
Q: how to handle foreign key with morph one to many files I have these tables:
file:
id - path - meme_type

fileable:
id - file_id - fileable_id - fileable_type

ticket_bodies:
id - title

each row of TickeBody have multi files. now how to implement morph functions? (I don't want to combine file table with fileable table)

A: Something like this?
App\Models\File:
public function fileable(){
    return $this->morphTo();
}

App\Models\TicketBody:
public function files(){
    return $this->morphMany(App\Models\File::class, 'fileable');
}


text:
Q: C# Blocking IP by modifying Windows 7 Firewall I'm starting to build an anti-ddos application in C#, it's going to block IP's by checking how many connections there are, in an amount of time, but I can't find whats needed for NetFwMgrType.
Here's code, I just started:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NETCONLib;
using NATUPNPLib;
using NetFwTypeLib;

namespace WindowsFormsApplication1
{

public partial class Form1 : Form
{
    Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
    INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
    bool Firewallenabled = mgr.LocalPolicy.CurrentProfile.FirewallEnabled;

    public Form1()
    {
        InitializeComponent();
    }
}
}

The errors I get is:
Error 1 A field initializer cannot reference the non-static field, method, or        property 'WindowsFormsApplication1.Form1.NetFwMgrType'
Error   2   A field initializer cannot reference the non-static field, method,     or property 'WindowsFormsApplication1.Form1.mgr'
(I added references:  \Windows\System32\hnetcfg.dll and \Windows\System32\FireWallAPI.dll)
Thanks for answer.
Oh and if you know how to block IPs with Firewall modifying, as well, it would save me a lot of googling:)


text:
Q: Unity ScrollView performace issue on Android and iOS I have asked this question on Stack Overflow one month ago, it didn't receive answers and it was automatically deleted.
Since I have found the solution, I'm asking the question again hoping my own answer can be useful to someone else.
In my Unity game, I have an inventory scene containing a Scroll View that gets populated at runtime.
In Editor everything works perfectly, on Android and iOS game slows down to the point of being unusable if the player opens and then closes the inventory a few times.

A: It was due to Admob. In the main game scene, inside Start method, a request for Admob banner was instantiated.
So switching between the scenes caused this request to be unnecessary instantiated multiple times, probably causing a garbage collection issue.


text:
Q: Stored procedure to update table in SQL I have a following issue...
I have three variable, v1,v2,v2 (All are of type java.util.ArrayList). I want to write a stored procedure that will take this variable as an input and update the one table.
How can I loop throw the array list of the variable in sql and update the table?
For instance, the values for v1 (10,11,12), v2(21,22,23), v3(31,32,33). The sql update of the table should happen as follows
Table1:
Row1: 10,21,31
Row2: 11,22,32
Row3: 12,23,33
I will be thankful if someone could get back to me on how to write the store procedure for this.

A: I have used this approach and it works for me perfectly fine.
Have your stored procedure receive the three variables, each as varchar(max) -- if you know the size you can write the number instead of max. For example:
create procedure usp_testSP
    @v1 varchar(max),
    @v2 varchar(max),
    @v3 varchar(max)
as
begin
    declare @v1Values table (number int);

    insert into @v1values
    select * from dbo.fnSplit(@v1,','); -- the fnSplit function is given below

    -- this way you can retrieve all values for other two variables
    -- then you can use the corresponding tables, i.e.: @v1Values to complete the steps you need to.
end

Here's the code for dbo.fnSplit(@inputList, @delimiter):
 CREATE FUNCTION [dbo].[fnSplit](@sInputList VARCHAR(max), @sDelimiter VARCHAR(10) = ',')
 RETURNS @List TABLE (item varchar(100))
 BEGIN
     DECLARE @sItem varchar(100)
     WHILE CHARINDEX(@sDelimiter, @sInputList, 0) <> 0
     BEGIN

         SELECT @sItem = RTRIM(LTRIM(SUBSTRING(@sInputList, 1, CHARINDEX(@sDelimiter, @sInputList,0) - 1))),
                @sInputList = RTRIM(LTRIM(SUBSTRING(@sInputList, CHARINDEX(@sDelimiter, @sInputList, 0) + LEN(@sDelimiter),LEN(@sInputList))))

         IF LEN(@sItem) > 0

         INSERT INTO @List SELECT @sItem

     END

     IF LEN(@sInputList) > 0
     BEGIN
         INSERT INTO @List SELECT @sInputList
     END
     RETURN
 END

And finally, in your java code, you can convert the list to a string and pass it on to the stored procedure call.
List<Integer> v1; //suppose this is the list that contains the values.
String s = String.join("," /*this is the delimiter. It should be the same as the one you use when you call the dbo.fnSplit() function.*/, v1);


text:
Q: Appium Parallel Test Execution removes driver for one device, showing A session is either terminated or not started Hi I tried to implement parallel test execution using TestNG and Appium, I used ThreadLocal. The problem is that one device after the first run is lost. But the other device is completed all its test.
Here is my code,
BaseDriver
TestClass
TestListener
TestNG XML
Error Description
Appium Server Log
Execution Log
I am struggling to find where the driver is removed.
Any help will be appreciated.

A: I fixed it by myself. As I am using System port and WDALocalPort I for single appium session, I don't need to use session override. Session overriding was replacing my current session's with a single new session. Anyway thanks everyone


text:
Q: CakePHP GROUP BY with WHERE and COUNT on HATBM table Although I'm aware of the group, contain, fields and order options on a find(), I just cannot seem to make the following query with CakePHP 2.2.3 :
SELECT `User`.*, SUM(`Influence`.`id`) AS matches
FROM `db`.`users` AS `User`
    LEFT JOIN `db`.`influences_users` AS `InfluencesUser` ON (`User`.`id` = `InfluencesUser`.`user_id`)
    LEFT JOIN `db`.`influences` AS `Influence` ON (`InfluencesUser`.`influence_id` = `Influence`.`id`)
WHERE 1 = 1
AND `Influence`.`id` IN (1, 2, 3, 4)
GROUP BY `User`.`id`
ORDER BY COUNT(`Influence`.`id`) DESC

Basically, I'm trying to retrieve an array of Users having the Influences 1, 2, 3 and 4, with the COUNT() function on the Influences tables, then order them by COUNT() DESC.
Is there a clean way (I'd rather not want to use any hacks or functions like Model::query()) to do so in CakePHP?

EDIT: It wasn't actually a SUM() but rather a COUNT() although I doesn't change anything to my problem.

A: you can add virtual fields dynamically for only the next queries using
$this->virtualFields['matches'] = 'SUM(Influence.id)';

then you have it directly in your result array to work with:
echo $user['User']['matches']; // if you query on the User model that is

also you can use it on your order/conditions etc:
'order' => array('User__matches' => 'DESC')

You need to work on the model, that has all the other models as "belongsTo", though!
So work with "InfluencesUser" and contain "Influence" and "User"
So in your case:
$this->User->InfluencesUser->virtualFields['matches'] = 'SUM(Influence.id)';
...
$results = $this->User->InfluencesUser->find(...)

and
echo $result['InfluencesUser']['matches']; //in the view

and
'order' => array('InfluencesUser__matches' => 'DESC')

A: I managed to find a solution, not too hacky and unless someone has a better solution (not a lot when you see the number of answers I got), here it is:
$this->User->virtualFields['matches'] = 'COUNT(InfluencesUser.influence_id)';
$matches = $this->User->find(
        'all',
        array(
            'joins' => array(
                array(
                    'alias' => 'InfluencesUser',
                    'table' => 'influences_users',
                    'type' => 'LEFT',
                    'conditions' => array(
                        'InfluencesUser.influence_id' => $userInfluences, //$userInfluences contains the list of influences I want to do the restriction on
                        '`InfluencesUser`.`user_id` = `User`.`id`'
                    )
                )
            ),
            'group' => 'User.id',
            'order' => array('User__matches' => 'DESC'),
        ));

I manually join the InfluencesUser table (I don't actually need the Influence one, only the list of influence_id) to make a big table. I just had to do the restriction (influence_id) on the join table, then I can do my goup by, the count() and append the count() field to my results array, thanks to mark's answer.
Obviously I would have prefered using something like the contain parameter, but it doesn't seem to allow me to do what I can achieve with the join in this particular situation.
Hope this could save some time to some people.

A: how about a sub query?
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#sub-queries
I answered a question using this approach for a HATBM issue. It is a useful approach for complex queries.


text:
Q: Why does the enter-animation not run when mounting new page components In this code example, the exit transition works, but the enter transition does not. I'm curious to if I approach this the right way of if this is a bug with styled-components.
The goal is to animate to 50% off screen when exiting, and to animate from 100% off screen to on-screen on enter. I've set the opacity to 50% to be able to see both page divs at all times.
I'd prefer to use Transition instead of CSSTransition as I'd like to purely use styled-components instead of mixing in regular style sheets.
Code example: https://codesandbox.io/s/sweet-mcnulty-dbptv
The animation states when exiting are (see console in CodeSandbox):

*

*entered - set initial position and disable transitions

*exiting - set target position and enable transitions

*exited - does not matter since the component is unmounted by react-router

NOTE: This (exit transition) works well.
The animation states when entering are (see console in CodeSandbox):

*

*exited - set initial position and disable transitions

*entering - set target position and enable transitions

*entered

This (the enter transition) does not animate at all. The big difference between on-exit and on-enter is that on-exit the component is already mounted, while on-enter it is mounted just before the animation should happen. My working thesis is that styled-component is not committing both the CSS updates (step 1 and 2) to the DOM individually, and thus the browser does not trigger the transition. But I Don't know this, anyhow it only happens if you mount just before the transition.
Any ideas?
Full code example (same as https://codesandbox.io/s/sweet-mcnulty-dbptv):
import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom";
import { TransitionGroup, Transition } from "react-transition-group";

const Nav = styled.nav`
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 80px;
`;

const Page = styled.div`
  background: white;
  display: flex;
  justify-content: center;
  align-items: center;
  will-change: transform;
  position: fixed;
  top: 80px;
  bottom: 0;
  left: 0;
  right: 0;
  background: ${props => (props.backgroundColor === "gray" ? "#eee" : "#efe")};
  opacity: 0.5;

  transform: ${props => {
    // Details page is green
    if (props.backgroundColor === "green") {
      // console.log(new Date().getTime(), 'Details page (css):      ', props.transitionState);
    }

    switch (props.transitionState) {
      case "entering":
        return "translateX(0)";

      case "entered":
        return "translateX(0)";

      case "exiting":
        return "translateX(-50%)";

      case "exited":
        return "translateX(100%)";

      default:
        throw new Error("This should never happen");
    }
  }};

  transition: ${props => {
    switch (props.transitionState) {
      case "entering":
        return "transform 1000ms cubic-bezier(0, 0, 0, 1)";

      case "entered":
        return "none";

      case "exiting":
        return "transform 1000ms cubic-bezier(0, 0, 0, 1)";

      case "exited":
        return "none";

      default:
        throw new Error("This should never happen");
    }
  }};
`;

const HomePage = props => {
  return (
    <Page backgroundColor="gray" transitionState={props.transitionState}>
      Home page!
    </Page>
  );
};

const DetailsPage = props => {
  console.log(new Date().getTime(), 'Details page (component):', props.transitionState);

  return (
    <Page backgroundColor="green" transitionState={props.transitionState}>
      Details page!
    </Page>
  );
};

function App() {
  return (
    <Router>
      <Nav>
        <Link to="/">Home</Link>
        <Link to="/details">Details</Link>
      </Nav>
      <Route
        render={({ location }) => {
          return (
            <TransitionGroup component={null}>
              <Transition key={location.pathname} timeout={1000}>
                {transitionState => {
                  return (
                    <Switch location={location}>
                      <Route
                        exact
                        path="/"
                        render={() => (
                          <HomePage transitionState={transitionState} />
                        )}
                      />
                      <Route
                        exact
                        path="/details"
                        render={() => (
                          <DetailsPage transitionState={transitionState} />
                        )}
                      />
                    </Switch>
                  );
                }}
              </Transition>
            </TransitionGroup>
          );
        }}
      />
    </Router>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

A: Here is a way around it, but it requires using CSSTransition. It still does not explain why the example in the original question does not work.
https://codesandbox.io/s/page-transition-with-csstransition-working-emudw
import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom";
import { TransitionGroup, CSSTransition } from "react-transition-group";

const Nav = styled.nav`
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 80px;
`;

const Page = styled.div`
  background: white;
  display: flex;
  justify-content: center;
  align-items: center;
  will-change: transform;
  position: fixed;
  top: 80px;
  bottom: 0;
  left: 0;
  right: 0;
  background: ${props => (props.backgroundColor === "gray" ? "#eee" : "#efe")};
  opacity: 0.5;

  &.page-transition-enter {
    transform: translateX(100%);
    transition: none;
  }

  &.page-transition-enter-active {
    transform: translateX(0);
    transition: transform 1000ms cubic-bezier(0, 0, 0, 1);
  }

  &.page-transition-exit {
    transform: translateX(0);
    transition: none;
  }

  &.page-transition-exit-active {
    transform: translateX(-50%);
    transition: transform 1000ms cubic-bezier(0, 0, 0, 1);
  }
`;

const HomePage = props => {
  return <Page backgroundColor="gray">Home page!</Page>;
};

const DetailsPage = props => {
  return <Page backgroundColor="green">Details page!</Page>;
};

function App() {
  return (
    <Router>
      <Nav>
        <Link to="/">Home</Link>
        <Link to="/details">Details</Link>
      </Nav>
      <Route
        render={({ location }) => {
          return (
            <TransitionGroup component={null}>
              <CSSTransition
                key={location.pathname}
                timeout={1000}
                classNames="page-transition"
              >
                <Switch location={location}>
                  <Route exact path="/" render={() => <HomePage />} />
                  <Route exact path="/details" render={() => <DetailsPage />} />
                </Switch>
              </CSSTransition>
            </TransitionGroup>
          );
        }}
      />
    </Router>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


text:
Q: applying css3 style to specific id I wanted to apply style only to the myPage id. But I am not able to achieve it with the following:
<!DOCTYPE html>

<link rel="stylesheet" href="style1.css"/>

Welcome To CSS3....
Learning.....!

Welcome ....

.myPage div{
border:2px solid black;
background-color:yellow;
font-color:red;
box-shadow:10px 10px 7px #777
}

Please tell me the fault.
Thanks
Sneha

A: When you use this selector:
.myPage div

You are looking for an element with the class of myPage. You want this one instead:
#myPage div

The . looks for classes. The # looks for elements with the specific ID.

A: The id of your div is myPage , so to apply style to elements with id you must use #.
You should use #myPage div here.
The . is used for applying styles to a class.Basic Reference.

A: when you given css style in page itself must be as below
< style>
// css code
< /style>
and the instead of using id -- #  you went for the class -- .
that was the mistake

A: The selector is looking for the class myPage, with a div contained within it.
Try the following selector:
div#myPage { }

This will look for an element that is both a div and has the id of myPage.
The dot indicaties a class, the hash indicates an id. The selector #myPage div would indicate any element with the id myPage that has a div inside of it, not an element that is both a div and has an id of myPage.

A:
.myPage div{} this will apply css to div inside the element having a class myPage
remember "." for class and "#" for id
so just make a change like

it will solve your problem


text:
Q: Using R to calculate probability of rolling 2 numbers in 20 throws We have an 8-sided die. Throwing it 20 times,
what is the probability of rolling a number larger than 6 at least 12 times and at most 16 times?
If you know of an efficient program to write so that I won't have to type in the maths manually, I would be so happy.

A: The answer by CoolSerdash shows you how to simulate the probability of interest.  Here is a direct probability calculation without simulation:
sides   <- 8    # Number of sides of the die
throws  <- 20   # Number of throws
no_cut  <- 6    # Cut-off value (must roll above this)
n_lower <- 12   # Lower bound
n_upper <- 16   # Upper bound

prob <- (sides - no_cut)/sides;
pbinom(n_upper, throws, prob) - pbinom(n_lower-1, throws, prob);

[1] 0.000935362

A: Here is a quick implementation. I'm sure there are more efficient ways.
d <- 8        # Sides of the die
throws <- 20  # Number of throws
no_cut <- 6   # Number at least on die
n_lower <- 12 # Lower cutoff
n_upper <- 16 # Upper cutoff

n_sim <- 1000000 # Number of simulations

res <- NULL

res <- replicate(n_sim, {
  x <- sample.int(d, size = throws, replace = TRUE)
  s <- sum(x > no_cut)
  (s >= n_lower && s <= n_upper)
})

sum(res)/n_sim # simulated probability


text:
Q: nav element with no heading -- document outline This question has to do with document outline structure as it relates to headers within the  element. It is not a question about validation.
When I validate one of the pages for my web app, and check the field that says "document outline" the outline includes this:

[nav element with no heading]

I don't want to add a heading to my nav element because it will seem extraneous, to the consumer of the app, in the context of my nav (it's a nav element for pagination of a sub-section of the page); but I do want to have a well structured document outline.
So my question is multi-part:

*

*Why is the outline including this?

*What is the proper way to add a heading to a nav element?

*Is it necessary to add a heading to a nav element? because it doesn't seem like a common practice on most websites.

A: *

*The nav element is a sectioning element, much like body, article, section and aside. Every section is expected, though not required, to have a heading.

*The proper way is with an h1, h2, ... element, just as with any other sectioning element.

*No, it's not necessary to do so. If you're really concerned about the outline, you can always add one and hide it using CSS, but there is nothing wrong with leaving out the heading altogether.

The outline that's produced by a document has no effect on validation. A document can validate as HTML5 while producing a completely different outline than the author might expect. But in the context of validation, headings are never required by any sectioning element.

A: It is not a HTML conformance error to have a nav element without a heading. The outline view provided in the conformance checker is purely informative.

A: @james-donnelly's answer is spot on. Just wanted to add that I typically do something like this:

Site Navigation

...

...

...

And then in my CSS, the v-h class is defined as:
.v-h {
    position: absolute !important;
    height: 1px; width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px, 1px, 1px, 1px);
}

This makes the header invisible in the rendered HTML content, but allows screen readers to 'see' the content.
references: http://snook.ca/archives/html_and_css/hiding-content-for-accessibility

A: This is because the nav element is defined within the Sections section of the HTML5 specification and sections are expected to have headings.
As for the document outline:

The outline for a sectioning content element or a sectioning root element consists of a list of one or more potentially nested sections. A section is a container that corresponds to some nodes in the original DOM tree. Each section can have one heading associated with it, and can contain any number of further nested sections.
— 4.3.10.1 Creating an outline - HTML5 Specification

Note the word can - they aren't required. If they were required, the validator would be throwing warnings and errors, not somewhat-friendly notes to remind you that a heading is missing.

So to answer your questions:

Why is the outline including this?

It's just a friendly reminder that a heading isn't present. Just in case you were expecting a heading to be present but you'd forgotten to add one, for instance.

What is the proper way to add a heading to a nav element?

That entirely depends on what you're wanting to achieve. The HTML5 specification itself gives the following example:

Navigation

...

Is it necessary to add a heading to a nav element? because it doesn't seem like a common practice on most websites.

Not at all. It's entirely optional. Some may argue that it'd be good for SEO purposes to add a heading to all sections, but that's entirely up to you. You can always hide the heading with CSS if you do want to add them but don't want to display them.


text:
Q: Apple Mach-O Librarian Error I download the cocos2d-x project from our SVN, but an problem happened when I opened it with Xcode, error information is as follows:
/Applications/Xcode .app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: -dynamic not specified the following flags are invalid: -ObjC
/Applications/Xcode .app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: can't locate file for: -lwebp
/Applications/Xcode .app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: file: -lwebp is not an object file (not allowed in a library)
Command /Applications/Xcode .app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool failed with exit code 1

can anyone give me some advice, thank you very much.

A: [edit]
@trojanfoe, you're right.
sry didn't read the last part. I check my cocos2s-x project and give you a right anwer.
[edit 2]
OK, I tested my project and the empty from github. Where have you downloaded the SVN from?
And what is your Xcode Version?
have you used this repository: get cocos2d-x?
If not, go ahead and clone it, open the build>cocos2d_samples.xcodeproj and select Test cpp iOS > iPhone > iOS 7.0 for example and run the build. This should work at least.


text:
Q: How to Select Multiple dropdowns using selenium webdriver Currently am working on selenium webdriver. I am trying select the multiple dropdowns and it is the filter selection. once i selected multiple dropdown i will click on Apply Filter button then i will produce the result based on the selected filter section. so i am getting problem to select multiple drop down and can't able to click on Apply filter dropdown. Could you please help me to figure out how to use the code. am using java
Here is my sample code:
driver.findElement(By.id("ext-new-prs")).click();
new Select(driver.findElement(By.id("visualizationId"))).selectByVisibleText("Center");
new Select(driver.findElement(By.id("periodId"))).selectByVisibleText("Last 52 Weeks");
new Select(driver.findElement(By.id("topographyId"))).selectByVisibleText("Center");
driver.findElement(By.cssSelector("#topographyId > option[value=\"center\"]")).click();
new Select(driver.findElement(By.id("centerId"))).selectByVisibleText("OAB");
new Select(driver.findElement(By.id("featureRequestId"))).selectByVisibleText("Include");
driver.findElement(By.id("kpiFilterSubmit")).click();

A: Something like below:-
Actions actions = new Actions(driver);
WebElement dBox1= (new WebDriverWait(driver,10)).until(ExpectedConditions.elementToBeClickable(By.id("visualizationId"))).selectByVisibleText("Center");
actions.moveToElement(dBox1);
actions.click();
actions.perform();

A: public static void waitforElement (WebDriver driver , int Seconds , String Locator )
{
WebDriverWait wait=new WebDriverWait(driver, Seconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(Locator)));
}
use this method
waitforElement(driver,30,"//div[@id='divGrid']");
call like this
By sundar
www.mjksundar.weebly.com


text:
Q: Sonar runner 2.3 throws exception with Sonar 3.7 --> IllegalDataException I am trying to analyse Java project using SOnar 3.7 & sonar-runner 2.3.
I was successfully able to analyse same codebase using Sonar 3.6.1 & Sonar runner 2.2.1 with same rule set/profile.
However, when I have upgraded version then I am having following errors...
org.jdom.IllegalDataException: The data "null" is not legal for a JDO
M attribute: A null is not a legal XML value
Console Output :
SonarQube Runner 2.3 Java 1.6.0_30 Sun Microsystems Inc. (64-bit) Windows 7 6.1 amd64
INFO: Error stacktraces are turned on.
INFO: Runner configuration file: C:\Dhruba\InstallationFolder\Sonar\sonar-runner-2.3\conf\sonar-runner.properties
INFO: Project configuration file: C:\Dhruba\Projects\Elsevier-OPSBANK_II_AIS\R11_Service_Workspace\sonar-project.properties
INFO: Default locale: "en_US", source code encoding: "windows-1252" (analysis is  platform dependent)
INFO: Work directory: C:\Dhruba\Projects\Elsevier-OPSBANK_II_AIS\R11_Service_Workspace\.sonar
INFO: SonarQube Server 3.7
13:38:29.376 INFO  - Load batch settings
13:38:29.482 INFO  - User cache: C:\Users\Dhruba\.sonar\cache
13:38:29.487 INFO  - Install plugins
13:38:31.219 INFO  - Install JDBC driver
13:38:31.227 INFO  - Create JDBC datasource for jdbc:oracle:thin:@localhost:1521 /orcl
13:38:32.382 INFO  - Initializing Hibernate 13:38:34.579 INFO  - Load project settings
13:38:34.665 INFO  - Apply project exclusions
13:38:34.788 INFO  - -------------  Scan OPSBankIIUtilityService
13:38:34.790 INFO  - Load module settings
13:38:35.382 INFO  - Quality profile : [name=OBBase1,language=java]
13:38:35.394 INFO  - Excluded sources:
13:38:35.394 INFO  -   **/*_*.java
13:38:35.394 INFO  -   **/bo/**
13:38:35.395 INFO  -   */stub/**
13:38:35.395 INFO  -   **/*FacadeSoap*.java
13:38:35.395 INFO  -   com.ibm.ejs.container._EJSWrapper_**/src
13:38:35.395 INFO  -  *_Deser/src
13:38:35.395 INFO  -   *Proxy.java
13:38:35.395 INFO  -   */*FacadeHome.java
13:38:35.395 INFO  -   */*FacadeLocalHome.java 13:38:35.395 INFO  - com/elsevier/obii/xml/*
13:38:35.395 INFO  - Excluded tests:
13:38:35.395 INFO  -   */package-info.java
13:38:35.430 INFO  - Configure Maven plugins
13:38:35.502 INFO  - Compare to previous analysis
13:38:35.532 INFO  - Compare over 7 days (2013-09-14)
13:38:35.558 INFO  - Compare to previous version
13:38:35.734 INFO  - Base dir: C:\Dhruba\Projects\Elsevier-OPSBANK_II_AIS\R11_Service_Workspace\OPSBankIIUtilityService
13:38:35.734 INFO  - Working dir: C:\Dhruba\Projects\Elsevier-OPSBANK_II_AIS\R11_Service_Workspace\.sonar\dhrsrvc_OPSBankIIUtilityService
13:38:35.735 INFO  - Source dirs: C:\Dhruba\Projects\Elsevier-OPSBANK_II_AIS\R11_Service_Workspace\OPSBankIIUtilityService\src
13:38:35.735 INFO  - Source encoding: windows-1252, default locale: en_US
13:38:36.090 INFO - Sensor JavaSourceImporter...
13:38:37.021 INFO  - Sensor JavaSourceImporter done: 931 ms
13:38:37.021 INFO  - Sensor JavaSquidSensor...
13:38:37.160 INFO  - Java AST scan...
13:38:40.518 INFO  - Java AST scan done: 3358 ms
13:38:40.763 INFO  - Sensor JavaSquidSensor done: 3742 ms
13:38:40.764 INFO  - Sensor SurefireSensor...
13:38:40.765 INFO  - parsing C:\Dhruba\Projects\Elsevier-OPSBANK_II_AIS\R11_Service_Workspace\.sonar\dhrsrvc_OPSBankIIUtilityService\build\surefire-reports
13:38:40.767 INFO  - Sensor SurefireSensor done: 3 ms
13:38:40.769 INFO  - Sensor CpdSensor...
13:38:40.770 INFO  - SonarEngine is used
13:38:40.846 INFO  - Cross-project analysis disabled
13:38:41.511 INFO - Sensor CpdSensor done: 742 ms
13:38:41.511 INFO  - Sensor CheckstyleSensor...
13:38:41.514 INFO  - Execute Checkstyle 5.6...
13:38:41.534 INFO  - Checkstyle configuration: C:\Dhruba\Projects\Elsevier-OPSBANK_II_AIS\R11_Service_Workspace\.sonar\dhrsrvc_OPSBankIIUtilityService\checkstyle.xml
13:38:43.845 INFO  - Execute Checkstyle 5.6 done: 2331 ms
13:38:43.849 INFO  - Sensor CheckstyleSensor done: 2338 ms
13:38:43.850 INFO  - Sensor PmdSensor...
13:38:43.853 INFO  - Execute PMD 4.3...
13:38:43.864 INFO  - Java version: 1.5
13:38:44.008 INFO  - Execute PMD 4.3 done: 155 ms
INFO: ------------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------------------------
Total time: 17.761s Final Memory: 15M/406M
INFO: ------------------------------------------------------------------------
ERROR: Error during Sonar runner execution
 org.sonar.runner.impl.RunnerException: Unable to execute Sonar
     at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:91)
     at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
     at java.security.AccessController.doPrivileged(Native Method)
     at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
     at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
     at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102)
     at org.sonar.runner.api.Runner.execute(Runner.java:90)
     at org.sonar.runner.Main.executeTask(Main.java:70)
     at org.sonar.runner.Main.execute(Main.java:59)
     at org.sonar.runner.Main.main(Main.java:41) Caused by: org.sonar.api.utils.XmlParserException: org.jdom.IllegalDataException : The data "null" is not legal for a JDOM attribute: A null is not a legal XML value.
     at org.sonar.plugins.pmd.PmdSensor.analyse(PmdSensor.java:55)
     at org.sonar.batch.phases.SensorsExecutor.execute(SensorsExecutor.java:72)
     at org.sonar.batch.phases.PhaseExecutor.execute(PhaseExecutor.java:114)
     at org.sonar.batch.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:142)
     at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:88)
     at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:73)
     at org.sonar.batch.scan.ProjectScanContainer.scan(ProjectScanContainer.java:186)
     at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:181)
     at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:179)
     at org.sonar.batch.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:174)
     at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:88)
     at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:73)
     at org.sonar.batch.scan.ScanTask.scan(ScanTask.java:57)
     at org.sonar.batch.scan.ScanTask.execute(ScanTask.java:45)
     at org.sonar.batch.bootstrap.TaskContainer.doAfterStart(TaskContainer.java:82)
     at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:88)
     at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:73)
     at org.sonar.batch.bootstrap.BootstrapContainer.executeTask(BootstrapContainer.java:156)
     at org.sonar.batch.bootstrap.BootstrapContainer.doAfterStart(BootstrapContainer.java:144)
     at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:88)
     at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:73)
     at org.sonar.batch.bootstrapper.Batch.startBatch(Batch.java:92)
     at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:74)
     at org.sonar.runner.batch.IsolatedLauncher.execute(IsolatedLauncher.java:45)
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
     at java.lang.reflect.Method.invoke(Method.java:597)
     at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:87)
     ... 9 more
**Caused by: org.jdom.IllegalDataException: The data "null" is not legal for a JDO M attribute: A null is not a legal XML value.**
     at org.jdom.Attribute.setValue(Attribute.java:486)
     at org.jdom.Attribute.<init>(Attribute.java:229)
     at org.jdom.Attribute.<init>(Attribute.java:252)
     at org.jdom.Element.setAttribute(Element.java:1109)
     at org.sonar.plugins.pmd.PmdProfileExporter.exportPmdRulesetToXml(PmdProfileExporter.java:126)
     at org.sonar.plugins.pmd.PmdProfileExporter.exportProfile(PmdProfileExporter.java:63)
     at org.sonar.plugins.pmd.PmdExecutor.createRulesets(PmdExecutor.java:107)
     at org.sonar.plugins.pmd.PmdExecutor.executeRules(PmdExecutor.java:89)
     at org.sonar.plugins.pmd.PmdExecutor.executePmd(PmdExecutor.java:75)
     at org.sonar.plugins.pmd.PmdExecutor.execute(PmdExecutor.java:61)
     at org.sonar.plugins.pmd.PmdSensor.analyse(PmdSensor.java:52)
     ... 37 more ERROR: ERROR: Re-run SonarQube Runner using the -X switch to enable full debug logging.

Can you please help to resolve this one ?

A: I was analyzing the issue and found that imported profile from Sonar 3.6.1 to 3.7 had  issue. Sonar 3.7 was not able to parse few of the XPath rules.
Therefore, I have just removed those XPath rules and re-added them manually and it starts working. This issue is not a bug of Sonar-runner instead Sonar 3.7 could not restore profiles correctly.


text:
Q: Make a Page Control like the iOS 7 Camera app I was curious as to how you would make the custom page control that Apple has implemented in their camera app, with the text essentially acting as the page control and moving along with the swipe.
Are they using a UI Element that has the text fade into the background like that?

A: If you mean the text on the bottom ("Video", "Photo", "Square", ...) there's no stock component for doing it.
If I had to implement it I'd try with a UICollectionView with a flow Layout. You can easily play with alphas and 3D transforms to achieve the same effect.
As a reference you may want to look at the WWDC 2012 talks about UICollectionView, in one of which (can't remember which one) they explain how to build a cover flow interface with using a flow layout.


text:
Q: how call external class (contains selenium commands) in selenium test properly? I use Selenium Web Driver with JUnit in Eclipse. I want diminish my code by creating new classes for repitable steps. I want store this classes in separate files for convenience. For example this one of such classes:
import org.openqa.selenium.ie.InternetExplorerDriver;

 //Login
public class Login {
private InternetExplorerDriver driver;

String url;
String name;
String password;
String language;
public Login (String ur, String nam, String pass, String lang){
    url=ur;
    name=nam;
    password=pass;
    language=lang;
}
 public void log_in (){
 driver.get(url);
 driver.findElement(By.name("username")).sendKeys(name);
 driver.findElement(By.name("password")).sendKeys(password);
 driver.findElement(By.name("language")).sendKeys(language);
 driver.findElement(By.name("logon_action")).click();
  }
  }

This is my main test:
package bobsworld;

import init.Login;

import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class WebTest {
private WebDriver driver;

@Test
public void testUnit() throws Exception {

//Open new window
System.setProperty("webdriver.ie.driver", "IEDriverServer.exe");
driver = new InternetExplorerDriver();

//Login
init.Login login = new init.Login ("myurl", "log","pas","English");
  login.log_in();
}

The problem is with object driver. I get java.lang.NullPointerException and can't execute test. How should I organize call to Login and code to make my test work?

A: What you try to achieve is a quite popular approach called "PageObjects".
Your issues:

*

*Use some checkstyle tool to improve code quality

*Do a whole lot of research about Java in general

*The Login Class or "init.Login" (it's quite unusual to have a part of the package as prefix for the class) is not able to use the same WebDriver instance because you don't forward it. Normally you would have opened a second WebDriver instance but that seems to be impossible though I don't know your setup. You have to forward the "driver" as a parameter to the constructor of the Login class.

*Try to use real PageObjects as described here inluding PageFactory to improve readability and maintainability


text:
Q: Powershell cmdlet requesting optional parameters as mandatory when running as script I am trying to use powershell to create a script which I use to add vpn connections to windows 8.1 machines. For this microsoft has made the add-vpnconnection cmdlet.
When running add-vpnconnection by hand, and supplying the mandatory parameters the cmdlet works fine.
When using my script to run the cmdlet - I am requested every single optional parameter before it functions. Does anyone know why? How can I prevent this?
Powershell script:
Param(

[Parameter(Mandatory=$true)]
[string]$Client,
[string]$Remotedns,
[string]$DNSSUFFIX ,
[string]$TunnelType = "SSTP"
) #end param
Add-VpnConnection -Name "$client VPN" -ServerAddress $Remotedns -AuthenticationMethod MSChapv2 -DnsSuffix $DNSSUFFIX = "" -SplitTunneling -TunnelType $TunnelType -AllUserConnection

A: After testing this, it seems that your script should have more mandatory parameters - Add-VpnConnection won't accept just the parameters passed with just your enforced ($Client).
When running the "minimal set", the return asks for further details.
Add-VpnConnection -Name "Test Name" -AuthenticationMethod MSChapv2 -SplitTunneling -AllUserConnection
cmdlet Add-VpnConnection at command pipeline position 1
Supply values for the following parameters:
ServerAddress:

If you run Get-Help against Add-VPNConnection, it seems that you'll need at least -ServerAddress ($Remotedns, in your script) to be mandatory as well.


text:
Q: Mongoimport results in "no collection specified" despite having collection defined mongoimport --uri mongodb://USER:SECRET@appname-shard-00-00-tlxyp.mongodb.net:27017,appname-shard-00-01-tlxyp.mongodb.net:27017,appname-shard-00-02-tlxyp.mongodb.net:27017/test?ssl=true&replicaSet=appname-shard-0&authSource=admin --collection scoringSystem --file /home/myUser/IdeaProjects/app/scoring-system.json

Arguments:

*

*URI: mongodb://USER:SECRET@appname-shard-00-00-tlxyp.mongodb.net:27017,appname-shard-00-01-tlxyp.mongodb.net:27017,appname-shard-00-02-tlxyp.mongodb.net:27017/test?ssl=true&replicaSet=appname-shard-0&authSource=admin

*Collection: scoringSystem

*File: /home/myUser/IdeaProjects/app/scoring-system.json
This results in:
[1] 23452
[2] 23453
2017-10-17T20:00:28.633+0200    no collection specified
2017-10-17T20:00:28.633+0200    using filename '' as collection
2017-10-17T20:00:28.633+0200    error validating settings: invalid collection name: collection name cannot be an empty string
2017-10-17T20:00:28.633+0200    try 'mongoimport --help' for more information
 --collection: command not found
[1]-  Exit 1                  mongoimport --uri mongodb://(...output omitted...)?ssl=true
[2]+  Done                    replicaSet=Wamsteady-shard-0

I do not understand how mongoimport doesn't find the command "--collection" since it's a valid parameter as documented here.
What is wrong?
mongoimport --version

mongoimport version: r3.4.9
git version: 876ebee8c7dd0e2d992f36a848ff4dc50ee6603e
Go version: go1.7
   os: linux
   arch: amd64
   compiler: gc
OpenSSL version: OpenSSL 1.0.2g  1 Mar 2016

A: You must quote the uri parameter. It contains a & which is being interpreted by whatever you are running mongoimport in.
So, replace this ...
mongoimport --uri mongodb://USER:SECRET@appname-shard-00-00-tlxyp.mongodb.net:27017,appname-shard-00-01-tlxyp.mongodb.net:27017,appname-shard-00-02-tlxyp.mongodb.net:27017/test?ssl=true&replicaSet=appname-shard-0&authSource=admin --collection scoringSystem --file /home/myUser/IdeaProjects/app/scoring-system.json

... with this:
mongoimport --uri "mongodb://USER:SECRET@appname-shard-00-00-tlxyp.mongodb.net:27017,appname-shard-00-01-tlxyp.mongodb.net:27017,appname-shard-00-02-tlxyp.mongodb.net:27017/test?ssl=true&replicaSet=appname-shard-0&authSource=admin" --collection scoringSystem --file /home/myUser/IdeaProjects/app/scoring-system.json

A: here is the connection string:
mongoimport --uri "mongodb+srv://testUser1:BtNuk3jO9myBOupf@rest.qks7o.mongodb.net/mainDB?retryWrites=true&w=majority" --collection dummyusers --file ./dummyusers.json --jsonArray

explanation:

*

*mongoimport = must have

*--uri =  must have before connection string

*"mongodb+srv.." = the connection string you use for connection to remote mongodb

*--collection dummyusers = is the name of the collection where you want your data to go, and you need --collection flag before it for it to work

*--file ./dummyusers.json =  is the file that you want to upload, MUST BE JSON, and make sure that you are in correct folder and path is correct

*--jsonArray = must have this flag, otherwise you will get "MongoDB Atlas mongoimport issues cannot decode array into a D" error

I made a whole video on my channel with link to code on how to setup the MongoDB localy, export data and import data into MongoDB remote, here is the video: https://youtu.be/I78wzFCXoqI


text:
Q: Oncreateview is not calling after addtobackstack As per fragment life cycle I am going like:
- Add fragment A + addToBackStack(null)
       |
- Add fragment B + addToBackStack(null)

and when I press back from B I expect Oncreateview should be call as per life cycle but it seems like : it just pop up back stage but no one method is call.so how can I identify back press in fragment A?
here is my simple code format:
// I am calling fragment like this way

      Fragment fragmentb=new FragmentB();
            FragmentManager fragmentManager=getFragmentManager();
            FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.fragment,fragmentb).addToBackStack(null);
            fragmentTransaction.commit();

A:       Fragment fragmentb=new FragmentB();
            FragmentManager fragmentManager=getFragmentManager();
            FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.fragment,fragmentb);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();


text:
Q: Fancy Box is not working with Box slider I am doing a project for one of my client. I am using box slider for the banner and it works fine. For a specific page on the website I am also trying to use fancy box for image light box.But It doesn't work however box slider is still working. Here is the head tag.

<link rel="stylesheet" type="text/css" href="js/jquery.fancybox.css?v=2.1.5" media="screen" />

<link href="css/jquery.bxslider.css" rel="stylesheet" />

And here is the the element where I am trying to use fancy box

when I disable box slider fancy box works. But when it is active fancy box doesn't work. Please help asap.Thanks


text:
Q: Combining multiple similar items on the Launcher I can't find this, but it could be I'm not sure how to search for it. I have a lot of icons in my Launcher. Is there a way to combine some, i.e. Firefox and Chrome or LibreOffice and gedit or graphics editors in one "folder"?

A: The magic word is 'Drawers'

A utility for organizing related items for easy launching from the
  Unity dock. Drawers creates a launcher for the Unity panel that can
  contain any combination of files, web links or directories. Just drop
  a file on the launcher and it will be added. Left-clicking the
  launcher "opens a drawer" with an icon view of each item for
  launching. Right-clicking allows fast launching through quicklists.

https://launchpad.net/~ian-berke/+archive/ppa-drawers
To install through Terminal:
sudo add-apt-repository ppa:ian-berke/ppa-drawers
sudo apt-get update
sudo apt-get install drawers

You can see Drawers in action on YouTube
More info on WebUpd8


text:
Q: Unable to instantiate application - java.lang.ClassNotFoundException: Didn't find class "com.xxxxx.App" on path: /data/app/com.xxxxx-1.apk This is the error everytime I run the app:
    E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate application com.xxxxx.App: java.lang.ClassNotFoundException: Didn't find class "com.xxxxx.App" on path: /data/app/com.xxxxx-1.apk
    at android.app.LoadedApk.makeApplication(LoadedApk.java:509)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4657)
    at android.app.ActivityThread.access$1400(ActivityThread.java:159)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:176)
    at android.app.ActivityThread.main(ActivityThread.java:5419)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.xxxxx.App" on path: /data/app/com.xxxxx-1.apk
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:64)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    at android.app.Instrumentation.newApplication(Instrumentation.java:992)
    at android.app.LoadedApk.makeApplication(LoadedApk.java:504)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4657)
    at android.app.ActivityThread.access$1400(ActivityThread.java:159)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:176)
    at android.app.ActivityThread.main(ActivityThread.java:5419)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
    at dalvik.system.NativeStart.main(Native Method)

Here some info:
JavaVersion.VERSION_1_8        (I cannot use 1.7 because of a library)
buildToolsVersion '24.0.0'
compileSdkVersion & target 24  (also tried 23)
gradle 2.2.0-alpha4            (also tried with 2.1.0)

I have instant run disabled.
I have a class named App that extends Application, so in AndroidManifest.xml I have <application android:name="com.xxxxx.App"
Please don't mark this question as duplicate, because I have already tried all the solutions given, but I cannot get rid of this error.

A: I was having the same error and just cleaning the project solve it for me.
it seems a bug in the new version of android studio.

A: remove the app from your mobile phone then build => clean project and try installing again

A: Have you tried running the app on another device/emulator?
I experienced this problem once because I was the 2nd user on the device that I was trying to run it on. If that's the case, you will have to switch to the primary user(owner) every time you wish to run your app.

A: I was having the same issue, then tried creating the same application class in java instead of kotlin and it worked.


text:
Q: Error on site using CI v 1.0 I have a site build using Codeiginiter 1.0. It was crowdfunding site and using wepay auth. When user register it was redirect to wepay landing and after loging in to wepay it was redirect back to home page. But now an error appear.
A PHP Error was encountered

Severity: Notice

Message: Undefined property: stdClass::$account_uri

Filename: controllers/home.php

Line Number: 114
A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /home/content/x/e/b/xebragroup3/html/ext_domains/undercoverfunder/system/core/Exceptions.php:185)

Filename: libraries/Session.php

Line Number: 675

Here is home.php
    <?php  if (! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
        $this->load->library('form_validation');
        $this->load->library('session');
        $this->load->library('pagination');
        $this->load->library('email');
        $this->load->model('home_model');
        $this->load->model('search_model');
        $this->load->helper('wepay');
        $this->load->library('tank_auth');
        $this->lang->load('tank_auth');
    }

    function index()
   {

    $data['categories']= $this->home_model->getallCategories();
    $data['home_active']='active';
    $per_page = 12;
                    if($this->uri->segment(3)==''){ $off = 0; }else{ $off = $this->uri->segment(3); }
                        $result = $this->home_model->count_getallprojects();
                        $base_url = base_url().'/home/index/';
                        $data['projects'] = $this->home_model->getallprojects($off,$per_page);
                        $config['uri_segment']          = '3';

                        $total  = count($result);

                            //code for pagging
                            $config['base_url']                 = $base_url;
                            $config['total_rows']           = $total;
                            $config['per_page']                 = $per_page;
                            $config['full_tag_open'] = '';
                            $config['full_tag_close'] = '';
                            $config['cur_tag_open'] = '';
                            $config['cur_tag_close'] = '';
                            $config['first_link'] = '« First';
                            $config['last_link'] = ' Last »';
                            $config['last_tag_open'] = '';
                            $config['last_tag_close'] = '';
                            $config['next_link'] = 'Next';
                            $config['next_tag_open'] = '';
                            $config['next_tag_close'] = '';
                            $config['prev_link'] = 'Prev';
                            $config['prev_tag_open'] = '';
                            $config['prev_tag_close'] = '';

                            $this->load->library('pagination',$result);
                            $this->pagination->initialize($config);

                        $this->load->view('frontend/home/home_view',$data);
    }

function wepay()
{
        if(isset($_GET['code']))
     {

                            $url = wepayurl.$_GET['code'];
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5');
                            $response = curl_exec($ch);
                            curl_close($ch);
                            $response_r = json_decode($response);
                            if(isset($response_r))
                            {
                                if (!$this->tank_auth->is_logged_in())  {
                                            //before login
                                            $user_id = $this->session->userdata('ses_userid_lf');
                                            $user_fname= $this->session->userdata('ses_name_lf');
                                }
                                else
                                {           //after login
                                            $user_id = $this->session->userdata('user_id');
                                            $user_fname = $this->session->userdata('front_username');
                                }

                                $data_wepay = array('user_id'=>$user_id,'wepay_user_id'=>$response_r->user_id,'wepay_user_access_token'=>$response_r->access_token);
                               $this->db->insert('wc_wepay_user_account_dtls',$data_wepay);

                                    $client_id = wepay_clientid;
                                $client_secret = wepay_scrite;

                                    $access_token = $response_r->access_token;
                                // change to useProduction for live environments
                                    //Wepay::useStaging($client_id, $client_secret);
                                    Wepay::useProduction($client_id, $client_secret);
                                    $wepay = new WePay($access_token);
                                    $res = $wepay->request('account/create/', array(
                                            'name'          => $user_fname,
                                            'description'   => 'Subscribed to Letsfund.it.'
                                ));

                                    if(!empty($res))
                                    {

                                        if (!$this->tank_auth->is_logged_in())  { $user_id =  $this->session->userdata('ses_userid_lf');    }
                                        else
                                        {   $user_id = $this->session->userdata('user_id');}

                                        $currdate = date('Y-m-d h:i:s');
                                        $data = array('account_uri'=>$res->account_uri,'account_id'=>$res->account_id,'dt_created'=>$currdate);
                                        $this->db->where('user_id',$user_id);
                                        $this->db->update('wc_wepay_user_account_dtls',$data);

                                        if (!$this->tank_auth->is_logged_in())  {
                                        $this->session->set_flashdata('message','You have successfully registered. Check your email address to activate your account.');
                                            //redirect('auth/register');
                                        }
                                        else{
                                            $this->session->set_flashdata('message','You have successfully given permitted Undercoverfunder to manage your wepay account.');
                                                //redirect('campaign');
                                            }
                                    }
                }
        }
        if(isset($_GET['error']))
        {

            $this->session->set_flashdata('msg','You denied the request so your account is not activated.');
            //redirect('auth/register');
        }
    } //end function

 }

Session.php :
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package     CodeIgniter
 * @author      ExpressionEngine Dev Team
 * @copyright   Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license     http://codeigniter.com/user_guide/license.html
 * @link        http://codeigniter.com
 * @since       Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Session Class
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Sessions
 * @author      ExpressionEngine Dev Team
 * @link        http://codeigniter.com/user_guide/libraries/sessions.html
 */
class CI_Session {

    var $sess_encrypt_cookie        = FALSE;
    var $sess_use_database          = FALSE;
    var $sess_table_name            = '';
    var $sess_expiration            = 7200;
    var $sess_expire_on_close       = FALSE;
    var $sess_match_ip              = FALSE;
    var $sess_match_useragent       = TRUE;
    var $sess_cookie_name           = 'ci_session';
    var $cookie_prefix              = '';
    var $cookie_path                = '';
    var $cookie_domain              = '';
    var $cookie_secure              = FALSE;
    var $sess_time_to_update        = 300;
    var $encryption_key             = '';
    var $flashdata_key              = 'flash';
    var $time_reference             = 'time';
    var $gc_probability             = 5;
    var $userdata                   = array();
    var $CI;
    var $now;

    /**
     * Session Constructor
     *
     * The constructor runs the session routines automatically
     * whenever the class is instantiated.
     */
    public function __construct($params = array())
    {
        log_message('debug', "Session Class Initialized");

        // Set the super object to a local variable for use throughout the class
        $this->CI =& get_instance();

        // Set all the session preferences, which can either be set
        // manually via the $params array above or via the config file
        foreach (array('sess_encrypt_cookie', 'sess_use_database', 'sess_table_name', 'sess_expiration', 'sess_expire_on_close', 'sess_match_ip', 'sess_match_useragent', 'sess_cookie_name', 'cookie_path', 'cookie_domain', 'cookie_secure', 'sess_time_to_update', 'time_reference', 'cookie_prefix', 'encryption_key') as $key)
        {
            $this->$key = (isset($params[$key])) ? $params[$key] : $this->CI->config->item($key);
        }

        if ($this->encryption_key == '')
        {
            show_error('In order to use the Session class you are required to set an encryption key in your config file.');
        }

        // Load the string helper so we can use the strip_slashes() function
        $this->CI->load->helper('string');

        // Do we need encryption? If so, load the encryption class
        if ($this->sess_encrypt_cookie == TRUE)
        {
            $this->CI->load->library('encrypt');
        }

        // Are we using a database?  If so, load it
        if ($this->sess_use_database === TRUE AND $this->sess_table_name != '')
        {
            $this->CI->load->database();
        }

        // Set the "now" time.  Can either be GMT or server time, based on the
        // config prefs.  We use this to set the "last activity" time
        $this->now = $this->_get_time();

        // Set the session length. If the session expiration is
        // set to zero we'll set the expiration two years from now.
        if ($this->sess_expiration == 0)
        {
            $this->sess_expiration = (60*60*24*365*2);
        }

        // Set the cookie name
        $this->sess_cookie_name = $this->cookie_prefix.$this->sess_cookie_name;

        // Run the Session routine. If a session doesn't exist we'll
        // create a new one.  If it does, we'll update it.
        if ( ! $this->sess_read())
        {
            $this->sess_create();
        }
        else
        {
            $this->sess_update();
        }

        // Delete 'old' flashdata (from last request)
        $this->_flashdata_sweep();

        // Mark all new flashdata as old (data will be deleted before next request)
        $this->_flashdata_mark();

        // Delete expired sessions if necessary
        $this->_sess_gc();

        log_message('debug', "Session routines successfully run");
    }

    // --------------------------------------------------------------------

    /**
     * Fetch the current session data if it exists
     *
     * @access  public
     * @return  bool
     */
    function sess_read()
    {
        // Fetch the cookie
        $session = $this->CI->input->cookie($this->sess_cookie_name);

        // No cookie?  Goodbye cruel world!...
        if ($session === FALSE)
        {
            log_message('debug', 'A session cookie was not found.');
            return FALSE;
        }

        // Decrypt the cookie data
        if ($this->sess_encrypt_cookie == TRUE)
        {
            $session = $this->CI->encrypt->decode($session);
        }
        else
        {
            // encryption was not used, so we need to check the md5 hash
            $hash    = substr($session, strlen($session)-32); // get last 32 chars
            $session = substr($session, 0, strlen($session)-32);

            // Does the md5 hash match?  This is to prevent manipulation of session data in userspace
            if ($hash !==  md5($session.$this->encryption_key))
            {
                log_message('error', 'The session cookie data did not match what was expected. This could be a possible hacking attempt.');
                $this->sess_destroy();
                return FALSE;
            }
        }

        // Unserialize the session array
        $session = $this->_unserialize($session);

        // Is the session data we unserialized an array with the correct format?
        if ( ! is_array($session) OR ! isset($session['session_id']) OR ! isset($session['ip_address']) OR ! isset($session['user_agent']) OR ! isset($session['last_activity']))
        {
            $this->sess_destroy();
            return FALSE;
        }

        // Is the session current?
        if (($session['last_activity'] + $this->sess_expiration) < $this->now)
        {
            $this->sess_destroy();
            return FALSE;
        }

        // Does the IP Match?
        if ($this->sess_match_ip == TRUE AND $session['ip_address'] != $this->CI->input->ip_address())
        {
            $this->sess_destroy();
            return FALSE;
        }

        // Does the User Agent Match?
        if ($this->sess_match_useragent == TRUE AND trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 120)))
        {
            $this->sess_destroy();
            return FALSE;
        }

        // Is there a corresponding session in the DB?
        if ($this->sess_use_database === TRUE)
        {
            $this->CI->db->where('session_id', $session['session_id']);

            if ($this->sess_match_ip == TRUE)
            {
                $this->CI->db->where('ip_address', $session['ip_address']);
            }

            if ($this->sess_match_useragent == TRUE)
            {
                $this->CI->db->where('user_agent', $session['user_agent']);
            }

            $query = $this->CI->db->get($this->sess_table_name);

            // No result?  Kill it!
            if ($query->num_rows() == 0)
            {
                $this->sess_destroy();
                return FALSE;
            }

            // Is there custom data?  If so, add it to the main session array
            $row = $query->row();
            if (isset($row->user_data) AND $row->user_data != '')
            {
                $custom_data = $this->_unserialize($row->user_data);

                if (is_array($custom_data))
                {
                    foreach ($custom_data as $key => $val)
                    {
                        $session[$key] = $val;
                    }
                }
            }
        }

        // Session is valid!
        $this->userdata = $session;
        unset($session);

        return TRUE;
    }

    // --------------------------------------------------------------------

    /**
     * Write the session data
     *
     * @access  public
     * @return  void
     */
    function sess_write()
    {
        // Are we saving custom data to the DB?  If not, all we do is update the cookie
        if ($this->sess_use_database === FALSE)
        {
            $this->_set_cookie();
            return;
        }

        // set the custom userdata, the session data we will set in a second
        $custom_userdata = $this->userdata;
        $cookie_userdata = array();

        // Before continuing, we need to determine if there is any custom data to deal with.
        // Let's determine this by removing the default indexes to see if there's anything left in the array
        // and set the session data while we're at it
        foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
        {
            unset($custom_userdata[$val]);
            $cookie_userdata[$val] = $this->userdata[$val];
        }

        // Did we find any custom data?  If not, we turn the empty array into a string
        // since there's no reason to serialize and store an empty array in the DB
        if (count($custom_userdata) === 0)
        {
            $custom_userdata = '';
        }
        else
        {
            // Serialize the custom data array so we can store it
            $custom_userdata = $this->_serialize($custom_userdata);
        }

        // Run the update query
        $this->CI->db->where('session_id', $this->userdata['session_id']);
        $this->CI->db->update($this->sess_table_name, array('last_activity' => $this->userdata['last_activity'], 'user_data' => $custom_userdata));

        // Write the cookie.  Notice that we manually pass the cookie data array to the
        // _set_cookie() function. Normally that function will store $this->userdata, but
        // in this case that array contains custom data, which we do not want in the cookie.
        $this->_set_cookie($cookie_userdata);
    }

    // --------------------------------------------------------------------

    /**
     * Create a new session
     *
     * @access  public
     * @return  void
     */
    function sess_create()
    {
        $sessid = '';
        while (strlen($sessid) < 32)
        {
            $sessid .= mt_rand(0, mt_getrandmax());
        }

        // To make the session ID even more secure we'll combine it with the user's IP
        $sessid .= $this->CI->input->ip_address();

        $this->userdata = array(
                            'session_id'    => md5(uniqid($sessid, TRUE)),
                            'ip_address'    => $this->CI->input->ip_address(),
                            'user_agent'    => substr($this->CI->input->user_agent(), 0, 120),
                            'last_activity' => $this->now,
                            'user_data'     => ''
                            );

        // Save the data to the DB if needed
        if ($this->sess_use_database === TRUE)
        {
            $this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->userdata));
        }

        // Write the cookie
        $this->_set_cookie();
    }

    // --------------------------------------------------------------------

    /**
     * Update an existing session
     *
     * @access  public
     * @return  void
     */
    function sess_update()
    {
        // We only update the session every five minutes by default
        if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
        {
            return;
        }

        // Save the old session id so we know which record to
        // update in the database if we need it
        $old_sessid = $this->userdata['session_id'];
        $new_sessid = '';
        while (strlen($new_sessid) < 32)
        {
            $new_sessid .= mt_rand(0, mt_getrandmax());
        }

        // To make the session ID even more secure we'll combine it with the user's IP
        $new_sessid .= $this->CI->input->ip_address();

        // Turn it into a hash
        $new_sessid = md5(uniqid($new_sessid, TRUE));

        // Update the session data in the session data array
        $this->userdata['session_id'] = $new_sessid;
        $this->userdata['last_activity'] = $this->now;

        // _set_cookie() will handle this for us if we aren't using database sessions
        // by pushing all userdata to the cookie.
        $cookie_data = NULL;

        // Update the session ID and last_activity field in the DB if needed
        if ($this->sess_use_database === TRUE)
        {
            // set cookie explicitly to only have our session data
            $cookie_data = array();
            foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
            {
                $cookie_data[$val] = $this->userdata[$val];
            }

            $this->CI->db->query($this->CI->db->update_string($this->sess_table_name, array('last_activity' => $this->now, 'session_id' => $new_sessid), array('session_id' => $old_sessid)));
        }

        // Write the cookie
        $this->_set_cookie($cookie_data);
    }

    // --------------------------------------------------------------------

    /**
     * Destroy the current session
     *
     * @access  public
     * @return  void
     */
    function sess_destroy()
    {
        // Kill the session DB row
        if ($this->sess_use_database === TRUE && isset($this->userdata['session_id']))
        {
            $this->CI->db->where('session_id', $this->userdata['session_id']);
            $this->CI->db->delete($this->sess_table_name);
        }

        // Kill the cookie
        setcookie(
                    $this->sess_cookie_name,
                    addslashes(serialize(array())),
                    ($this->now - 31500000),
                    $this->cookie_path,
                    $this->cookie_domain,
                    0
                );

        // Kill session data
        $this->userdata = array();
    }

    // --------------------------------------------------------------------

    /**
     * Fetch a specific item from the session array
     *
     * @access  public
     * @param   string
     * @return  string
     */
    function userdata($item)
    {
        return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item];
    }

    // --------------------------------------------------------------------

    /**
     * Fetch all session data
     *
     * @access  public
     * @return  array
     */
    function all_userdata()
    {
        return $this->userdata;
    }

    // --------------------------------------------------------------------

    /**
     * Add or change data in the "userdata" array
     *
     * @access  public
     * @param   mixed
     * @param   string
     * @return  void
     */
    function set_userdata($newdata = array(), $newval = '')
    {
        if (is_string($newdata))
        {
            $newdata = array($newdata => $newval);
        }

        if (count($newdata) > 0)
        {
            foreach ($newdata as $key => $val)
            {
                $this->userdata[$key] = $val;
            }
        }

        $this->sess_write();
    }

    // --------------------------------------------------------------------

    /**
     * Delete a session variable from the "userdata" array
     *
     * @access  array
     * @return  void
     */
    function unset_userdata($newdata = array())
    {
        if (is_string($newdata))
        {
            $newdata = array($newdata => '');
        }

        if (count($newdata) > 0)
        {
            foreach ($newdata as $key => $val)
            {
                unset($this->userdata[$key]);
            }
        }

        $this->sess_write();
    }

    // ------------------------------------------------------------------------

    /**
     * Add or change flashdata, only available
     * until the next request
     *
     * @access  public
     * @param   mixed
     * @param   string
     * @return  void
     */
    function set_flashdata($newdata = array(), $newval = '')
    {
        if (is_string($newdata))
        {
            $newdata = array($newdata => $newval);
        }

        if (count($newdata) > 0)
        {
            foreach ($newdata as $key => $val)
            {
                $flashdata_key = $this->flashdata_key.':new:'.$key;
                $this->set_userdata($flashdata_key, $val);
            }
        }
    }

    // ------------------------------------------------------------------------

    /**
     * Keeps existing flashdata available to next request.
     *
     * @access  public
     * @param   string
     * @return  void
     */
    function keep_flashdata($key)
    {
        // 'old' flashdata gets removed.  Here we mark all
        // flashdata as 'new' to preserve it from _flashdata_sweep()
        // Note the function will return FALSE if the $key
        // provided cannot be found
        $old_flashdata_key = $this->flashdata_key.':old:'.$key;
        $value = $this->userdata($old_flashdata_key);

        $new_flashdata_key = $this->flashdata_key.':new:'.$key;
        $this->set_userdata($new_flashdata_key, $value);
    }

    // ------------------------------------------------------------------------

    /**
     * Fetch a specific flashdata item from the session array
     *
     * @access  public
     * @param   string
     * @return  string
     */
    function flashdata($key)
    {
        $flashdata_key = $this->flashdata_key.':old:'.$key;
        return $this->userdata($flashdata_key);
    }

    // ------------------------------------------------------------------------

    /**
     * Identifies flashdata as 'old' for removal
     * when _flashdata_sweep() runs.
     *
     * @access  private
     * @return  void
     */
    function _flashdata_mark()
    {
        $userdata = $this->all_userdata();
        foreach ($userdata as $name => $value)
        {
            $parts = explode(':new:', $name);
            if (is_array($parts) && count($parts) === 2)
            {
                $new_name = $this->flashdata_key.':old:'.$parts[1];
                $this->set_userdata($new_name, $value);
                $this->unset_userdata($name);
            }
        }
    }

    // ------------------------------------------------------------------------

    /**
     * Removes all flashdata marked as 'old'
     *
     * @access  private
     * @return  void
     */

    function _flashdata_sweep()
    {
        $userdata = $this->all_userdata();
        foreach ($userdata as $key => $value)
        {
            if (strpos($key, ':old:'))
            {
                $this->unset_userdata($key);
            }
        }

    }

    // --------------------------------------------------------------------

    /**
     * Get the "now" time
     *
     * @access  private
     * @return  string
     */
    function _get_time()
    {
        if (strtolower($this->time_reference) == 'gmt')
        {
            $now = time();
            $time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now));
        }
        else
        {
            $time = time();
        }

        return $time;
    }

    // --------------------------------------------------------------------

    /**
     * Write the session cookie
     *
     * @access  public
     * @return  void
     */
    function _set_cookie($cookie_data = NULL)
    {
        if (is_null($cookie_data))
        {
            $cookie_data = $this->userdata;
        }

        // Serialize the userdata for the cookie
        $cookie_data = $this->_serialize($cookie_data);

        if ($this->sess_encrypt_cookie == TRUE)
        {
            $cookie_data = $this->CI->encrypt->encode($cookie_data);
        }
        else
        {
            // if encryption is not used, we provide an md5 hash to prevent userside tampering
            $cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key);
        }

        $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time();

        // Set the cookie
        setcookie(
                    $this->sess_cookie_name,
                    $cookie_data,
                    $expire,
                    $this->cookie_path,
                    $this->cookie_domain,
                    $this->cookie_secure
        );
    }

    // --------------------------------------------------------------------

    /**
     * Serialize an array
     *
     * This function first converts any slashes found in the array to a temporary
     * marker, so when it gets unserialized the slashes will be preserved
     *
     * @access  private
     * @param   array
     * @return  string
     */
    function _serialize($data)
    {
        if (is_array($data))
        {
            foreach ($data as $key => $val)
            {
                if (is_string($val))
                {
                    $data[$key] = str_replace('\\', '{{slash}}', $val);
                }
            }
        }
        else
        {
            if (is_string($data))
            {
                $data = str_replace('\\', '{{slash}}', $data);
            }
        }

        return serialize($data);
    }

    // --------------------------------------------------------------------

    /**
     * Unserialize
     *
     * This function unserializes a data string, then converts any
     * temporary slash markers back to actual slashes
     *
     * @access  private
     * @param   array
     * @return  string
     */
    function _unserialize($data)
    {
        $data = @unserialize(strip_slashes($data));

        if (is_array($data))
        {
            foreach ($data as $key => $val)
            {
                if (is_string($val))
                {
                    $data[$key] = str_replace('{{slash}}', '\\', $val);
                }
            }

            return $data;
        }

        return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
    }

    // --------------------------------------------------------------------

    /**
     * Garbage collection
     *
     * This deletes expired session rows from database
     * if the probability percentage is met
     *
     * @access  public
     * @return  void
     */
    function _sess_gc()
    {
        if ($this->sess_use_database != TRUE)
        {
            return;
        }

        srand(time());
        if ((rand() % 100) < $this->gc_probability)
        {
            $expire = $this->now - $this->sess_expiration;

            $this->CI->db->where("last_activity < {$expire}");
            $this->CI->db->delete($this->sess_table_name);

            log_message('debug', 'Session garbage collection performed.');
        }
    }
}
// END Session Class

/* End of file Session.php */
/* Location: ./system/libraries/Session.php */