text:
Q: How do I use ServiceStack from a strongly named host? I have a code base which requires strong names.
At first, I thought this was going to be an easy fix, as I simply assigned strong names to the ServiceStack assemblies I needed.  This failed due to inter-dependencies within ServiceStack on weak named assemblies.  Then, I bit the bullet and recompiled ServiceStack using my key file - which was undesirable as I didn't see a means by which this could be done in a single location and had to add it to each project.
Even then, the solution failed to build with the tests due to this:
[assembly: InternalsVisibleTo("ServiceStack.Common.Tests")]

I'm finding myself in a downward spiral of having to tweak things to get them to work and taking myself further and further away from source libraries I'd like to keep updated.
How should I approach this problem?  I don't like where this is going...

A: It may not solve your problem, as this is not 100% reliable (although, if it works fine on one host it will work on all hosts - so if you have good test coverage you can at least make sure it worked fine).
LibZ (disclaimer: LibZ.Author = Me) has a function sign-and-fix which finds unsigned assemblies, traverses assembly tree bottom-up and replaces all assembly references to this "new" signed assemblies.
Link:
https://libz.codeplex.com/wikipage?title=Signing%20assemblies&referringTitle=Documentation

A: Could you just the signed version that is available in nuget?


text:
Q: cant get jquery href value into input box I have been trying to create a rough autocomplete input box and am almost there. However, getting stuck at a certain point. Do check the code before i identify the problem.
JS

Some CSS

HTML
<input type="text" name="" id="cit" onkeyup="getres()">

Test 1
Test 2
Test 3

PHP (results.php)
 <?php
if(isset($_GET['cit'])){$cit= $_GET['cit'];}
include('connnew.php');
$getprops=$clientdb->query("SELECT * FROM cities WHERE city LIKE '%$cit%'")  or die ($clientdb->error);
while($info=$getprops->fetch_assoc()){

       echo "$info[city]
";

    //echo "$info[city]
";
}
?>

My problem is, though everything works, when I click on the hrefs Tes1, Test2 and Test3, the input box #cit gets filled with the value, but not the values of href populated by the PHP into the same #resdiv !
Why is it so ? WIll the click function of jquery work only on hrefs written as text ? And not on the populated hrefs ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Symfony2 + Doctrine2 - select on many to many relationship I have problem with selecting data from DB with many to many relationship.
I have news on page. Each news, in spite of other fields, have two interesting cols - type (string) and category. Each news can have many categories. I have no problem with saving news with many categories when adding in admin. But then - we have users who log in on page and each user have assigned categories. When user is logged in and have assigned categories, I should take from DB only news with user selected categories and other news (type != 'news').
News.php entity
/**
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Category", inversedBy="news")
 * @ORM\JoinTable(name="news_categories")
 */
private $categories;

Category.php entity
/**
 *
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\News", mappedBy="category")
 */
private $news;

I'm collecting news in news repository:
$query = $this->createQueryBuilder('p');
    if($user->hasCategories()) {
        $query
            ->innerJoin('p.category', 'c')
            ->andWhere('p.type != :paramType OR (c.id IN (:categoryIds) AND p.type = :paramType)')
            ->setParameter(':categoryIds', $categories)
            ->setParameter(':paramType', 'news');
    }
    $result = $query->getQuery()->getResult();

When I log in with user with no categories assigned - I'm getting all news. Not going into "if" statement, it works just fine.
When I'm logged in with user with assigned categories, I'm getting only news with type "news" with user assigned categories, but no other news (with type != 'news').
What am I doing wrong?
Once again, goal is to get all data from news table if user with no assigned categories (no problem) and take only news with type = 'news' and defined categories if logged in user has assigned categories.
Thanks.


text:
Q: Getting names of directories under given path I am trying to get the names of all first level  directories under given path.
I tried to use File::Find but had problems.
Can someone help me with that?

A: If you don't need to traverse the entire directory hierarchy, File::Slurp is much easier to use than File::Find.
use strict;
use warnings;
use File::Slurp qw( read_dir );
use File::Spec::Functions qw( catfile );

my $path = shift @ARGV;
my @sub_dirs = grep { -d } map { catfile $path, $_ } read_dir $path;
print $_, "\n" for @sub_dirs;

And if you ever do need to traverse a hierarchy, check CPAN for friendlier alternatives to File::Find.

*

*File::Finder and File::Find::Rule are front-ends for File::Find.

*File::Find::Closures is worth studying to learn how to use File::Find and how
to write closures.

*File::Next uses an iterator approach to directory traversal and
looks promising, although I have never used it.
Finally, in the spirit of TIMTOWTDI, here's something quick and sleazy:
my @sub_dirs = grep {-d} glob("$ARGV[0]/*");

A: use File::Spec::Functions qw( catfile );

my ($path) = @ARGV;

opendir my $DIR, $path
    or die "Cannot open directory: '$path': $!";

while ( my $entry = readdir $DIR ) {
    next if $entry =~ /\A\.\.?\z/;
    next unless -d catfile $path, $entry;
    print $entry, "\n";
}

closedir $DIR;

This worked for me.

A: Use the-d file check operator:
#!/usr/bin/perl

use strict;
use warnings;
use autodie;

my $path = $ARGV[0];
die "Please specify which directory to search"
    unless -d $path;

opendir( my $DIR, $path );
while ( my $entry = readdir $DIR ) {
    next unless -d $path . '/' . $entry;
    next if $entry eq '.' or $entry eq '..';
    print "Found directory $entry\n";
}
closedir $DIR;

A: I'm running ActivePerl 5.10.1 under Windows XP. If I wanted to get all the names of the directories under the root drive F. I would use the following code:
#!perl
opendir (DIR,'F:/');
my @folder = readdir(DIR);
foreach my $f (@folder)
{
   next if ($f =~ /\./);
   print "$f\n";
 }

Well, this usually works because my folder names do not contain the dot. Otherwise it fails.
Okay, it seems that even my method works for my case, people would still downvote because it is faulty. So I'd have to use the official approach, the -d flag to check if a file is a directory:
The upgraded code:
#!perl
use strict;
use warnings;

opendir (DIR, "F:/");
my @files = readdir(DIR);
my @dirs = grep { -d } @files;
print @dirs;

A: Use opendir and -d.

A: you can use find2perl to translate your find command to perl. See perldoc find2perl for more info.
Workaround of maxdepth: (reference from Randall)
$  find2perl /home/path -type d -eval 'my $slashes = $File::Find::name =~ tr#/##;return $File::Find::prune = 1 if $slashes > 2;return if $slashes ==2'

Code:
   use strict;
    use File::Find ();
    use vars qw/*name *dir *prune/;
    *name   = *File::Find::name;
    *dir    = *File::Find::dir;
    *prune  = *File::Find::prune;
    sub wanted;

    File::Find::find({wanted => \&wanted}, '/');
    exit;
    sub wanted {
        eval { my $slashes = $File::Find::name =~ tr#/##;return $File::Find::prune = 1 if $slashes > 1;return if $slashes ==1 };
        if ( $? == "0" && -d _  ){
            print "$name --- \n";
        }
    }

output
$ pwd
/temp

$ tree
.
|-- dir1
|   |-- subdir1
|   |   |-- subsubdir1
|   |   `-- testsubdir1.txt
|   `-- testdir1.txt
|-- dir2
|   |-- subdir2
|   |   |-- subsubdir2
|   |   `-- testsubdir2.txt
|   `-- testdir2.txt
|-- dir3
|   `-- subdir3
|       `-- subsubdir3
`-- test

9 directories, 5 files

$ perl perl.pl
/temp ---
/temp/dir3 ---
/temp/dir1 ---
/temp/dir2 ---

A: Using File::Find::Rule
#!/usr/bin/perl --
use strict;
use warnings;

use Shell::Command qw( rm_rf touch mkpath );
use autodie;
use File::Find::Rule;

Main(@ARGV);
exit(0);

sub Main{
  use autodie;
  my $dir = "tmp";
  mkdir $dir;
#~   chdir $dir;
  mkpath "$dir/a/b/c/d";
  mkpath "$dir/as/b/c/d";
  mkpath "$dir/ar/b/c/d";

  print `tree`;
  print "---\n";
  print "$_\n"
    for File::Find::Rule->new->maxdepth(1)->directory->in($dir);

  print "---\n";

  print "$_\n"
    for grep -d, glob "$dir/*"; ## use forward slashes, See File::Glob

#~   chdir "..";
  rm_rf $dir;
}
__END__
.
|-- test.pl
`-- tmp
    |-- a
    |   `-- b
    |       `-- c
    |           `-- d
    |-- ar
    |   `-- b
    |       `-- c
    |           `-- d
    `-- as
        `-- b
            `-- c
                `-- d

13 directories, 1 file
---
tmp
tmp/a
tmp/ar
tmp/as
---
tmp/a
tmp/ar
tmp/as

Or using File::Find::Rule frontend findrule
$ findrule tmp -maxdepth ( 1 ) -directory
tmp
tmp/a
tmp/ar
tmp/as

A:  $path="/path/to/search";

 @files = `find $path -name myfile.name -type f`;
 print "@files\n";

A: You could use File::Find for that.  For example:
use File::Find ();

File::Find::find(\&wanted, '.');

sub wanted {
    if (-d) {
        print "$File::Find::name\n";
    }
}

For each file found under '.', this will call the wanted subroutine.  Inside the subroutine you can use -d to check for a directory.
File::Find:find descends to all subdirectories in the tree below the directory specified.


text:
Q: Overloading << operator - multiple parameters Many of you may know the following in C++:
cout << 1 << 2 << 3 << 4; // would produce 1234

I'm attempting to recreate the same thing - but instead encapsulate it into a class and increment the values into an integer variables.
I get the error:
error: 'int operator<<(const int&, const int&)' must have an argument of class or enumerated type|
class Test
{
private:
    int data;

public:
    Test() { data = 0; }
    void print() { cout << data; }

    friend int operator<<(const int &x, const int &y)
    {
        data += x;
        data += y;
    }
};

int main()
{
    Test a;
    a << 50 << 20;
    a.print();   //if I had only 1 parameter - it worked and printed out only 50
    return 0;
}

A: In a nutshell, the operator needs to return the Test instance:
class Test
{
    ...
    friend Test& operator<<(Test& test, int val);
};

Test& operator<<(Test& test, int val)
{
    test.data += val;
    return test;
}

A:
cout << 1 << 2 << 3 << 4;

This way this works is as a series of calls with two arguments e.g.
(((cout << 1) << 2) << 3) << 4;

Which is roughly equivalent to this:
cout << 1;
cout << 2;
cout << 3;
cout << 4;

So you don't write an operator<< taking multiple parameters, it always takes two operands, the left operand and the right operand. The left operand in the example above is cout i.e. the ostream and the right operand is the int being written to it.  The operator returns the left operand, allowing it to be used again in the next operation, and so on for as many << operations as you chain together.
So cout << 1 returns cout again, so that (cout << 1) << 2 invokes the operator to write 1 to the stream and return the stream, then invokes the operator again on the return value to write 2 to the stream and then returns the stream again.
This is just nonsense:
friend int operator<<(const int &x, const int &y)
{
    data += x;
    data += y;
}

Where is data supposed to come from?  A friend function is not a member of the class, so there is no this pointer, so no this->data, also you claim to return int but don't return anything, and this class is completely unrelated to Test. What you've written is an operator<< for two ints i.e. for doing 1 << 2 but that operator already exists, it's the bitshift operator, and you can't overload it for built-in types like int.
You want:
class Test
{
private:
    int data;

public:
    Test() { data = 0; }
    void print() { cout << data; }

    Test& operator<<(int y)
    {
        data += x;
        return *this;
    }
};

Or as a friend:
class Test
{
private:
    int data;

public:
    Test() { data = 0; }
    void print() { cout << data; }

    friend Test& operator<<(Test& t, int y)
    {
        t.data += x;
        return t;
    }
};


text:
Q: Rearranging equation with Sums Could anyone help me with rearranging the below to find $\mu$:
$$\sum^{N-1}_{n = 0}\frac{1}{\sigma_n^2}(x_n - \mu) = 0$$
The mark scheme for the question seems to rearrange the equation like this:
$$\sum_n\frac{x_n}{\sigma_n^2} = \mu\sum_n\sum_n\frac{1}{\sigma_n^2}$$
However, I have no clue why there is two sums on the right hand side, and why it doesn't just rearrange to $ \sum_n\frac{x_n}{\sigma_n^2} = \mu\sum_n\frac{1}{\sigma_n^2} $.
Thanks to anyone that can help me out.


text:
Q: Заносится пустая информация в БД В базу заносится пустая информация. Есть код, отправляющей информацию обработчику (метод пост), в обработчике эта информация заноситься в переменные. Если попробовать вывести переменный с echo, то ничего не выводит.
if (isset($_POST['name'])){$name =$_POST['name'];
} - заносим в переменную значение поля name. Почему информация заносится в БД как пустая?
A: Используйте !empty() вместо isset().


text:
Q: Why would a specific comparison return records from a SQL Server Stored Proc but an IN clause containing the same value return nothing? I have two Stored Procedures which are identical except for two things:
(a) One works (returns records) and the other doesn't (returns no records)
(b) The working one searches for a single match, whereas the nonworking one casts a wider net, including additional values in those being sought
The only differences (besides the SP names) between the two Stored Procedures are:
1)
Where the working Stored Proc contains this:
where UPPER(up.Unit) = 'ROCK BOTTOM'

...the nonworking Stored Proc contains this:
where UPPER(up.Unit) IN ('CHOPHOUSE', 'CRAFTWORKS SC', 'GORDON BIERSCH', 'OLD CHI FRANCHISE', 'OLD CHICAGO', 'ROCK BOTTOM')

2)
Where the working Stored Proc contains this:
where UPPER(up.Unit) = 'ROCK BOTTOM' and C.BeginDate <= @CalendarEndDate and C.EndDate >= @CalendarBegDate

...the nonworking Stored Proc contains this:
where UPPER(mp.Unit) IN ('CHOPHOUSE', 'CRAFTWORKS SC', 'GORDON BIERSCH', 'OLD CHI FRANCHISE', 'OLD CHICAGO', 'ROCK BOTTOM') and C.BeginDate <= @CalendarEndDate and C.EndDate >= @CalendarBegDate

3)
And finally, where the working Stored Proc contains this:
and Unit = ''ROCK BOTTOM'' and

...the nonworking Stored Proc contains this:
and Unit IN (''CHOPHOUSE'', ''CRAFTWORKS SC'', ''GORDON BIERSCH'', ''OLD CHI FRANCHISE'', ''OLD CHICAGO'', ''ROCK BOTTOM'') and

Why would searching for 'Rock Bottom' along with other values fail, while looking for that value alone succeed?
UPDATE
At commenter Kritner's request, here are the Stored Procs in their entirety; the first one is the one that works:
IF OBJECT_ID ( 'sp_ViewPriceMatrix_Variance_RockBottomRollup_RockBottom', 'P' ) IS NOT NULL
    DROP PROCEDURE sp_ViewPriceMatrix_Variance_RockBottomRollup_RockBottom;
GO
CREATE Procedure [dbo].[sp_ViewPriceMatrix_Variance_RockBottomRollup_RockBottom]
    @BegDate datetime,
    @EndDate datetime,
    @SortBy varchar(20)
AS
DECLARE
@SQLstring varchar(max),
@Statement varchar(8000),
@ShortName varchar(50),
@ItemCode varchar(25),
@PriceWeek varchar(30),
@LastPriceWeek varchar(30),
@Week int,
@WherePriceWeek varchar(2000),
@Price varchar(25),
@Contractprice int,
@CalendarBegDate datetime,
@CalendarEndDate datetime

create table #Temp
(
    Unit varchar(50),
    ShortName varchar(25),
    ItemCode varchar(50),
    Description varchar(250),
    regionorder int,
    Contractprice varchar(50),
    Price varchar(25),
    Variance varchar(25),
    PriceWeek varchar(50),
    Week varchar(10)
)

-- create temp table
Select up.Unit, mm.ShortName,
up.ItemCode, Description=(Select Description from MasterProducts where ItemCode=up.itemcode),
mm.regionorder, up.Contractprice
into #TempContract From UnitProducts up
Inner Join Unitmembers um on up.Unit=um.Unit and abs(um.pricesheet) = 1
Inner Join Members mm on um.memberno = mm.memberno
where UPPER(up.Unit) = 'ROCK BOTTOM'

Select @CalendarBegDate = C.BeginDate From Calendar C where @BegDate between C.BeginDate and C.EndDate
Select @CalendarEndDate = C.EndDate From Calendar C where @EndDate between C.BeginDate and C.EndDate

-- get weeks and where clause
SET @WherePriceWeek = ' Where '

Declare GetPriceWeek Cursor For
Select [PriceWeek] = C.Description, C.BeginDate
From Calendar C
where C.BeginDate <= @CalendarEndDate and C.EndDate >= @CalendarBegDate
Order By 2
Open GetPriceWeek
fetch next from GetPriceWeek into @PriceWeek, @BegDate
while @@fetch_status = 0
    begin
        Select @Statement = ('Alter Table #TempContract Add [' + @PriceWeek + '] numeric(8,2) ')
        exec (@Statement)
        IF(@WherePriceWeek<>' Where ')
        Begin
            SET @WherePriceWeek = @WherePriceWeek + 'or '
        End
        SET @WherePriceWeek = @WherePriceWeek + 'IsNull(['+@PriceWeek+'],''0.00'') <> ''999.99'' '
        fetch next from GetPriceWeek into @PriceWeek, @BegDate
    end
Close GetPriceWeek
Deallocate GetPriceWeek

-- build member data by weeks
Declare GetMemberColumns Cursor For
SELECT distinct ShortName,ItemCode
FROM #TempContract
Order by ShortName,ItemCode
Open GetMemberColumns
fetch next from GetMemberColumns into @ShortName,@ItemCode
while @@fetch_status = 0
    begin
        Declare GetMemberPrice Cursor For
        Select [PriceWeek] = C.Description, convert(varchar(20),
        cast(IsNull(mp.Price,0) as numeric(8,2))) as Price,
        up.Contractprice
        From MemberPrice mp
        Inner Join UnitProducts up on mp.unit=up.unit and mp.itemcode=up.itemcode
        Inner Join Unitmembers um on mp.memberno=um.memberno and mp.unit=um.unit and abs
(um.pricesheet) = 1
        Inner Join Members mm on mp.memberno = mm.memberno
        Inner Join Calendar C on mp.CYear=C.CYear and mp.Cweek=C.CWeek
        where UPPER(up.Unit) = 'ROCK BOTTOM' and C.BeginDate <= @CalendarEndDate and C.EndDate >=

@CalendarBegDate
and mm.ShortName = @ShortName and Mp.ItemCode = @ItemCode
        Open GetMemberPrice
        fetch next from GetMemberPrice into @PriceWeek,@Price,@Contractprice
        while @@fetch_status = 0
            begin
                Print(@Price)
                Select @Statement = ('Update #TempContract Set [' + @PriceWeek  + ']=''' +
IsNull(@Price,'0.00') + ''' where ItemCode=''' + @ItemCode + ''' and Unit = ''ROCK BOTTOM'' and
[ShortName]=''' + @ShortName +'''')
                exec (@Statement)
                fetch next from GetMemberPrice into @PriceWeek,@Price,@Contractprice
            end
        Close GetMemberPrice
        Deallocate GetMemberPrice

        fetch next from GetMemberColumns into @ShortName,@ItemCode
    end
Close GetMemberColumns
Deallocate GetMemberColumns

--Select * From #TempContract

-- final select statement
SET @Week = 0
SET @LastPriceWeek = ''
SET @SQLstring = ''

Declare SetPriceWeekSQL Cursor For
Select [PriceWeek] = C.Description, C.BeginDate
From Calendar C
where C.BeginDate between @CalendarBegDate and @CalendarEndDate
Order By 2
Open SetPriceWeekSQL
fetch next from SetPriceWeekSQL into @PriceWeek, @BegDate
while @@fetch_status = 0
    begin
        SET @Week = @Week + 1
        IF(@SQLstring='')
        Begin
            SET @SQLstring = @SQLstring + 'Insert Into #Temp Select Unit, ShortName, ItemCode,
Description, regionorder, Contractprice, IsNull('+
            '['+@PriceWeek+'],''0.00'') as Price, (convert(decimal(10,3),''-0.001'')) as
Variance,
            '''+@PriceWeek+''' as PriceWeek, ''WK'+convert(varchar(2),@Week)+''' as Week From
#TempContract'+@WherePriceWeek

            IF(@SortBy='Members')
            Begin
                SET @SQLstring = @SQLstring + ' UNION Select Unit, ShortName, '''',
''zzzz'', '''', '''', ''0'' as Price, ''-0.001'' as Variance, '''' as PriceWeek, ''WK'+convert(varchar
(2),@Week)+''' as Week From #TempContract'+@WherePriceWeek
            End
            Else
            Begin
                SET @SQLstring = @SQLstring + ' UNION Select Unit, '''', ItemCode,
Description, ''1000'', Contractprice, ''0'' as Price, ''-0.001'' as Variance, '''' as PriceWeek,
''WK'+convert(varchar(2),@Week)+''' as Week From #TempContract'+@WherePriceWeek
            End
        End
        ELSE
        Begin
            SET @SQLstring = @SQLstring + ' UNION '
            SET @SQLstring = @SQLstring + 'Select Unit, ShortName, ItemCode, Description,
regionorder, Contractprice, IsNull('+
            '['+@PriceWeek+'],''0.00'') as Price, IsNull(convert(decimal(10,2),['+@PriceWeek
+'])-convert(decimal(10,2),['+@LastPriceWeek+']),''0.00'') as Variance,
            '''+@PriceWeek+''' as PriceWeek, ''WK'+convert(varchar(2),@Week)+''' as Week From
#TempContract'+@WherePriceWeek

            IF(@SortBy='Members')
            Begin
                SET @SQLstring = @SQLstring + ' UNION Select Unit, ShortName, '''',
''zzzz'', '''', '''', ''0'' as Price, ''0'' as Variance, '''' as PriceWeek, ''WK'+convert(varchar
(2),@Week)+''' as Week From #TempContract Where IsNull(['+@LastPriceWeek+'],''0.00'') <> ''999.99'' or
IsNull(['+@PriceWeek+'],''0.00'') <> ''999.99'' '
            End
            Else
            Begin
                SET @SQLstring = @SQLstring + ' UNION Select Unit, '''', ItemCode,
Description, ''1000'', Contractprice, ''0'' as Price, ''0'' as Variance, '''' as PriceWeek, ''WK'+convert
(varchar(2),@Week)+''' as Week From #TempContract Where IsNull(['+@LastPriceWeek+'],''0.00'') <> ''999.99''
or IsNull(['+@PriceWeek+'],''0.00'') <> ''999.99'' '
            End
        End
        SET @LastPriceWeek = @PriceWeek
        fetch next from SetPriceWeekSQL into @PriceWeek, @BegDate
    end
Close SetPriceWeekSQL
Deallocate SetPriceWeekSQL

Print(@SQLstring)
Execute(@SQLstring)

Drop Table #TempContract

IF(@SortBy='Members')
Begin
    Select
        Unit,
        ShortName,
        ItemCode,
        Description,
        regionorder,
        Contractprice,
        convert(varchar(20),convert(decimal(10,2),Price)) as Price,
        sum(convert(money,Variance)) as Variance,
        VarianceAverage = convert(varchar(25),convert(decimal(10,2),(Select sum(convert
(money,Variance)) From #Temp Where ShortName=T.ShortName and Week=T.Week) / Replace(((Select count
(regionorder) From #Temp Where ShortName=T.ShortName and Week=T.Week)-count(Variance)),'0','1'))),
        PriceWeek,Week
    From #Temp T
    Group By
        Unit,
        ShortName,
        ItemCode,
        Description,
        regionorder,
        Contractprice,
        Price,
        PriceWeek,Week
    Order By Week,ShortName,Description
End
ELSE
Begin
    Select
        Unit,
        ShortName,
        ItemCode,
        Description,
        regionorder,
        Contractprice,
        convert(varchar(20),convert(decimal(10,2),Price)) as Price,
        sum(convert(money,Variance)) as Variance,
        VarianceAverage = convert(varchar(25),convert(decimal(10,2),(Select sum(convert
(money,Variance)) From #Temp Where ItemCode=T.ItemCode and Week=T.Week) / Replace(((Select count
(regionorder) From #Temp Where ItemCode=T.ItemCode and Week=T.Week)-count(Variance)),'0','1'))),
        PriceWeek,Week
    From #Temp T
    Group By
        Unit,
        ShortName,
        ItemCode,
        Description,
        regionorder,
        Contractprice,
        Price,
        PriceWeek,Week
    Order By Week,Description,regionorder
End

Drop Table #Temp

...and this is the one that returns nothing:
IF OBJECT_ID ( 'sp_ViewPriceMatrix_Variance_RockBottomExtended', 'P' ) IS NOT NULL
    DROP PROCEDURE sp_ViewPriceMatrix_Variance_RockBottomExtended;
GO
CREATE Procedure [dbo].[sp_ViewPriceMatrix_Variance_RockBottomExtended]
    @BegDate datetime,
    @EndDate datetime,
    @SortBy varchar(20)
AS
DECLARE
@SQLstring varchar(max),
@Statement varchar(8000),
@ShortName varchar(50),
@ItemCode varchar(25),
@PriceWeek varchar(30),
@LastPriceWeek varchar(30),
@Week int,
@WherePriceWeek varchar(2000),
@Price varchar(25),
@Contractprice int,
@CalendarBegDate datetime,
@CalendarEndDate datetime

create table #Temp
(
    Unit varchar(50),
    ShortName varchar(25),
    ItemCode varchar(50),
    Description varchar(250),
    regionorder int,
    Contractprice varchar(50),
    Price varchar(25),
    Variance varchar(25),
    PriceWeek varchar(50),
    Week varchar(10)
)

-- create temp table
Select up.Unit, mm.ShortName,
up.ItemCode, Description=(Select Description from MasterProducts where ItemCode=up.itemcode),
mm.regionorder, up.Contractprice
into #TempContract From UnitProducts up
Inner Join Unitmembers um on up.Unit=um.Unit and abs(um.pricesheet) = 1
Inner Join Members mm on um.memberno = mm.memberno
where UPPER(up.Unit) IN ('CHOPHOUSE', 'CRAFTWORKS SC', 'GORDON BIERSCH', 'OLD CHI FRANCHISE', 'OLD CHICAGO', 'ROCK BOTTOM')

Select @CalendarBegDate = C.BeginDate From Calendar C where @BegDate between C.BeginDate and C.EndDate
Select @CalendarEndDate = C.EndDate From Calendar C where @EndDate between C.BeginDate and C.EndDate

-- get weeks and where clause
SET @WherePriceWeek = ' Where '

Declare GetPriceWeek Cursor For
Select [PriceWeek] = C.Description, C.BeginDate
From Calendar C
where C.BeginDate <= @CalendarEndDate and C.EndDate >= @CalendarBegDate
Order By 2
Open GetPriceWeek
fetch next from GetPriceWeek into @PriceWeek, @BegDate
while @@fetch_status = 0
    begin
        Select @Statement = ('Alter Table #TempContract Add [' + @PriceWeek + '] numeric(8,2) ')
        exec (@Statement)
        IF(@WherePriceWeek<>' Where ')
        Begin
            SET @WherePriceWeek = @WherePriceWeek + 'or '
        End
        SET @WherePriceWeek = @WherePriceWeek + 'IsNull(['+@PriceWeek+'],''0.00'') <> ''999.99'' '
        fetch next from GetPriceWeek into @PriceWeek, @BegDate
    end
Close GetPriceWeek
Deallocate GetPriceWeek

-- build member data by weeks
Declare GetMemberColumns Cursor For
SELECT distinct ShortName,ItemCode
FROM #TempContract
Order by ShortName,ItemCode
Open GetMemberColumns
fetch next from GetMemberColumns into @ShortName,@ItemCode
while @@fetch_status = 0
    begin
        Declare GetMemberPrice Cursor For
        Select [PriceWeek] = C.Description, convert(varchar(20),
        cast(IsNull(mp.Price,0) as numeric(8,2))) as Price,
        up.Contractprice
        From MemberPrice mp
        Inner Join UnitProducts up on mp.unit=up.unit and mp.itemcode=up.itemcode
        Inner Join Unitmembers um on mp.memberno=um.memberno and mp.unit=um.unit and abs
(um.pricesheet) = 1
        Inner Join Members mm on mp.memberno = mm.memberno
        Inner Join Calendar C on mp.CYear=C.CYear and mp.Cweek=C.CWeek
        where UPPER(mp.Unit) IN ('CHOPHOUSE', 'CRAFTWORKS SC', 'GORDON BIERSCH', 'OLD CHI FRANCHISE', 'OLD CHICAGO', 'ROCK BOTTOM') and C.BeginDate <= @CalendarEndDate and C.EndDate >= @CalendarBegDate
and mm.ShortName = @ShortName and Mp.ItemCode = @ItemCode
        Open GetMemberPrice
        fetch next from GetMemberPrice into @PriceWeek,@Price,@Contractprice
        while @@fetch_status = 0
            begin
                Print(@Price)
                Select @Statement = ('Update #TempContract Set [' + @PriceWeek  + ']=''' +
IsNull(@Price,'0.00') + ''' where ItemCode=''' + @ItemCode + ''' and Unit IN (''CHOPHOUSE'', ''CRAFTWORKS SC'', ''GORDON BIERSCH'', ''OLD CHI FRANCHISE'', ''OLD CHICAGO'', ''ROCK BOTTOM'') and
[ShortName]=''' + @ShortName +'''')
                exec (@Statement)
                fetch next from GetMemberPrice into @PriceWeek,@Price,@Contractprice
            end
        Close GetMemberPrice
        Deallocate GetMemberPrice

        fetch next from GetMemberColumns into @ShortName,@ItemCode
    end
Close GetMemberColumns
Deallocate GetMemberColumns

--Select * From #TempContract

-- final select statement
SET @Week = 0
SET @LastPriceWeek = ''
SET @SQLstring = ''

Declare SetPriceWeekSQL Cursor For
Select [PriceWeek] = C.Description, C.BeginDate
From Calendar C
where C.BeginDate between @CalendarBegDate and @CalendarEndDate
Order By 2
Open SetPriceWeekSQL
fetch next from SetPriceWeekSQL into @PriceWeek, @BegDate
while @@fetch_status = 0
    begin
        SET @Week = @Week + 1
        IF(@SQLstring='')
        Begin
            SET @SQLstring = @SQLstring + 'Insert Into #Temp Select Unit, ShortName, ItemCode,
Description, regionorder, Contractprice, IsNull('+
            '['+@PriceWeek+'],''0.00'') as Price, (convert(decimal(10,3),''-0.001'')) as
Variance,
            '''+@PriceWeek+''' as PriceWeek, ''WK'+convert(varchar(2),@Week)+''' as Week From
#TempContract'+@WherePriceWeek

            IF(@SortBy='Members')
            Begin
                SET @SQLstring = @SQLstring + ' UNION Select Unit, ShortName, '''',
''zzzz'', '''', '''', ''0'' as Price, ''-0.001'' as Variance, '''' as PriceWeek, ''WK'+convert(varchar
(2),@Week)+''' as Week From #TempContract'+@WherePriceWeek
            End
            Else
            Begin
                SET @SQLstring = @SQLstring + ' UNION Select Unit, '''', ItemCode,
Description, ''1000'', Contractprice, ''0'' as Price, ''-0.001'' as Variance, '''' as PriceWeek,
''WK'+convert(varchar(2),@Week)+''' as Week From #TempContract'+@WherePriceWeek
            End
        End
        ELSE
        Begin
            SET @SQLstring = @SQLstring + ' UNION '
            SET @SQLstring = @SQLstring + 'Select Unit, ShortName, ItemCode, Description,
regionorder, Contractprice, IsNull('+
            '['+@PriceWeek+'],''0.00'') as Price, IsNull(convert(decimal(10,2),['+@PriceWeek
+'])-convert(decimal(10,2),['+@LastPriceWeek+']),''0.00'') as Variance,
            '''+@PriceWeek+''' as PriceWeek, ''WK'+convert(varchar(2),@Week)+''' as Week From
#TempContract'+@WherePriceWeek

            IF(@SortBy='Members')
            Begin
                SET @SQLstring = @SQLstring + ' UNION Select Unit, ShortName, '''',
''zzzz'', '''', '''', ''0'' as Price, ''0'' as Variance, '''' as PriceWeek, ''WK'+convert(varchar
(2),@Week)+''' as Week From #TempContract Where IsNull(['+@LastPriceWeek+'],''0.00'') <> ''999.99'' or
IsNull(['+@PriceWeek+'],''0.00'') <> ''999.99'' '
            End
            Else
            Begin
                SET @SQLstring = @SQLstring + ' UNION Select Unit, '''', ItemCode,
Description, ''1000'', Contractprice, ''0'' as Price, ''0'' as Variance, '''' as PriceWeek, ''WK'+convert
(varchar(2),@Week)+''' as Week From #TempContract Where IsNull(['+@LastPriceWeek+'],''0.00'') <> ''999.99''
or IsNull(['+@PriceWeek+'],''0.00'') <> ''999.99'' '
            End
        End
        SET @LastPriceWeek = @PriceWeek
        fetch next from SetPriceWeekSQL into @PriceWeek, @BegDate
    end
Close SetPriceWeekSQL
Deallocate SetPriceWeekSQL

Print(@SQLstring)
Execute(@SQLstring)

Drop Table #TempContract

IF(@SortBy='Members')
Begin
    Select
        Unit,
        ShortName,
        ItemCode,
        Description,
        regionorder,
        Contractprice,
        convert(varchar(20),convert(decimal(10,2),Price)) as Price,
        sum(convert(money,Variance)) as Variance,
        VarianceAverage = convert(varchar(25),convert(decimal(10,2),(Select sum(convert
(money,Variance)) From #Temp Where ShortName=T.ShortName and Week=T.Week) / Replace(((Select count
(regionorder) From #Temp Where ShortName=T.ShortName and Week=T.Week)-count(Variance)),'0','1'))),
        PriceWeek,Week
    From #Temp T
    Group By
        Unit,
        ShortName,
        ItemCode,
        Description,
        regionorder,
        Contractprice,
        Price,
        PriceWeek,Week
    Order By Week,ShortName,Description
End
ELSE
Begin
    Select
        Unit,
        ShortName,
        ItemCode,
        Description,
        regionorder,
        Contractprice,
        convert(varchar(20),convert(decimal(10,2),Price)) as Price,
        sum(convert(money,Variance)) as Variance,
        VarianceAverage = convert(varchar(25),convert(decimal(10,2),(Select sum(convert
(money,Variance)) From #Temp Where ItemCode=T.ItemCode and Week=T.Week) / Replace(((Select count
(regionorder) From #Temp Where ItemCode=T.ItemCode and Week=T.Week)-count(Variance)),'0','1'))),
        PriceWeek,Week
    From #Temp T
    Group By
        Unit,
        ShortName,
        ItemCode,
        Description,
        regionorder,
        Contractprice,
        Price,
        PriceWeek,Week
    Order By Week,Description,regionorder
End

Drop Table #Temp

A: There is another difference in the two queries...
First query:
 where UPPER(up.Unit) = 'ROCK BOTTOM' and C.BeginDate <= @CalendarEndDate and C.EndDate >=

Second query:
 where UPPER(mp.Unit) IN ('CHOPHOUSE', 'CRAFTWORKS SC', 'GORDON BIERSCH', 'OLD CHI FRANCHISE', 'OLD CHICAGO',

You're referencing a different table. Does that make a difference? Notice in the first (working) query you reference up and the second is mp.


text:
Q: What is Action? I'm a mathematics student and while I was studying classical mechanics I could find some relationship with Differential Geometry (classical one, with Gauss mapping), but I couldn't understand what is Action properly and the integral definition don't give me any intuition.

A: Mathematically, the action is defined as being the integral over time of the Lagrangian. So it is a functional over paths that describe what is the motion of the system over a particular path. Also, it has the units of [energy]$\cdot$[time]. Properly, we say that the system must follow the principle of least action, which says that the action must be stationary for a physical path. Since one can show that the equation of motion leads to Newton's formalism if $\mathcal{L}=T-U$, it is accepted that different Lagrangian leads to different formalism, depending on the symmetry one impose on the system. For example, for some region of spacetime on a globally hyperbolic manifold $M$ equipped with a metric, the action for a scalar field would be:
$$
S=\int \mathrm{d}^4x\sqrt{-g}\left(-\frac{1}{2}D_\mu\phi D^\mu\phi-\frac{1}{2}m^2\phi^2\right).
$$


text:
Q: Why do we use the letters T,U in generics I noticed most tutorials/courses/articles use T,U... as the name of generic types. Why exactly, why not assign normal names instead?

A:
I noticed most tutorials/courses/articles use T,U... as the name of generic types. Why exactly, why not assign normal names instead?

Mostly because they are mundane and poor examples.
As I mention below, It's much better practice to prefix something with T instead of just saying T in most cases.  Array<T> being prime example of one that is truly open.  If you were to say, write your own version of .Net's Dictionary which holds Key Value Pairs, then you could see why you could be more explicit in the following examples of it's interface.
Dictionary<T,U>

// or

Dictionary<TKey, TValue>

Excerpt from my own answer of a very similar question:
In Typescript what does <T> mean?

'T' is going to be a type declared at run-time instead of compile time.  The T variable could be any non-declared variable (I couldn't find a reference, but I would assume any valid set of characters that could be used for a variable names).  Similarly in c#, if the type T represents is not a value type but a more complex type (class) or interface, it could be named/declared as TVehicle or TAnimal to help denote a valid type for future programmers (and could be considered best practice because just T is not intuitive). I prefer TSomething because I know that uppercase T means a generic type.  WSometing or ASomething is also valid, but I just don't prefer it.  (Microsofts APIs are almost always TContext or TEntity for example).

You can explain to me why in the Typescript documentation they put <T> instead of putting something more descriptive like <Identity> for example. Nothing and <T> for me is the same. Now does everyone use the <T> like fools, or did I miss something?

These are all going to be assumptions in the following.  I do not know neither the team who designed the typescript generic system nor the team who wrote the documentation.

At the root level of generics is the ability to use T as any possible type (not to be confused with typescript any).  Meaning Array<T> is the interface (for lack of a better word) and when we create a concrete type we replace T with a declared type:

Array<number>

So for the interface Array<T> what makes more sense than T?  I don't know.  I do know that T has to be a Type (number, string, etc) so it makes sense to use T because it the first letter of the word Type.  I think Array<Type> would be really confusing and/or might even be invalid if type or Type became reserved or restricted (currently type has special meaning in certain contexts so it's also a poor choice) so avoiding those is a good choice.  Other languages (C-sharp, Java) also choose to use T, so switching between languages and being able to use the same term is advantageous.

A: It's just a convention; different kinds of things have visibly different name formats so you can tell what kind of thing something is from what format its name is written in. For example, in Java, Javascript and Typescript it's conventional to use camelCase for variables and method names, UpperCamelCase for class names, and UPPER_SNAKE_CASE for constants; and it's conventional to use T for a type parameter.
This way, if you see a type named T you know it is a type parameter, whereas if you see a type named Person you know it's not. And if you see person you know it's not a type. Being able to tell apart a class from a type parameter is useful because of type erasure; classes exist at runtime but type parameters are removed from the code during compilation. (This applies moreso in Java than in Typescript, because in Java only type parameters are erased, whereas in Typescript interfaces and type aliases are also erased. But the convention comes from Java and similar languages, so it has stuck.)
Most likely, the default letter to use is T because it stands for "Type", then just like in mathematics it's conventional to use consecutive letters for multiple variables representing the same kinds of thing, so S, T, U, V are common. Also, K is often used for a generic key type and V for a value type associated with it; in some cases E is used for the type of "elements" in a collection.


text:
Q: How to access the data from multiple documents within a collection with self Join in ArangoDB I have stored the data in ArangoDB 2.7.1 as with collection name DSP:
{"content": "Book.xml", "type": "string", "name": "name", "key": 102}
{"content": "D:/XMLexample/Book.xml", "type": "string", "name": "location", "key": 102}
{"content": "xml", "type": "string", "name": "mime-type", "key": 102}
{"content": 4130, "type": "string", "name": "size", "key": 102}
{"content": "Sun Aug 25 07:53:32 2013", "type": "string", "name": "created_date", "key": 102}
{"content": "Wed Jan 23 09:14:07 2013", "type": "string", "name": "modified_date", "key": 102}
{"content": "catalog", "type": "tag", "name": "root", "key": 102}
{"content": "book", "type": "string", "name": "tag", "key": 103}
{"content": "bk101", "type": {"py/type": "__builtin__.str"}, "name": "id", "key": 103}
{"content": "Gambardella, Matthew", "type": {"py/type": "__builtin__.str"}, "name": "author", "key": 1031}
{"content": "XML Developer's Guide", "type": {"py/type": "__builtin__.str"}, "name": "title", "key": 1031}
{"content": "Computer", "type": {"py/type": "__builtin__.str"}, "name": "genre", "key": 1031}
{"content": "44.95", "type": {"py/type": "__builtin__.str"}, "name": "price", "key": 1031}
{"content": "2000-10-01", "type": {"py/type": "__builtin__.str"}, "name": "publish_date", "key": 1031}
{"content": "An in-depth look at creating applications with XML.", "type": {"py/type": "__builtin__.str"}, "name": "description", "key": 1031}

Here, a single set {"content": "Book.xml", "type": "string", "name": "name", "key": 102} represents a single document in collection.
Now, I want to access all the documents with the similar value of the key attribute in multiple documents or the value title and price where genre is computer" for the same key value.  I have tried an AQL as FOR p IN DSP filter p.name == "publish_date" AND p.content == "2000-10-01" AND p.name == 'title' return p but this is returning an empty set because it is comparing within the single document, Not in a collection.
Like relational database, there is some kind of self join will required but I don't know how the self join will applied. Please tell me how can I access the all documents with same value of the key attribute where publish_date is "2000-10-01". I expect the result of this query the following documents because corresponding to publish_date with value 2000-10-01 the value of key is 1031:
{"content": "Gambardella, Matthew", "type": {"py/type": "__builtin__.str"}, "name": "author", "key": 1031}
{"content": "XML Developer's Guide", "type": {"py/type": "__builtin__.str"}, "name": "title", "key": 1031}
{"content": "Computer", "type": {"py/type": "__builtin__.str"}, "name": "genre", "key": 1031}
{"content": "44.95", "type": {"py/type": "__builtin__.str"}, "name": "price", "key": 1031}
{"content": "2000-10-01", "type": {"py/type": "__builtin__.str"}, "name": "publish_date", "key": 1031}
{"content": "An in-depth look at creating applications with XML.", "type": {"py/type": "__builtin__.str"}, "name": "description", "key": 1031}

A: Assuming that the publish date is stored in attribute name and its value in attribute content, you will first need to find all documents with that combination:
FOR self IN DSP
  FILTER self.name == 'publish_date' && self.content == '2000-10-01'
  RETURN self

Now, with these documents being found, you can join them with the DSP collection again, filtering out documents that have the same key value, but excluding the already found documents from the initial FOR:
FOR self IN DSP
  FILTER self.name == 'publish_date' && self.content == '2000-10-01'
  FOR other IN DSP
    FILTER other.key == self.key && other._key != self._key
    RETURN { self, other }

If you're always filtering on name and content and/or key, it may be sensible to index these attributes. It looks like key deserves an index on its own. A hash index should suffice as key will always be equality-compared. name and content (in this order) can be put into a skiplist index.


text:
Q: How can i use implicit intent but avoid "select an app to handle this intent" screen? In my code I want to trigger an implicit intent to open another android library activity.
Intent i = new Intent("Shared library", Uri.parse("https://www.google.com/"));
startActivity(i);

Lets say few apps contain this same library. If I trigger an implicit intent will the user see the "select an app to handle this intent"?
Or because all the apps contain the same library it will just open?

A:
If I trigger an implicit intent will the user see the "select an app to handle this intent"?

If the library:

*

*...is an AAR

*...has an AndroidManifest.xml file, which...

*...has an <activity> with an <intent-filter> that matches your implicit Intent
Then any app that incorporates the library and is not blocking that <activity> via its own manifest will be a candidate for responding to that implicit Intent. If there are 2+ of those apps, normal Android implicit Intent resolution occurs:

*

*If the user set a default for this Intent structure on a previous startActivity() call, that default activity will be the one that is started

*Otherwise, the user will see a chooser

Or because all the apps contain the same library it will just open?

No, because Android does not know which app is the one that the user wants.

How can i use implicit intent but avoid "select an app to handle this intent" screen?

You can't, if the user has not set a default activity. It is up to the user to decide which app's activity should handle that implicit Intent.
To put it another way: malware authors would love the ability to unilaterally hijack implicit Intents and force them all to route to the malware.


text:
Q: How to make GridCacheStore-backed get() store its result in the cache When I use a GridCacheStore-backed cache, the first get() may take a long time, because internally the GridCacheStore will perform calculations / slow search etc.
The second get() on that node will be quick because the result has been cached by that node.
However, the get() on other node is still slow because the result is not being replicated. How to make this replicated? I've set cacheMode=REPLICATED.
My config:
<bean parent="cache-template">
    <property name="name" value="yagoEntityByLabel" />
    <property name="cacheMode" value="REPLICATED" />
    <property name="atomicityMode" value="ATOMIC" />
    <property name="distributionMode" value="NEAR_PARTITIONED" />
    <property name="backups" value="1" />
    <property name="store">
        <bean class="id.ac.itb.ee.lskk.lumen.core.yago.YagoEntityByLabelCacheStore" />
    </property>
    <property name="swapEnabled" value="false" />
    <property name="evictionPolicy">
        <bean class="org.gridgain.grid.cache.eviction.lru.GridCacheLruEvictionPolicy">
            <property name="maxSize" value="10000" />
        </bean>
    </property>
</bean>

The workaround is to not use GridCacheStore-backed but to use put() instead, but there's a lot of typing and it's not atomic, since the logic will be:
@Nullable value = cache.get(key);
if (value == null) {
   value = calculateHeavily(key);
   cache.put(key, value);
}

A: GridGain (as most other data grids) does not replicate on Get operation - it simply loads data into cache. Your workaround using Put operation is good.
To make it atomic (if you need to do so), you can wrap your code into transaction, like so:
try (GridCacheTx tx = cache.txStart()) {
   @Nullable value = cache.get(key);
   if (value == null) {
      value = calculateHeavily(key);
      cache.put(key, value);
   }

   tx.commit();
}


text:
Q: How to leave a cell blank when using IF plus AND/OR statement I am using the following statement and its working but i would like the cell to be blank until S, I or R are entered into G4 and I4. At the moment it states Fail.
=IF(OR(AND(G4="S", I4="S"), AND(G4="R", I4="R"), AND(G4="I",I4="I")), "Pass", "Fail")

Any suggestions?

A: If anything but S,I, or R is in those two cells this will return an empty string:
=IF(AND(OR(G4={"S","I","R"}),OR(I4={"S","I","R"})),...,"")

Where ... is your formula.
If all you care about is whether blank or not in those two cells it can be:
=IF(AND(G4<>"",F4<>""),...,"")

We can also use SUMPRODUCT(COUNTIFS()) to lessen the use of ORs and ANDs:
IF(SUMPRODUCT(COUNTIFS(G4,{"S","I","R"},I4,{"S","I","R"})),"PASS","FAIL")

Though this approach does not shorten the current formula greatly, it would if the criteria were to increase to more than 3.
So:
=IF(AND(OR(G4={"S","I","R"}),OR(I4={"S","I","R"})),IF(SUMPRODUCT(COUNTIFS(G4,{"S","I","R"},I4,{"S","I","R"})),"PASS","FAIL"),"")


text:
Q: Swagger-UI like API documentation tool for API written in Golang and consumes/produces protocolBuffer input/output I am developing a web product with Rest APIs which is using protocol buffers in Golang.
In my earlier products, we used Swagger for automated API documentation as they were using JSON for request/response. We are aiming at the same functionality/tool for integration but haven't found an ideal match.
Is there any tool that we should consider or look into?


text:
Q: Windows 8:How to use external images in windows 8 Metro app Context:
Hi,
I am a complete newbie in windows based development. I am building an app for windows 8. I am using the grid app available in visual studio along with javascript, html-5 and css.
Problem:
I want to use external images(from my server ) while displaying a list of objects. But the following binding code does not allow it.

The windows metro apps don't allow this for security reasons i.e. referencing to external url dynamically.
Is there a work around for this ? Please help I am stuck here completely.

A: You want to use a data binding converter to prepend the URL prefix to the image value. Refer to http://msdn.microsoft.com/en-us/magazine/jj651576.aspx and search for "converter" on the page for how to do this.


text:
Q: Hashicorp Vault get Vault to generate several key values I'm using Hashicorp Vault and java spring vault, trying to generate several key-value pairs. What is the best way (or vault API) to do this? Ideally this key-value pair is generated within Vault.
Java will only have access (or need to know) to the key-part which is a reference to the real secret, the value-part.
As an illustration:
From java initalizeSecret() -> Vault creates key-value pair -> return key-part to java.

A: If I understood your question, you have to supply the key to write it to vault. Vault itself does not generate your key. You must know the key so you will use it to read this value afterwords.


text:
Q: HTACCESS URL Rewrite not working making static url I have  problem i am using htaccess for add index.php and convert url also.
index.php working perfect but url is not converting.
Given url : http://example.com/allmodels/Samsung-mobiles_80
I want to convert into http://example.com/allmodels?st=Samsung-mobiles_80
I have used following syntax.
1:
        Options +FollowSymLinks -MultiViews
        RewriteEngine on
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule .* index.php/$1
        RewriteRule ^allmodels/(.*)$ allmodels?st=$1 [NC,L]

2:
        Options +FollowSymLinks -MultiViews
        RewriteEngine on
        RewriteRule ^allmodels/(.*)$ allmodels?st=$1 [NC]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule .* index.php/$1 [PT,L]

3:
        Options +FollowSymLinks -MultiViews
        RewriteEngine on
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^allmodels/(.*)$ allmodels?st=$1 [NC]
        RewriteRule .* index.php/$1 [PT,L]

I have try many syntax but all that not working for me.
I got error 404 page not found.

A: I updated the suggested solution again according to the new information I got:
Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteRule ^/allmodels/(.*)$ /allmodels?st=$1 [P,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$1 [L]

RewriteRule .* index.php/$1 has to go second or otherwise the /allmodels-call will be rewrited to index.php/allmodels/(.*). Or you have to add the third line to exclude /allmodels-calls like I did.
R=301 and R=permanent is the same. Use whatever you prefer.
And finally make sure that the target file really exists ;)

UPDATE
Setting up your rewrite.log requires you to add following line right after "RewriteEngine on"
RewriteLogLevel Debug

After you did that, restart the apache and call your URL. Then have a look into /var/log/apache2/rewrite.log and you will see how your request is processed by the rewrite-module. Either post the result or describe it in such a way it will enable others to further support you. Thanks :)
UPDATE-2
After some back and forth it got clear that the suggested rule itself isn't the problem. But the way to ask for the final solution wasn't optimal^^
So I changed my solution by now to fit the approved correct and working version, with a 'P' for proxy instead of 'R' for rewrite to hide the orignal-URL that the user gets written to.

A: Finally i got my solution i used following code that is working for me.
Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteRule ^allmodels/(.*)$ /allmodels?st=$1 [P,NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$1 [L]

And thanks fishy.


text:
Q: Image not loading in .phtml file I have an image stored in media/images. I have a .phtml file that includes the following code:

but the image is not loading. I also tried
img src ="media/images/Bocadillos.png"

but it's also not working.
Which is the correct way to reference an image here?

A: I'm pretty sure the {{...}} is a cms directive only used in cms/pages and cms/blocks.
If you are looking to add a specific media file to a template try:
<?php echo $this->getUrl('pub/media') . 'path/to/url.png'; ?>

A: Use below code,
<image src='<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'images/YOUR_IMAGE_NAME'; ?>' />

A: You can use getBaseUrl function of Mage class to get Media URL in template file.
<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'images/Bocadillos.png'; ?>

Please check this for more details.

A: Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) - will return http://[yourdomain].com/media/.
So you can use it like this:
<img src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>images/Bocadillos.png" />


text:
Q: how do i escape a slash character in a WPF binding path, or how to work around? I'm just learning WPF, and I gragged a table from a datasource onto a window which generated XAML for each column.
Some of those columns had names that caused the following:
<DataGridTextColumn x:Name="_Rev_UnitColumn" Binding="{Binding Path=Rev/Unit}" Header="Rev/Unit" Width="SizeToHeader" />

This causes the column to come up blank (like me).

A: On MSDN there is an article on property paths which has a section on escape characters:

Inside indexers ([ ]), the caret character (^) escapes the next character.
You must escape (using XML entities) certain characters that are special to the XML language definition. Use & to escape the character "&". Use > to escape the end tag ">".
You must escape (using backslash \) characters that are special to the WPF XAML parser behavior for processing a markup extension.

*

*Backslash (\) is the escape character itself.

*The equal sign (=) separates property name from property value.

*Comma (,) separates properties.

*The right curly brace (}) is the end of a markup extension.

The slash is not listed here so i do not know if the backslash escape would work, but you can try.
(How exactly do you have a property name like that? It seems to be illegal both in XML and C#)

A: I (kind of randomly) tried:
<DataGridTextColumn x:Name="_Rev_UnitColumn" Binding="{Binding Path=[Rev/Unit]}" Header="Rev/Unit" Width="SizeToHeader" />

And the result was everything worked as I expected it to.  Looking at it again, I guess H.B.'s MSDN quote tells me this.  When I read that (originally on MSDN before I even posted this question, then again here) I just didn't understand what "Inside indexers --comma-- the caret character (^) escapes the next character" meant.

A: If you need to mask a path with : character, you can try using parenthesis char (path)
Example usage
<Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="materialDesign:ButtonAssist.CornerRadius" Value="24"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Border CornerRadius="{Binding (materialDesign:ButtonAssist.CornerRadius), RelativeSource={RelativeSource AncestorType=Button}}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


text:
Q: Learning how to use a new statistical GUI? The question is in the header, but I would extend the context a bit.
Next semester I am due to be a teaching assistant (TA) in a course in statistics, where I would need to help sociology students learn to use SPSS. I don't know SPSS, yet, and would like to learn how to use it.
I was thinking of taking a simple dataset, and start reviewing it with methods I know, thus starting to map out where are methods I know of.  And once finished, to try and explore more options.
Can someone propose other/better strategies to master a new statistical graphical user interface (GUI)? (in my case SPSS, but it could apply to many other GUI's).

A: Since you are pretty well versed in R, get a copy of Muenchen's "R for SAS and SPSS Users" (Springer, 2009) and work backwards.

A: As someone who made the shift the other way from SPSS to R, I'd say that SPSS is relatively simple and intuitive relative to R. The menus and dialog boxes guide you through the process. Of course this means that it is also fairly easy to run analyses that don't make sense. And the GUI  leads to less flexible analyses and tedious button pressing especially for repetitive analyses.
Thus, your approach of taking a dataset and just playing around might be sufficient.
There's plenty of how-to books out there, such as:

*

*Discovering Statistics Using SPSS

*SPSS Survival Manual

There's also plenty of websites offering tutorials:

*

*Andy Field

*My old notes

*UCLA on SPSS
I'd also recommend that if you are teaching students about SPSS, you encourage them to use syntax. Using SPSS syntax is not as good as using technologies like R and Sweave.
However, using syntax is much better than just pressing menus and buttons in an ad hoc way and then wondering later what you've actually done.
I wrote a post listing tips for using SPSS syntax in order to approximate reproducible research with SPSS.

A: In youtube there are a lot of videos related with SPSS, I usually learn a gui with them. I recommend you record videos to teach how to apply methods and encourage them to use the "paste" button to learn a little of syntax

A: Your method will certainly work for most introductory techniques you'd need to do. I am quite familiar with R, but I was required to learn Minitab to teach to non-statistics people. In one afternoon, I had a basic enough understanding of Minitab to explain how to use it in the limited framework of an introductory stats class. I figure SPSS would behave similarly.
I would suggest reviewing the course syllabus and trying to complete all techniques outlined in the syllabus. A large majority of your students' questions will pertain to doing tasks the teacher has asked them to do, and a smaller percentage of questions will be related to doing tasks in their other statistics endeavors.
You will be able to answer a large majority of student questions by knowing how to use SPSS to solve a class-related problem, so just playing around within SPSS will benefit you.


text:
Q: For $0 \le x \le 1 , p\gt 1$, prove $1 \over2^{p-1}$ $\le x^p +(1-x)^p \le 1$. For $0 \le x \le 1 , p\gt 1$, prove $1 \over2^{p-1}$ $\le x^p +(1-x)^p \le 1$.

A: One way to prove the first inequality is to use the fact that $x\mapsto x^p$ is a convex function to observe that
$$\frac{1}{2^p}= \left(\frac{x+(1-x)}{2}\right)^p\leq \frac{x^p+(1-x)^p}{2}.$$
I prefer this method because it seems more insightful.
However, you can also do the straightforward thing and differentiate $x^p+(1-x)^p$, which for $p>1$ gives $px^{p-1}-p(1-x)^{p-1}$. This is zero iff $x=1-x$, i.e. $x=1/2$. Thus the extrema of $x^p+(1-x)^p$ occur at $0,1/2,1$ and you can observe that the value of $x^p+(1-x)^p$ at these points is $1,1/2^{p-1}$ and $1$ respectively.

A: From the answer here, we have for a real number $p \geq 1$ and complex numbers $\alpha, \beta$,
\begin{equation}
|\alpha + \beta|^p \leq 2^{p-1}(|\alpha|^p + |\beta|^p)
\end{equation}
In your case, take $\alpha = x \in [0,1]$ and $\beta = 1-x$ to obtain the lower bound on $x^p + (1-x)^p$. The upper bound is trivial since for $p>1$ and $x \in [0,1]$, we have
$$x^p \leq x \,\, \text{ and } \,\, (1-x)^p \leq 1-x$$
Hence, we get
$$x^p + (1-x)^p \leq x + 1-x = 1$$which gives us the upper bound.


text:
Q: Setting (dp) values in properties box in Eclipse
Possible Duplicate:
Android eclipse editor: Unable to edit properties

I have changed my computer recently with the last version of Eclipse and ADT plugin and I'm confused.
I have noticed some changed with the ADT plugin and now I can't put specific values in the properties box in Eclipse.
I used to click on a Layout (in graphical View); then I went to the properties box and change one of a Layout properties to a specific value like 50dp.
Now I don't have a choice, I can only select fill_parent, wrap_content, match_parent ...
I order to do what I want, I need to edit xml manually.
Do I miss something or not ?

A: If you look in the toolbar just above your layout, use the button with a dashed square in it.


text:
Q: httpclient is superslow (htmlunit 2.24 ) hi i am a webprogrammer in korea and i developed a method for
crawling lot's of merchandise informations.
i made it in our webapplication(made by spring). and it is activated by requesting specific url that is down below
@RequestMapping(value = "/naverCrawlJobAjax", produces = "application/json; charset=utf8")
it works fine when i activate it in my local tomcat server.
but when i request the url of the actual running server, it is stucked
with this method
(org/apache/http/impl/client/InternalHttpClient.doExecute(HttpHost, HttpRequest, HttpContext))
it also works in the actual running server. but too slow to use it....
any help? T.T
    //code start
    WebClient webClient =  new WebClient(BrowserVersion.FIREFOX_45);//maybe stucked in here
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setCssEnabled(false);
    webClient.addRequestHeader("Accept-Language", "ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4, value");
    webClient.addRequestHeader("Accept-Charset", "windows-949,utf-8;q=0.7,*;q=0.3");
    webClient.getCookieManager().setCookiesEnabled(true);
    webClient.setJavaScriptTimeout(50000);

    String result = "S";
    String url = "https://adcenter.shopping.naver.com/member/login/form.nhn";
    HtmlPage page;
    JSONObject obj = new JSONObject();
    obj.put("resultCode", result);
    obj.put("httpClientVer", HttpClientBuilder.class.getProtectionDomain().getCodeSource().getLocation());


text:
Q: Which is the best use of useEffect to fetch multiple data? I'm some confused about some different ways to use the useEffect hook to fetch API data. I want to know if there is a "best way" to do this, performance related, or if it really doesn't matter how to do it.
Consider the following ways:
Mutiple function calls to fetch API data inside a single useEffect:
useEffect(() => {
  const fetchStudents = async () => {
    const students = await studentService.getAll()
    setStudents(students)
  }

  const fetchCourses = async () => {
    const courses = await courseService.getAll()
    setCourses(courses)
  }

  const fetchSchedules = async () => {
    const schedules = await scheduleService.getAll()
    setSchedules(schedules)
  }

  fetchStudents()
  fetchCourses()
  fetchSchedules()
}, [])

A single function call to fetch all the api data inside a single useEffect:
useEffect(() => {
  const fetchAllData = async () => {
    const students = await studentService.getAll()
    const courses = await courseService.getAll()
    const schedules= await scheduleService.getAll()

    setStudents(students)
    setCourses(courses)
    setSchedules(schedules)
  }

  fetchAllData()
}, [])

Maybe, multiple useEffects for each api call:
useEffect(() => {
  const fetchStudents= async () => {
    const students = await studentService.getAll()

    setStudents(students)
  }

  fetchStudents()
}, [])

useEffect(() => {
  const fetchCourses = async () => {
    const courses = await courseService.getAll()

    setCourses(courses)
  }

  fetchCourses()
}, [])

useEffect(() => {
  const fetchSchedules = async () => {
    const schedules= await scheduleService.getAll()

    setSchedules(schedules)
  }

  fetchSchedules()
}, [])

Is there another way to consider? Let it be known.

A: In your second example you wait for each promise to resolve before executing the next one, this will hurt performance, the other examples are all running in parallel.
I would go with Promise.all inside a single useEffect because i think its more readable then 3 useEffect or 3 functions, and this will also make sure all of our promises are executing in parallel.
Note that if one of the promises inside Promise.all reject, the function is going to throw and you won't have any access to the resolved promises
useEffect(() => {
  Promise.all([
    studentService.getAll().then(setStudents),
    courseService.getAll().then(setCourses),
    scheduleService.getAll().then(schedules)
  ])
}, [])


text:
Q: General Windows Vista check-up Being very new to windows can anyone recommend a tool/app that does a general clean-up health-check for a windows vista system. Coming from a mac world I would use onyx or main menu and fsck - etc

A: We generally don't recommend these programs for Windows, as they can do more harm than good most of the time.
Vista does pretty well at maintenance, disk defrag runs on a schedule automatically, you can use Disk Cleanup once a month if you wish.
http://www.microsoft.com/atwork/maintenance/speed.aspx
.
Once a month run chkdsk command (no switches) it will check the integrity of the file system in read only mode, if it finds problems, re run chkdsk with the f switch (chkdsk /f)
See method 2
http://www.vistax64.com/tutorials/67612-check-disk-chkdsk.html
Others here may recommend CCleaner, be careful if you use it, It has a registry cleaner that can do more harm than good also.
.


text:
Q: HTML: Terinary operator in option tag showing option as selected if it matches input <html>
    <head> </head>
    <body>
        <select>
            <option value='one' ${Data.input == 11 ? "selected" : ""}>1</option>
            <option value='two' ${Data.input == 22 ? "selected" : ""}>2</option>
            <option value='three' ${Data.input == 3 ? "selected" : ""}>3</option>
            <option value='four' ${Data.input == 44 ? "selected" : ""}>4</option>
        </select>
    </body>
</html>

I am trying to show drop down value as selected when my parameter matches any of the values in the options.
Suppose if my Data.input is 3 then option 3 has to be selected as default when I open the page.
But it is not working.
P.S: I am new to web technologies. So please let me know if I am doing anything wrong.
EDIT:
I am using jsp and you can see the output at JSFiddle

A: I am assuming you are using JSP since you tagged JSP in your question.
Try this:
<html>
    <head> </head>
    <body>
        <select>
            <option value='one' <%= Data.input == 1 ? "selected" : "" %>>1</option>
            <option value='two' <%= Data.input == 2 ? "selected" : ""%>>2</option>
            <option value='three' <%= Data.input == 3 ? "selected" : ""%>>3</option>
            <option value='four' <%= Data.input == 4 ? "selected" : ""%>>4</option>
        </select>
    </body>
</html>

Also I see that you say == 11, == 22, == 3, ==4. Should those be 1, 2, 3, 4?

A: As an alternate solution you can use the JSTL with EL:
<select>
    <option <c:if test="${Data.value == 1}">selected</c:if>> 1 </option>
    <option <c:if test="${Data.value == 2}">selected</c:if>> 2 </option>
    <option <c:if test="${Data.value == 3}">selected</c:if>> 3 </option>
</select>


text:
Q: Why is it that nobody on these sites is here to help? I've used a few of the Stack Exchange sites and I've noticed that instead of trying to help people with their problems and questions, all most people do is down vote questions for the slightest mistake or even put an important question on hold.

A: Like most of your questions on SE, you've shown little to no effort in quantifying your question/statement here.  As someone pointed out above, Stack Overflow is a community site.  Yes, there are some employees, but 99.99% of us are just regular people like yourself who have a bit of a "philanthropist" streak in them and just want to be able to help people.  We are more than happy to help, as evidenced by the many thousands of answered questions here, but we also have jobs/school/families and we can't dedicate our lives to writing code for free.  Show a little initiative, narrow down your problem to one block of code, and I guarantee you will get an answer quickly.  Ask us to do your whole job with little-to-no understanding of what you're actually doing, and we're going to move on to another question.  Sorry, it just works that way.


text:
Q: notifyDataSetChanged does not work in adapter in kotlin There is a delete button on my recylerview item when I click it I m showing a alert dialog when I click yes button I want to refresh my recylerview but I could'not. I call directly notifyDataSetChanged in adapter at the end of the my code but it does not work.
MyAlertDialog(In my adapter)
            mAlertDialog.setPositiveButton("Yes") { dialog, id ->

            val databaseHandler: DBHelper = DBHelper(holder.itemView.context)
            val removedMed = Medicine(id = medicine.id,name = medicine.name,amount = medicine.amount,description = medicine.description)
            databaseHandler.deleteMedicine(removedMed)

            dialog.dismiss()

            notifyDataSetChanged()
        }

Mainactivity
class MainActivity : AppCompatActivity() {

private var adapter: MedicineAdapter? = null
private var medicineList : ArrayList<Medicine> = arrayListOf()
private var recyclerView: RecyclerView? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    getDataFromDb()
}

fun getDataFromDb(){

    val context = this
    val db = DBHelper(context)

    recyclerView = findViewById<View>(R.id.recyclerView) as RecyclerView

    adapter = MedicineAdapter(this, db.readData())

    val layoutManager = LinearLayoutManager(applicationContext)

    recyclerView!!.layoutManager = layoutManager
    recyclerView!!.itemAnimator = DefaultItemAnimator()

    // set the adapter
    recyclerView!!.adapter = adapter

    adapter!!.notifyDataSetChanged()

}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    menuInflater.inflate(R.menu.menu, menu)
    return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
    R.id.addBtn -> {

        val intent = Intent(this,AddNewMedicine::class.java)
         startActivity(intent)

        true
    }
    else -> super.onOptionsItemSelected(item)
}

override fun onResume() {
    super.onResume()

    getDataFromDb()
}

}
MedicineAdapter
class MedicineAdapter(
private val mainActivity: MainActivity,
val medicineList: ArrayList<Medicine>)

: RecyclerView.Adapter<MedicineAdapter.ListItemHolder>(){

override fun onCreateViewHolder(
    parent: ViewGroup, viewType: Int): ListItemHolder {

    val itemView = LayoutInflater.from(parent.context).inflate(R.layout.medicine_items, parent, false)

    return ListItemHolder(itemView)

}
inner class ListItemHolder(view: View) :
    RecyclerView.ViewHolder(view),
    View.OnClickListener {

    internal var name = view.findViewById<TextView>(R.id.name)

    internal var amount = view.findViewById<TextView>(R.id.amount)

    internal var description = view.findViewById<TextView>(R.id.description)

    internal var deleteButton = view.findViewById<ImageButton>(R.id.deleteBtn)

    internal var editButton = view.findViewById<ImageButton>(R.id.editBtn)

    init {
        view.isClickable = true
        view.setOnClickListener(this)
        deleteButton.setOnClickListener(this)
        editButton.setOnClickListener(this)
    }

    override fun onClick(view: View) {

        //val intentToCarPager = Intent(view!!.context, CarPagerActivity::class.java)

        //view.context.startActivity(intentToCarPager)

    }

}

override fun onBindViewHolder(holder: ListItemHolder, position: Int) {

    val medicine = medicineList!![position]

    holder.name.text = medicine.name

    holder.amount.text = medicine.amount

    holder.description.text = medicine.description

    holder.deleteButton.setOnClickListener {

        val mAlertDialog = AlertDialog.Builder(holder.itemView.context)

        mAlertDialog.setTitle("Are you sure you want to this record!") //set alertdialog title

        mAlertDialog.setPositiveButton("Yes") { dialog, id ->

            val databaseHandler: DBHelper = DBHelper(holder.itemView.context)
            val removedMed = Medicine(id = medicine.id,name = medicine.name,amount = medicine.amount,description = medicine.description)
            databaseHandler.deleteMedicine(removedMed)

            notifyDataSetChanged()
            dialog.dismiss()
            medicineList.removeAt(position)
            notifyItemRemoved(position)

        }

        mAlertDialog.setNegativeButton("No") { dialog, id ->

        }

        mAlertDialog.show()

    }

    holder.editButton.setOnClickListener {

        val dialog = UpdateMedicine(medicine)
        val manager = (holder.itemView.context as MainActivity).supportFragmentManager

        dialog.show(manager,"")

    }
}

override fun getItemCount(): Int {
    if (medicineList != null) {
        return medicineList.size
    }
    return -1
}

}

A: I solved my problem by removing the object from the array
        notifyDataSetChanged()
        dialog.dismiss()
        medicineList.removeAt(position)
        notifyItemRemoved(position)


text:
Q: Rails Rspec Test Resets Database I'm doing the Rails tutorial, and have been following it fairly strictly. However, my user_pages_spec.rb test resets the development database. So whenever I run a test, I lose all of the current data that was in there before the test. My guess is that the problem is on line 11, but I'm not really sure. Any help is greatly appreciated, thanks :)
Here's my user_pages_spec.rb file:
require 'spec_helper'

describe "UserPages" do

subject { page }

describe "index" do
    let(:user) { FactoryGirl.create(:user) }

    before(:all) { 30.times { FactoryGirl.create(:user) } }
    after(:all) { User.delete_all }

    before(:each) do
        sign_in user
        visit users_path
    end

    it { should have_selector('title', text: 'All users') }
    it { should have_selector('h1', text: 'All users') }

    describe "pagination" do
        it { should have_selector('div.pagination') }

        it "should list each user" do
            User.paginate(page: 1).each do |user|
                page.should have_selector('li', text: user.name)
            end
        end
    end

    describe "as an admin user" do
        let(:admin) { FactoryGirl.create(:admin) }
        before do
            sign_in admin
            visit users_path
        end

        it { should have_link('delete', href: user_path(User.first)) }
        it "should be able to delete another user" do
            expect { click_link('delete') }.to change(User, :count).by(-1)
        end
        it { should_not have_link('delete', href: user_path(admin)) }
    end
end

describe "signup page" do
    before { visit signup_path }
    let(:submit) { "Create my account" }

    it { should have_selector('h1', text: 'Sign up')}
    it { should have_selector('title', text: full_title('Sign up'))}

    describe "with invalid information" do
        it "should not create a user" do
            expect { click_button submit }.not_to change(User, :count)
        end

        describe "after submission" do
            before { click_button submit }

            it { should have_selector('title', text: 'Sign up') }
            it { should have_content('error') }
        end
    end

    describe "with valid information" do
        before do
            fill_in "Name", with: "Example User"
            fill_in "Email", with: "user@example.com"
            fill_in "Password", with: "foobar"
            fill_in "Confirmation", with: "foobar"
        end

        it "should create a user" do
            expect { click_button submit }.to change(User, :count).by(1)
        end

        describe "after saving the user" do
            before { click_button submit }
            let(:user) { User.find_by_email('user@example.com') }

            it { should have_selector('title', text: user.name) }
            it { should have_selector('div.alert.alert-success', text: 'Welcome' ) }
        end
    end
end

describe "profile page" do
    # Code to make a user variable
    let(:user) { FactoryGirl.create(:user) }
    before { visit user_path(user) }

    it { should have_selector('h1', text: user.name) }
    it { should have_selector('title', text: user.name) }
end

describe "edit" do
    let(:user) { FactoryGirl.create(:user) }
    before do
        sign_in user
        visit edit_user_path(user)
    end

    describe "page" do
        it { should have_selector('h1', text: "Update your profile") }
        it { should have_selector('title', text: "Edit user") }
        it { should have_link('change', href: 'http://gravatar.com/emails') }
    end

    describe "with invalid information" do
        before { click_button "Save changes" }
        it { should have_content('error') }
    end

    describe "with valid information" do
        let(:new_name) { "New Name" }
        let(:new_email) { "new@example.com" }

        before do
            fill_in "Name", with: new_name
            fill_in "Email", with: new_email
            fill_in "Password", with: user.password
            fill_in "Confirm Password", with: user.password
            click_button "Save changes"
        end

        it { should have_selector('title', text: new_name) }
        it { should have_selector('div.alert.alert-success') }
        it { should have_link('Sign out', href: signout_path) }
        specify { user.reload.name.should == new_name }
        specify { user.reload.email.should == new_email }
    end
end
end

Here's my database.yml file:
# PostgreSQL. Versions 8.2 and up are supported.
#
# Install the pg driver:
#   gem install pg
# On Mac OS X with macports:
#   gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
# On Windows:
#   gem install pg
#       Choose the win32 build.
#       Install PostgreSQL and put its /bin directory on your path.
#
# Configure Using Gemfile
# gem 'pg'
#
development:
  adapter: postgresql
  encoding: unicode
  database: rails
  pool: 5
  username: postgres
  password: pwpwpwpw

  # Connect on a TCP socket. Omitted by default since the client uses a
  # domain socket that doesn't need configuration. Windows does not have
  # domain sockets, so uncomment these lines.
  #host: localhost
  #port: 5432

  # Schema search path. The server defaults to $user,public
  #schema_search_path: myapp,sharedapp,public

  # Minimum log levels, in increasing order:
  #   debug5, debug4, debug3, debug2, debug1,
  #   log, notice, warning, error, fatal, and panic
  # The server defaults to notice.
  #min_messages: warning

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test: &test
  adapter: postgresql
  encoding: unicode
  database: rails
  pool: 5
  username: postgres
  password: pwpwpwpw

production:
  adapter: postgresql
  encoding: unicode
  database: rails
  pool: 5
  username: postgres
  password: pwpwpwpw

cucumber:
  <<: *test

A: You need separate databases for development and test environments. For example:
development: &BASE
  adapter: postgresql
  encoding: unicode
  database: rails_development
  pool: 5
  username: postgres
  password: pwpwpwpw

test: &test
  <<: *BASE
  database: rails_test

production:
  <<: *BASE
  database: rails_production

cucumber:
  <<: *test


text:
Q: React Native How do I add an object in an array using the map? this is my array
var arr1 = [{key:0, ele: "A"}, {key:1, ele: "B"}]

i want to make a new array with arr1 using map
like this
newarray = [
 {
  title: "@@@", items: [{here: "A"}, {here: "B"}]
 }
]

In summary, I want to put the ele of arr1 in here of newarray[0].items. And I hope newarray[0].title is maintained.
Thank you for your time and I look forward to your advice.

A: Please Try this,If you find any issues feel free to ask
var arr1 = [{key:0, ele: "A"}, {key:1, ele: "B"}]
var newarray = [
 {
  title: "@@@", items: arr1.map(el => {return ({here:el.ele})})
 }
]

A: try this one
newarray = [
 {
  title: "@@@", items: arr1.map(element => {here:element.ele})
 }
]


text:
Q: How can I avoid making attacks that drain my own life? There is a certain defensive attacks that Tallion does that makes him hit the ground (Elven Light) that makes pushing back every enemy nearby but it drain your own lifebar; I just want to know how to do it and avoid doing it because its make you so vulnerable to captain attacks

A: The skill you're referring to is the Elven Light.  It's the second wraith skill you can learn. You press X + A (or Square + X on PS4) to do the attack when you have enough might.

Elven Light
You probably have some gear equipped that is causing it to drain your health when you are using it. You can drain your own health to be able to perform a skill that requires might, even when you don't have enough.
This is the set bonus of the Vendetta legendary set. This is typically found when completing online vendetta missions. Perhaps you have them equipped?

Vendetta legendary set
Remove some or all of the equipment so that the set bonus doesn't take effect. Then even if you accidentally press the buttons, it won't do the skill and you don't drain your health, it just does nothing.


text:
Q: What is 'type' being associated with value or variable? I am trying to understand what are the different 'typing disciplines' in programming. I found there are Dynamic and Static typing disciplines.
In Static typing, Types are associated with variables (as opposed to values). And in Dynamic typing, Types are associated with values (as opposed to variables).
I have linked where I read this...
So, what does type being associated with variable or value mean?

A: Static typing means that the programmer or its compiler declare the data type of the variable. The variable will then only accept that kind of data, i.e. the type is associated with the variable. For example, in Java:
int price_of_donut;

price_of_donut has been assigned an int data type. The variable will only accept ints in your program. It could be 0, 2, 5000000, but not  "free", as the word "free" is a string.
On the other hand, dynamic typing means that the data type of the variable is dependent on its input, i.e. the type is associated with the value. For example, this program in Python:
price_of_donut=2.99
price_of_donut='free'

Notice how there is no declaration of data type before the variable (No declaration is needed).
price_of_donut in the first line is a float, but in the second line price_of_donut turns into a string. The program will run with no problems.

So you might ask: Which one's better?

*

*Dynamic typing makes for an easier coding experience since you type less and potentially use less variables, but the programmer has to keep in mind the data types of variables during coding, whether it changes mid way or not. If a crash occurs, the program might not tell you the right place to look.

Consider this situation: a data type changes in line 81 of your program, but the crash happened on line 246 of your program, and the program tells you something went wrong on line 246. You look at line 246, and it doesn't look wrong at all. Uh oh, where's the bug?

*

*Static typing is rigorous as you will have to potentially make more variables, but the programmer can rest easy knowing that variables can only take the data types they specifically declare. This makes for an easier debugging experience.

With the previous situation in mind: the program will crash on line 81, telling you that the a variable is being fed the wrong data type. You immediately see this, and rectify the problem, probably by making a new variable and potentially having to scroll through the entire program replacing some variables with the new one.


text:
Q: Accessing An ArrayList from a method in a different class I'm working on my very first project outside the college.
I have two classes. In first one I have a method which adds strings to an arraylist.
In the second class I would like to access the arrayList from the method in previous class, and get elements of it.
How could I do that ?
Thank you for helping.

A: You may expose the ArrayList as a static property in the first class and then you can access that property from the second class.
public class First
{
    public static ArrayList MyList { get; set; }
}

public class Second
{
    public void SomeMethod()
    {
        //First.ArrayList will give you access to that class
    }
}

Best is not to use ArrayList at all (if you are using .Net 2.0 or higher) instead use List which is type safe

A: Unless you're using .NET 1.1 i would avoid ArrayLists and use their strongly typed counterparts List<T>.
You need to make the method public in class 1. Then you can access it from class 2 if it is static or if you have an instance of class 1.
For example:
public class Class1{
    public List<String> getList()
    {
        // create the list and return it
    }
}

public class Class2{
    Class1 firstClass{ get;set; }
    void foo()
    {
        // now you can access the List<String> of class1 via it's instance
        List<String> list = firstClass.getList();
        foreach(String s in list)
        {
            // do something
        }
    }
}

A: The best option is to use a readonly property which exposes the arraylist, like this:
class MyClass
{
    private ArrayList FArrayList;
    public ArrayList ArrayList { get { return FArrayList; } }

    ...

A: Try this..
public class First
{
    public ArrayList MyList;
    public First()
    {
       MyList = new ArrayList();
    }
    public void AddString(string str)
    {
       MyList.Add(str);
    }
}
public class Second
{
    public void someMethod()
    {
       First f = new First();
       f.AddString("test1");
       f.AddString("test2");
       f.AddString("test3");
       ArrayList aL = f.MyList; // you will get updated array list object here.
    }
}


text:
Q: LiveDataScope emit not calling I am experiencing a very unusual problem where LiveDataScope is not throwing my Exception, launched in my repository.
The problem is that if in place of the emit, I put a livedata event, it is dispatched to the observer, however with emit, it does not launch the event to it.
ViewModel:
fun launchJob(makeThis: suspend LiveDataScope<ViewState>.() -> Unit): LiveData<ViewState> =
    liveData {
        viewModelScope.launch {
            emitLoad()
            try {
                makeThis(this@liveData)
            } catch (error: Error){
                //its work
                showErrorEvent.value = Pair(error, true)

                // not work
                emit(ViewState.Error(error))
            }
        }
    }
      viewmodel implementation
/**
 * Método responsável por realizar o método de reset de senha.
 * */
    fun requestReset() = launchJob {
         emitSucess(shippingMethodRepository.resetPassword(method))
    }

base repository
  suspend fun getAsyncData(params: P): T {
    try {
        return api.invoke(params)
    } catch (error: Exception) {
        error.printStackTrace()
        throw error
    }
}

As I mentioned, changing the emit to a different livedata, it is observed by the activity, and any code before the emit is read as well, as well as Log, etc.

A: From the docs :

The liveData building block serves as a structured concurrency
  primitive between coroutines and LiveData. The code block starts
  executing when LiveData becomes active and is automatically canceled
  after a configurable timeout when the LiveData becomes inactive.

The root cause why your observer not triggered after called emit function is because your liveData has been observed (activated).
LiveData building block is more suitable for initialising liveData value than to change its value. If you want to change the liveData value like that, just use a mutableLiveData


text:
Q: Tableview prototype cell higher than the the other cells I made a tableview with UIViewController and dragged a tableview scheme into the viewcontroller. I have remembered all the codes that are needed i the class (im quite sure??). But i can't figure out, why the prototype cell is a different size than all the other cells?
It will look as the picture below, when i run the app

A: Set the desired height for each cell in tableView.heightForRowAtIndexPath

A: Go to the Storyboard file and select your Prototype cell. Than in the right sidebar (Utilities pane) select the Size inspector. Here you can enter a custom height for your cell:

-- Edit --
Maybe remove the Scroll View Insets of the UIViewController? Select the UIViewController and in the attributes inspector uncheck: ' Adjust scroll view insets ' :


text:
Q: Getting price from Amazon with Xpath in the following page:
http://www.amazon.com/Jessica-Simpson-Womens-Double-Breasted/dp/B00K65ZMCA/ref=sr_1_4_mc/185-0705108-6790969?s=apparel&ie=UTF8&qid=1413083859&sr=1-4
I am trying to get the price with the expression
'//span[@id="priceblock_ourprice"]'

but the result is an empty variable.
the interesting part is that In other amazon pages, like this one
: http://www.amazon.com/SanDisk-Cruzer-Frustration-Free-Packaging--SDCZ36-032G-AFFP/dp/B007JR532M/ref=sr_1_1?s=pc&ie=UTF8&qid=1413084653&sr=1-1&keywords=usb
I do have an expression that works
'//b[@class="priceLarge"]'

But i dont even know why, because in the source of the page I cant find such a  tag...
So why does it work? and how do I get the price on the first page?
Thanks!

A: When scraping with PHP you can not just take what you see in the browser source for granted.
Instead you first need to fetch the content with PHP and then look into the source there:
$url    = 'http://www.amazon.com/ ... ';
$buffer = file_get_contents($url);

The variable $buffer then contains the HTML that you will be scraping.
Done that with your example links will show that for the first and second address both have an element of .priceLarge containing probably what you're looking for:
$168.00
$14.99

After finding out where the data is you're looking for, you can create the DOMDocument:
$doc          = new DOMDocument();
$doc->recover = true;
$saved        = libxml_use_internal_errors(true);
$doc->loadHTML($buffer);

You might also be interested in parsing errors:
/** @var array|LibXMLError[] $errors */
$errors = libxml_get_errors();
foreach ($errors as $error) {
    printf(
        "%s: (%d) [%' 3d] #%05d:%' -4d %s\n", get_class($error), $error->level, $error->code, $error->line,
        $error->column, rtrim($error->message)
    );
}
libxml_use_internal_errors($saved);

as this is a way that DOMDocument tells you where problems occured. For example duplicate ID values.
After loading the buffer into DOMDocument you can create the DOMXPath:
$xp = new DOMXPath($doc);

You will use it to obtain the actual values from the document.
For example those two example addresses HTML hasshown that the information you're looking for is the #priceBlock both containing .listprice and .priceLarge:
$priceBlock = $doc->getElementById('priceBlock');
printf(
    "List Price: %s\nPrice: %s\n"
    , $xp->evaluate('string(.//*[@class="listprice"])', $priceBlock)
    , $xp->evaluate('string(.//*[@class="priceLarge"])', $priceBlock)
);

Which will result in the following output:
List Price: $48.99
Price: $14.99

If you're missing something, obtaining a parent section element into a variable as $priceBlock in the example does not only allow you to use relative paths for Xpath but can also help with debugging in case you're missing some of the more detailed information:
echo $doc->saveHTML($priceBlock);

This outputs the whole
 that contains all pricing information for example.
If you setup yourself some helper classes, you can further on use this to obtain other useful information from the document for scraping it, like showing all tag/class combinations within the price-block:
// you can find StringCollector at the end of the answer
$tagsWithClass = new StringCollector();
foreach ($xp->evaluate('.//*/@class', $priceBlock) as $class) {
    $tagsWithClass->add(sprintf("%s.%s", $class->parentNode->tagName, $class->value));
}
echo $tagsWithClass;

This then outputs the list of collected strings and their count which is here the tagnames with their class attribute values:
table.product (1)
td.priceBlockLabel (3)
span.listprice (1)
td.priceBlockLabelPrice (1)
b.priceLarge (1)
tr.youSavePriceRow (1)
td.price (1)

As you can see, this is from the first example URL because .pricelarge is with a  element.
This is a relative simple helper, for scraping you can do more, like displaying the whole HTML structure in form of a tree.
DomTree::dump($priceBlock);

It will give you the following output which allows for better consumption than just DOMDocument::saveHTML($node):
`

  +"\n\n  "
  `

    +

    | +
    | | `"List Price:"
    | +"\n    "
    | +
    | | `
    | |   `"$48.99"
    | `"\n  "
    +

    | +
    | | `"Price:"
    | +"\n    "
    | +
    | | +
    | | | `
    | | |   `"$14.99"
    | | +"\n    "
    | | `
    | |   +"\n        \n\n\n    "
    | |   +
    | |   | `"\n        \n    "
    | |   +"\n    \n\n\n\n\n\n\n\n\n\n    \n\n\n\n\n\n \n\n\n\n\n& "
    | |   +
    | |   | `"FREE Shipping"
    | |   +" on orders over $35.\n\n\n\n"
    | |   +
    | |   | `"Details"
    | |   `"\n\n\n\n\n\n\n\n\n    \n\n    \n    \n\n\n\n\n\n      \n"
    | `"\n"
    +

    | +
    | | `"Deal Price: "
    | +"\n  "
    | +
    | | +"\n    "
    | | +
    | | +"\n    "
    | | +
    | | `"\n  "
    | `"\n"
    +


text:
Q: Separate string after equal number of characters with white space basically what I need is to convert
123456789012345678901234567  to   12345 67890 12345 67890 12345 67
So after each 5th element a white space is inserted. I can do it in old fashioned ways but was wondering if there is a quick alternative.

A: echo join(' ', str_split('123456789012345678901234567', 5));

A: $text = "123456789012345678901234567";
$newtext = wordwrap($text, 5, "\n", true);
echo $newtext;


text:
Q: Issue in formatting date/numeric columns in SSRS matrix report Mine is tablix report, with columns and values. Which are dynamically generating.

Issue is, there are some date and numeric columns which i want to format, and for that i am trying below given expressions:
=IIf(Fields!ColumnName.Value = "Charge",
    FormatCurrency(Fields!Value.Value, 2),
    IIf(Fields!ColumnName.Value = "StartDate",
        FORMAT(CDate(Fields!Value.Value),"MM-dd-yyyy"),
    IIf(Fields!ColumnName.Value = "EndDate",
        FORMAT(CDate(Fields!Value.Value),"MM-dd-yyyy"),
        Fields!Value.Value
    )
  )
 )

OR
=Switch
(
  Fields!ColumnName.Value = "Charge", FormatCurrency(Fields!Value.Value, 2),
  Fields!ColumnName.Value = "StartDate", FORMAT(CDate(Fields!Value.Value),"MM-dd-yyyy"),
  Fields!ColumnName.Value = "EndDate", FORMAT(CDate(Fields!Value.Value),"MM-dd-yyyy"),
  true, Fields!Value.Value
)

OR
=IIF(IsNumeric(Fields!Value.Value), FormatNumber(Fields!Value.Value, 2), Fields!Value.Value)

none of them are working, it changes the number columns correctly and then it gives #Error in every columns.

A: Add the following custom code to your report
Public Function FormatColumn(columnName As String, value AS String) As String

Select columnName
    Case "Charge"
        Return  Format(CLng(value), "c2")
    Case "StartDate"
         Return Format(CDate(value),"MM-dd-yyyy")
    Case "EndDate"
         Return Format(CDate(value),"MM-dd-yyyy")
    Case Else
        Return value
End Select

End Function

Set the cell expression to
= Code.FormatColumn(Fields!ColumnName.Value,Fields!value.Value)


text:
Q: Как отследить наводку курсора мыши на консольное приложение C++ Надо обработать события когда курсор находиться в консольном окне. Надо что-то на подобия функции  TrackMouseEvent только для консоли, то есть когда курсор в консольном окне должно выдавать True и на оборот когда выходит из него должно выдавать False.

A: #include <Windows.h>

bool IsInConsol(const HWND& hwnd,POINT& p)
{
    RECT aRect;
    GetWindowRect(hwnd, &aRect);
    GetCursorPos(&p);
    if (((p.y >= aRect.top) && (p.y <= aRect.bottom)) && ((p.x >=
aRect.left) && (p.x <= aRect.right)))return true;
    return false;
}


text:
Q: Не скрывать элемент если нажат второй блок. Вот пример работы на http://jsfiddle.net/ghkEY/98/

$('.nav__top-level li').click(function(){
var links =  $('.sub-menu li').children();
var arrLinks = [];
links.each(function(index,element)
{
if(index >= 1)
arrLinks.push($(element).attr('href'));''
});
$('#sub-menu a').each(function(index,element){
$(element).attr('href',arrLinks[index]);
console.log(arrLinks);
});
});

Сервис

Без рубрики

instagram

Обувь и Аксессуары

Одежда

Как сделать, чтобы при раскрытом меню, нажав на другой главный пункт меню, текущие элементы заменились бы, но при этом анимация или не сработала бы или раскрылась по новой.?

A:  $('#sub').html(newLinks);
  if ($(this).hasClass('activeMenu')){
   $('.nav__second-level').children('#sub').slideUp('slow');
   $(this).removeClass('activeMenu');
  } else{
      $('.nav__second-level').children('#sub').hide().slideDown('slow');
      $('.menu-item-has-children').removeClass('activeMenu');
      $(this).addClass('activeMenu');
  }

Обновил фидл.
http://jsfiddle.net/moonvvell/ghkEY/101/


text:
Q: Как сделать кастомная функцию sprintf? Как мне сделать кастомную функцию по типу sprintf, с неограниченными задаваемыми параметрами?
Написал такой код:
function customSprintf($format, ...$params)
{
    return sprintf($format, $params);
}

Выводит ворнинг: "Warning: Too few arguments in ..." и возвращает NULL

A: Чтобы передать массив как неограниченный список аргументов нужно тоже использовать троеточие:
function customSprintf($format, ...$params)
{
    return sprintf($format, ...$params);
}

Количество передаваемых аргументов в функцию sprintf должно быть не менее, чем количество аргументов в форматируемой строке, иначе вы так и будете получать предупреждение.
Можно также вручную подсчитать количество аргументов в форматируемой строке и заполнить недостающие аргументы пустыми строками, получив на выходе более лояльную версию sprintf:
function customSprintf($format, ...$params)
{
    if (preg_match_all("~%(?:(\d+)[$])?[-+]?(?:[ 0]|['].)?(?:[-]?\d+)?(?:[.]\d+)?[%bcdeEufFgGosxX]~", $format, $expected) > 0)
    {
        $expected = intval(max($expected[1], count(array_unique($expected[1]))));

        if (count($params) < $expected)
        {
            $n = $expected - count($params);
            $params = array_merge($params, array_fill(0, $n, ''));
        }
    }

    return sprintf($format, ...$params);
}