text:
Q: validating form which is rendered using renderPartial in yii I have more then one forms on one page and I am rendering one form using renderPartial, now if I want to validate it using ajax validation it don't work.
view code
<?php $form=$this->beginWidget('CActiveForm', array(
                'id'=>'bill-shipp-form',
                'action'=>CController::createUrl('cart/index'),
                'enableAjaxValidation'=>true,
                'focus'=>array($billingShippingInfo,'first_name_b'),
                //'enableClientValidation'=>true,
                'clientOptions' => array(
                            'validateOnSubmit' => true,
                            'validateOnChange'=>false,
                            'afterValidate'=>'js:postBillShipp'
                            ),
        )); ?>

and in cart/index I have
if(isset($_POST['ajax']) && $_POST['ajax']==='bill-shipp-form')
        {
            echo CActiveForm::validate($billingShippingInfo);
            Yii::app()->end();
        }

Thanks in advance

A: You should use 4th parameter for render partial:
$this->render('view',$data,false,TRUE);

The 4th paramater is processOutput and you should set it to true
API


text:
Q: Showing a map is orthogonal projection Let $T$ be a self-adjoint linear operator on $H$ =  $\Bbb{C}^n$.
Let $x_j$ be a unit eigen vector cooresponding to $\lambda_j$.
I am also given that $T$ has $n$ distinct eigen values.
Define $P: H \rightarrow H$ as
$P(x) = <x,x_j>.x_j$
Then how can I show that $P$ is orthogonal projection of $H$ onto the eigen space of $T$ corresponding to $\lambda_j$?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What Perl modules are useful for validating subroutine arguments? I'm looking for a general-purpose module to take the drudgery out of validating subroutine and method arguments. I've scanned through various possibilities on CPAN: Params::Validate, Params::Smart, Getargs::Mixed, Getargs::Long, and a few others.
Any information regarding pros and cons of these or other modules would be appreciated. Thanks.

A: If you start to use Moose, you'll find MooseX::Types to your liking. Types automatically have an is_$type(), and to_$type(). These are for making sure you input passes type constraints, or making your input has a valid coercion to the type. I like them better even for these types of things because you can ensure the state of your object has the said types at no additional cost.
use Moose;
has 'foo' => ( isa => MyType, is => ro );

sub _check_my_type {
  my ( $self, $type ) = @_;
  is_MyType( $type );
};

It might be lacking some support for deep/recursive types, but if your using this stuff in modern perl you're probably "doing it wrong." Instead use an object that has its own consistency checks (like mine above with MyType), and just pass the object.

A: Have a look at MooseX::Method::Signatures which provides a bit more than just validating the arguments.
Example from POD:
package Foo;

use Moose;
use MooseX::Method::Signatures;

method morning (Str $name) {
    $self->say("Good morning ${name}!");
}

method hello (Str :$who, Int :$age where { $_ > 0 }) {
    $self->say("Hello ${who}, I am ${age} years old!");
}

method greet (Str $name, Bool :$excited = 0) {
    if ($excited) {
        $self->say("GREETINGS ${name}!");
    }
    else {
        $self->say("Hi ${name}!");
    }
}

MooseX::Method::Signatures also comes as standard with MooseX::Declare which brings even more sexy syntax to the Perl plate.  The above could be written like so (just showing first method for brevity):
use MooseX::Declare;

class Foo {

    method morning (Str $name) {
        $self->say("Good morning ${name}!");
    }
}

There is also a corollary signatures CPAN module for plain subroutines but unfortunately it isn't as feature rich as above.

A: I am currently researching the same question as the O.P.
I noticed that Dave Rolsky - hyper-productive programmer of Moose fame - has recently (2009) taken over maintenance of Params::Validate, so I think this a good sign. The module has not been upgraded since 2003. So I guess, it still can be used again for checking subroutine params.


text:
Q: How to parameterize a date range in a rails (postgres) query? Just like the title asks, how do I include a date range in a query?
For example, let's say I have a model called VisitToGrandma and it has a field called visit_date. Now, I want to find all visits to grandmothers that happened in the last month.
Here is what I'm trying:
VisitToGrandma.where("? @> visit_date", (1.month.ago..Time.now))

However, this produces the query:

SELECT "visits_to_grandmas".* FROM "visits_to_grandmas" WHERE ('2018-07-01','2018-07-02','2018-07-03','2018-07-04','2018-07-05','2018-07-06','2018-07-07','2018-07-08','2018-07-09','2018-07-10','2018-07-11','2018-07-12','2018-07-13','2018-07-14','2018-07-15','2018-07-16','2018-07-17','2018-07-18','2018-07-19','2018-07-20','2018-07-21','2018-07-22','2018-07-23','2018-07-24','2018-07-25','2018-07-26','2018-07-27','2018-07-28','2018-07-29','2018-07-30','2018-07-31','2018-08-01' @> visit_date)

What's the correct way to parameterize this?
Yes, I know for this fictional example, I can just use the start and end date and use BETWEEN or some other operators to do this without using an actual date range, but that's not what I'm asking about.
Edit to point out how this question is different from the other question:
That question is just about finding a date in a range, my question is asking how to actually parameterize a range object so that all of postgresql's daterange operators can be used.

A: As I recently mentioned in another PostgreSQL/range/ActiveRecord answer, AR's integration with PostgreSQL's range types is limited.
You can get around that by semi-manually producing the string representation of the range you want:
ActiveRecord::Base.connection.type_cast(1.month.ago.to_date .. Time.now.to_date)

Not the #to_date calls to get dates rather than timestamps. You could also say:
today = Date.today
ActiveRecord::Base.connection.type_cast(today.months_ago(1) .. today)

Mixing that in with your query:
today = Date.today
VisitToGrandma.where(
  '? @> visit_date',
  VisitToGrandma.connection.type_cast(today.months_ago(1) .. today)
)

Depending on context, you might have easier/cleaner access to connection. You might want to include a typecast just to be sure nothing is misinterpreted:
today = Date.today
VisitToGrandma.where(
  '?::daterange @> visit_date',
  VisitToGrandma.connection.type_cast(today.months_ago(1) .. today)
)

A: It seems you'll need to abuse a bit of where placeholders to accomplish this with ActiveRecord
VisitToGrandma.where(
  ":range::daterange @> date",
  range: '[2011-01-01,2011-03-01)'
)

Note the symbols [ and ) in the range, more information on the Postgres doc
https://www.postgresql.org/docs/current/static/rangetypes.html#RANGETYPES-IO


text:
Q: ssh command to run remote script exist shell on remote server when switching user When I run a script such as this:
ssh -t root@10.10.10.10 '/tmp/somescript.sh'

where the script is defined as:
#!/bin/sh
mkdir -p /data/workday/cred
chown -R myuser:myuser /data
su myuser -  # <------- NOTICE THIS ! ! ! !
rpm -Uvp --force --nodeps --prefix /data/place /data/RPMs/myrpm.rpm

Notice the above su command.
If I comment-out the su command, the script runs remotely and then my shell prompt returns to where I came from ( same server where I ran the ssh command above )
But leaving the script as listed above, causes the script to complete successfully but the shell prompt stays on the remote server.
How can I prevent that ? Making sure that the issuer of the rpm command is a different user than root just a listed ?

A:
But leaving the script as listed above, causes the script to complete successfully but the shell prompt stays on the remote server.

Not exactly. The script is running up to the su command, which spawns a new subshell, and stopping there until you exit the shell. Until you exit that shell, the rpm command never runs, and when it does, it runs as root.
If you want to run the rpm command as a non-root user, you'd need to do something a little different, like:
sudo -u myuser rpm -Uvp ...

A: add 'exit' at the end of your script


text:
Q: Resize Ext.form.ComboBox to fit its content There are quite few solutions on Ext forums, but I wasn't able to get any of them work. It seems I am missing something minor.
I need to resize combobox to fit its content when it's first created. I do not need to worry about resizing it when content is changing.
Is there any working examples using Extjs 3.2?
Current Code:
var store = new Ext.data.ArrayStore({
    fields: ['view', 'value', 'defaultselect'],
    data: Ext.configdata.dataCP
});

comboCPU = new Ext.form.ComboBox({
    tpl: '<tpl for=".">
{view}

</tpl>',
    store: store,
    displayField: 'view',
    width: 600,
    typeAhead: true,
    forceSelection: true,
    mode: 'local',
    triggerAction: 'all',
    editable: false,
    emptyText: 'empty text',
    selectOnFocus: true,
    listeners: { select: AdjustPrice, change: AdjustPrice, beforeselect: function (combo, record, index) { return ('false' == record.data.disabled); } },
    applyTo: 'confelement'
});

I've also tried removing width: 600 and replacing it with minListWidth: 600 but that result following and didnt fix the issue.
alt text http://img28.imageshack.us/img28/7665/4272010105134am.png

A: Try the following:

*

*Determine the list-box option with the most chars

*Create a div and set the option with the most chars

*Append this div to the body

*Get the div's clientWidth

Below codes works in ExtJs 3.2!
myStore = new Ext.data.Store({
 ...
listeners : {
            load: function() {
                var maxValue = "";
                var charLen = 0, maxCharLen = 0;
                var maxListWidth = 300;

                /**
                 * This is a work-around since the 'listWidth' property
                 * does not accept any values that would simulate auto-resize
                 * in reference to the category with the most characters.
                 */
                this.data.each(function(item, index, totalItems ) {
                    var nameValue = item.data['name']; // 'name' is the field name

                    if(nameValue == null || nameValue == ''){
                        // do nothing
                    }else {
                        charLen = nameValue.length;
                        if(charLen > maxCharLen){
                            maxCharLen = charLen;
                            maxValue = nameValue;
                        }
                    }
                });

                if(maxValue != ""){
                    var divEl = document.createElement('div');
                    divEl.id = 'tempEl';
                    divEl.style.display = "inline";
                    divEl.className = "x-combo-list";
                    divEl.innerHTML = maxValue;

                    document.body.appendChild(divEl);

                    // check if appended
                    divEl = document.getElementById('tempEl');
                    if(divEl) {
                        var divWidth = divEl.clientWidth;
                        if(divWidth == 0 ) {
                            divEl.style.display = "inline-block";
                            divWidth = divEl.clientWidth;
                        }

                        // the allocated width for the scrollbar at side of the list box
                        var scrollbarWidth = 30;

                        // make sure that column width is not greater than
                        if((divWidth + scrollbarWidth) > maxListWidth) {
                            maxListWidth = divWidth + scrollbarWidth;
                            myCombo.listWidth = maxListWidth;
                        }
                        document.body.removeChild(divEl);
                    }
                }
            }
});

var myCombo = new fm.ComboBox({
 ...
});

A: try
autoWidth: true
and remove the width parameter

A: width: 600 is correct, so you must have some other issue going on that's not obvious from what you posted.  You might try removing the applyTo config and instead put renderTo: Ext.getBody() just to see if it has something to do with how it's applied to your element.  Are you sure there is not some other code that could be affecting the width?

A: Found here:
// throw this stuff in a closure to prevent
// polluting the global namespace
(function(){

    var originalOnLoad = Ext.form.ComboBox.prototype.onLoad;
    Ext.form.ComboBox.prototype.onLoad = function(){
        var padding = 8;
        var ret = originalOnLoad.apply(this,arguments);
        var max = Math.max(this.minListWidth || 0, this.el.getWidth());
        var fw = false;
        Ext.each(this.view.getNodes(), function(node){
            if(!fw){ fw = Ext.fly(node).getFrameWidth('lr'); }
            if(node.scrollWidth){ max = Math.max(max,node.scrollWidth+padding); }
        });
        if( max > 0 && max-fw != this.list.getWidth(true) ){
            this.list.setWidth(max);
            this.innerList.setWidth(max - this.list.getFrameWidth('lr'));
        }
        return ret;
    };

})();


text:
Q: split rowcount of a table by 3 ways in perl I am getting rowcount of a sybase table in perl. For example table have 100 rows, so n=100
I want to split this value into 3 parts
1-33 | 34-66 | 67-99 or 100
please advise how do get this in perl.
Reason for this split: I need to pass the values 1 and 33 as input parameter to a stored proc to select rows whose identity column value is between 1 and 33.
same goes for 34-66 & 67-99

A: The interesting part is deciding where each range starts. From there it's easy to decide that each range ends at one less than the start of the next range.
This partition() function will determine the start points for given number of partitions within a given number of elements starting at a given offset.
sub partition {
    my ($offset, $n_elements, $n_partitions) = @_;

    die "Cannot create $n_partitions partitions from $n_elements elements.\n"
        if $n_partitions > $n_elements;

    my $step = int($n_elements / $n_partitions);

    return map {$step * $_ + $offset} 0 .. $n_partitions - 1;
}

Here's how it works:
First, determine what the step should be by dividing the number of elements by the number of partitions, and preserving the integer by truncating any trailing decimal places.
Next walk through the steps by starting at zero and multiplying by the step number (or the partition number).  So if the step is 5 then 5*0=0, 5x1=5, 5x2=10, and so on.  We will not look at the last step, because it makes more sense to include an "off by one" in the last partition than to start a new partition with only one element.
Finally, we allow for an offset to be applied, so that partition(0,100,5)means to find the starting element positions for five partitions starting at zero and continuing for 100 elements (so a range of 0 to 99).  And partition(1,100,5) would mean start at 1 and continue to 100 elements partitioning in five segments, so a range of 1 to 100.
Here's an example of putting the function to use to find the partition points in a set of several ranges:
use strict;
use warnings;
use Test::More;

sub partition {
    my ($offset, $n_elements, $n_partitions) = @_;

    die "Cannot create $n_partitions partitions from $n_elements elements.\n"
        if $n_partitions > $n_elements;

    my $step = int($n_elements / $n_partitions);

    return map {$step * $_ + $offset} 0 .. $n_partitions - 1;
}

while(<DATA>) {
    chomp;
    next unless length;

    my ($off, $n_elems, $n_parts, @starts) = split /,\s*/;

    local $" = ',';

    is_deeply
        [partition($off, $n_elems, $n_parts)],
        [@starts],
        "Partitioning $n_elems elements starting at $off by $n_parts yields start positions of [@starts]";
}

done_testing();

__DATA__
0,10,2,0,5
1,11,2,1,6
0,3,2,0,1
0,7,3,0,2,4
0,21,3,0,7,14
0,21,7,0,3,6,9,12,15,18
0,20,3,0,6,12
0,100,4,0,25,50,75
1,100,4,1,26,51,76
1,100,3,1,34,67
0,10,1,0
1,10,10,1,2,3,4,5,6,7,8,9,10

This yields the following output:
ok 1 - Partitioning 10 elements starting at 0 by 2 yields start positions of [0,5]
ok 2 - Partitioning 11 elements starting at 1 by 2 yields start positions of [1,6]
ok 3 - Partitioning 3 elements starting at 0 by 2 yields start positions of [0,1]
ok 4 - Partitioning 7 elements starting at 0 by 3 yields start positions of [0,2,4]
ok 5 - Partitioning 21 elements starting at 0 by 3 yields start positions of [0,7,14]
ok 6 - Partitioning 21 elements starting at 0 by 7 yields start positions of [0,3,6,9,12,15,18]
ok 7 - Partitioning 20 elements starting at 0 by 3 yields start positions of [0,6,12]
ok 8 - Partitioning 100 elements starting at 0 by 4 yields start positions of [0,25,50,75]
ok 9 - Partitioning 100 elements starting at 1 by 4 yields start positions of [1,26,51,76]
ok 10 - Partitioning 100 elements starting at 1 by 3 yields start positions of [1,34,67]
ok 11 - Partitioning 10 elements starting at 0 by 1 yields start positions of [0]
ok 12 - Partitioning 10 elements starting at 1 by 10 yields start positions of [1,2,3,4,5,6,7,8,9,10]
1..12

For additional examples look at Split range 0 to M into N non-overlapping (roughly equal) ranges. on PerlMonks.
Your question is looking for complete range start and end points. This method makes it rather trivial:
sub partition {
    my ($offset, $n_elements, $n_partitions) = @_;
    my $step = int($n_elements / $n_partitions);
    return map {$step * $_ + $offset} 0 .. $n_partitions - 1;
}

my $n_elems = 100;
my $offset  = 1;
my $n_parts = 3;

my @starts = partition($offset, $n_elems, $n_parts);

my @ranges = map{
    [
        $starts[$_],
        ($starts[$_+1] // $n_elems+$offset)-1,
    ]
} 0..$#starts;

print "($_->[0], $_->[1])\n" foreach @ranges;

The output:
(1, 33)
(34, 66)
(67, 100)

Even more implementation examples appear in Algorithm for dividing a range into ranges and then finding which range a number belongs to on the StackExchange Software Engineering forum.


text:
Q: How can I change the order of my Bootstrap columns? Here is how the blocks are positioned on desktop within a row class which looks  good on desktop.

Unfortunately, on xs device this looks not the way we need. I need this order when it's displayed on extra-small device:
1
3
2

Solution that doesn't work: I can't place the block 3 into block 1, as I need full width of block 3 on desktop (the 100% of the screen width, not the 100% of the block 1).
Any ideas how to change the order of 2nd and 3rd blocks with pure css on xs-devices so it is as
1
3
2

,
and not
1
2
3

as it is now?
Thank you.

A:
Any ideas how to change the order of 2nd and 3rd blocks with pure CSS
  on xs-devices so it is as

Try this:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
        crossorigin="anonymous">

You might consider this solution in case there's no solution out there can help achieve your required behaviour with pure CSS

A: It is important to also include Container and Row.
https://getbootstrap.com/docs/4.0/layout/grid/
Does the original code look like this?

      1

      2

      3

A: You cannot change the order of columns in smaller screens but you can do that in large screens.
So change the order of your columns.

By default this displays the main content first.
So in mobile main content is displayed first.
By using col-lg-push and col-lg-pull we can reorder the columns in large screens and display sidebar on the left and main content on the right.
Column Reordering in Bootstrap

A: Assuming block 2 has a fixed height and its always at most the same height with block one, you can do the following:
CSS:

HTML:

Block1

Block 3

Block 2

Please note that with this method, if block 2 is longer than block one, it will overflow on block 3.


text:
Q: Android : Touch events in layout after animation I have a LinearLayout which contains only a ListView. LinearLayout fills the entire screen and the listView at first stays at the bottom quarter of the screen. I am setting Top Margin of ListView to a big value to keep the listView at the bottom of the screen. Below illustration might  help you to understand my layout better.

Now on a button click I want my listView to slide up and fill the screen. I am using Translate animation just like this
TranslateAnimation animation = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF,0.0f
                                ,Animation.RELATIVE_TO_SELF, 0.0f
                                ,Animation.RELATIVE_TO_SELF,0.0f
                                ,Animation.RELATIVE_TO_SELF, -0.70f);
animation.setDuration(1000);
animation.setFillAfter(true);
animation.setFillEnabled(true);
mBottomView.startAnimation(animation);

where mBottomView is my Listview Layout. And this code successfully animates the listView to the top.
Now my problem is when listView fills the screen, and I try to scroll, touch events to the listview is not recognized above listview's original position. ie when I touch anywhere in the yellow space (in the image) to scroll the listView, touch is not getting detected. I am able to scroll below the listView's original position. Why is that?

A: I faced same problem and the answer to this problem is completely defined in the answer of this question.
EditText stucks after animation and alive back on scrolling......?


text:
Q: PlayFramework activator run bug I'm new in play, and i am trying run my app, but It is happening this error:
"
error: error while loading <root>, zip file is empty
scala.reflect.internal.MissingRequirementError: object scala.runtime in compiler mirror not found.
    at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:16)
    at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:17)
    ...

[error] scala.reflect.internal.MissingRequirementError: object scala.runtime in compiler mirror not found.

"
I need fix it, but i dont know!!!!
can anyone help me?


text:
Q: Question on Rudin's Proof of the Residue Theorem The Theorem in question is Theorem 10.42.: If $f$ is meromorphic in $U$, $A$ is the set of poles of $f$ and $\Gamma$ is a cycle in $U-A$ so that $Ind _{\Gamma}=0$ in $U^c$ then
\begin{equation}\frac 1{2\pi i}\int_{\Gamma}f=\sum_{a\in A}Ind_{\Gamma}(a)Res_f(a)
\end{equation}
My problem is with the first part of the proof, i.e. proving that the sum, or equivalently the set $B=\left\{a\in A:Ind_{\Gamma}(a)\neq 0\right\}$ is finite. The proof goes like this:
Every component $V$ of $(\Gamma^*)^c$ (that is a component of the interior, or the exterior of $\Gamma$) that is unbounded or intersects $U^c$ is in the exterior of $\Gamma$ ($Ind_{\Gamma}=0$ in $V$). Since $A$ has no limit points in $U$, we conclude that $B$ is a finite set.
How exactly do we conclude that? The arguments made before that are pretty obvious but this one is not. I am thinking that $B$ is bounded and with no limit points, but that does not make it finite right?

A: Any set $B$ which is bounded and has no limit points must be finite.
Otherwise you can find a sequence $x_n \in B$ with $x_n \neq x_m, \forall m \neq n$.
Since $B$ is bounded, its closure is bounded and closed, thus compact. Hence $x_n$ has a subsequence which is convergent in $\bar{B}$. But then, the limit is a limit point for $B$.


text:
Q: How to stop GitLab from evaluating $ inside variable value? I am passing GitLab variable while running CI/CD pipeline as below.
type - variable
key - password
value - {"a": "abc$def@pqr"}

I am reading it in some GitLab pipeline stage as below.
echo $password

It is showing as below.
{"a":"abc@pqr"}

But I want it to show as below.
{"a":"abc$def@pqr"}

I don't want it to evaluate $def as blank
Note:

*

*I tried with \ escaping and with single quotes too.

*I need this to be in json kind of format itself for further use.

A: Works fine on using double $$ instead of single $


text:
Q: How to P/Invoke WaveOut API on Windows CE 6.0 R3 How to P/Invoke WaveOut API on Windows CE 6.0 R3 ?
When I put this
[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MMRESULT waveOutOpen(ref IntPtr hWaveOut, int uDeviceID, ref WAVEFORMATEX lpFormat, DelegateWaveOutProc dwCallBack, int dwInstance, int dwFlags);

[DllImport("winmm.dll")]
public static extern MMRESULT waveInOpen(ref IntPtr hWaveIn, int deviceId, ref WAVEFORMATEX wfx, DelegateWaveInProc dwCallBack, int dwInstance, int dwFlags);

[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT waveInStart(IntPtr hWaveIn);

[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint waveInGetDevCaps(int index, ref WAVEINCAPS pwic, int cbwic);

[DllImport("winmm.dll", SetLastError = true)]
public static extern uint waveInGetNumDevs();

[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint waveOutGetDevCaps(int index, ref WAVEOUTCAPS pwoc, int cbwoc);

[DllImport("winmm.dll", SetLastError = true)]
public static extern uint waveOutGetNumDevs();

[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MMRESULT waveOutWrite(IntPtr hWaveOut, ref WAVEHDR pwh, int cbwh);

[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MMRESULT waveOutPrepareHeader(IntPtr hWaveOut, ref WAVEHDR lpWaveOutHdr, int uSize);

It works on Window XP, 7 but throws a message "Can't P/Invoke winmm.dll" on Wnidows CE 6.0.
What am I doing wrong? Is the WaveOut API moved to some other dll or is it something else ?
Anyway SoundPlayer (from .NET Compact Framework 3.5) works correctly.

A: Change winmm.dll to coredll.dll and you are done !


text:
Q: Persona automatically logs me out right after login Well, this is my persona setup:
$ ->
    $('#login-btn').click (e) ->
        e.preventDefault()
        navigator.id.request()
        false
    $('#logout-btn').click (e) ->
        e.preventDefault()
        navigator.id.logout()
        false

    current_user = window.current_user or null

    navigator.id.watch
        loggedInUser: current_user
        onlogin: (assertion) ->
            ($.post '/verify', assertion: assertion, (response) ->
                if response.success
                    window.location.reload()
                else
                    console.log response
            ).fail (err) -> console.log err
        onlogout: () ->
            $.post '/logout', () ->
                window.location.reload()

The /verify and /logout paths just initialise the session. It works fine, the user is added to the database, which means the login is successful. I get to see the logged in screen for a moment, but then suddenly, the site reloads and I am logged out again. Every time.
During that brief moment, I was able to cancel the reload and could see that the email in window.current_user was correctly set as well.
So why does this happen?

A: Do you happen to have disabled third-party cookies, by any chance?


text:
Q: How to import the script that instantiated a class I am trying to call functions in the script that instantiated a class from the script with the class. Thx for the help.
I tried importing the script at the top of the class but it didn't work.


text:
Q: I am unable to boot into Ubuntu 12.10. no matching password file entry in /etc/shadow add user I am unable to boot into Ubuntu 12.10. I have Windows 7 installed as well. The GRUB seems fine. I can boot into Windows. But when I boot into Ubuntu , the following appears.
"no matching password file entry in /etc/shadow add user 'varun'"

A: This means your /etc/shadow file is missing user varun. Information about the /etc/passwd and /etc/shadow can be found here.
Use a live CD or a GRUB rescue prompt. For the 2nd one follow the answer with images here How do I reset a lost administrative password?
Have a look at your /etc/passwd file with more /etc/passwd|grep varun  and at your /etc/shadow file with sudo more /etc/shadow|grep varun. if the 1st does contain a line and the 2nd does not you can re-create your shadow file with the command
sudo pwcon
After that you can use passwd varun to create a new password.


text:
Q: Solving Difference Equation I have the following equation:
$$\frac{Z-1}{{Z^2}-2Z+6}$$
I tried to apply difference equation on it:
$$y_{n+2}-5y_{n-1}-6y_n = x_{n+1}-x_n$$
I need to find equation expressed as $y_n$
I have the answer (At the end of the chapter) to be:
$$y_n = 5y_{n-1}-6y_{n-2}+x_{n-1}-x_{n-2}$$
Can somone please tell me how did in this case the second equation expressd as $y_n$ ? I cant figure it out!

A: The differences between your equation and the book's are:
the index has been shifted by 2
the sign on the 6 has been corrected
two terms have been moved to the other side
To see the index shift, define $m=n+2$ and substitute it in.
Also, the $2$ in the denominator has become $5$ in both your solution and the book's.  Did you copy it correctly?


text:
Q: outer product of matrix rows (e.g. A(i,:)^T * A(i,:) for all rows i) + mean of same element in all submatrices created I'm trying to calculate the outer product of all rows in a matrix. So far I'm doing the following:
A = rand(10,8);
[N J] = size(A);
for i = 1:N,
    B(((i-1)*J+1):J+((i-1)*J),:) = A(i,:)'*A(i,:)
end

I then take the mean of the same elements of the same row in each submatrix created above.
for j=1:J,
    C(1:J,j) = accumarray(repmat((1:J)',N,1),B(:,j)).*(1/N);
end

Now this works, but my input matrix will eventually be a number of magnitudes larger, so a vectorized version would be nice. I assume there is some way to do this with permute and bsxfun but the solutions for outer product I have seen so far don't seem to apply here.

A: Sure. You can compute C directly as
C = mean(bsxfun(@times, permute(A, [2 3 1]), permute(A, [3 2 1])), 3);

Or, if you really need the B variable, you can do it this way:
B_3D = bsxfun(@times, A.', permute(A,[3 1 2])); %'// 3D array
B = reshape(B_3D, numel(A), []);
C = mean(permute(B_3D, [1 3 2]), 3);


text:
Q: Can't initialize UITableViewCell if (cell == nil) {

//cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 260, 44) reuseIdentifier:CellIdentifier] autorelease];

//The line above works like a breeze

cell = [[[UITableViewCell alloc] initWithStyle:initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];   //This is the line that is causing me problems
}

These are the error logs:
/Users/myname/Downloads/myApp/Classes/MyTableView.m: In function '-[MyTableView tableView:cellForRowAtIndexPath:]':

/Users/myname/Downloads/myApp/Classes/MyTableView.m:88: error: 'initWithStyle' undeclared (first use in this function)

/Users/myname/Downloads/myApp/Classes/MyTableView.m:88: error: (Each undeclared identifier is reported only once

/Users/myname/Downloads/myApp/Classes/MyTableView.m:88: error: for each function it appears in.)

/Users/myname/Downloads/myApp/Classes/MyTableView.m:88: error: 'UITableViewCellStyleValue1' undeclared (first use in this function)

/Users/myname/Downloads/myApp/Classes/MyTableView.m:88: warning: no '-initWithStyle::reuseIdentifier:' method found

/Users/myname/Downloads/myApp/Classes/MyTableView.m:88: warning: (Messages without a matching method signature

/Users/myname/Downloads/myApp/Classes/MyTableView.m:88: warning: will be assumed to return 'id' and accept

/Users/myname/Downloads/myApp/Classes/MyTableView.m:88: warning: '...' as arguments.)

A: The correct method is
initWithStyle:reuseIdentifier:

You are using instead
initWithStyle:initWithStyle:reuseIdentifier:

Simply delete the redundant initWithStyle: and it will work.

A: Are you compiling for OS 3? I don't believe UITableViewCellStyleValue1 existed in OS 2...

A: UITableViewCellStyleValue1 was not defined in SDKs prior to 3.0.  Check the SDK you are using.


text:
Q: Set duration of CakePHP session after successful login I have a CakePHP application that allows login using basic Auth. Each user has a specific role  such as "normal", "admin", etc..
Is there a way to set how long they can remain logged in for before it requires them to log back in?
Ideally, I'd like a regular user to be 1 hour, and an admin to be 14 hours.
Thanks!


text:
Q: Converting row data into column in Mysql Dynamically I have written query as
    SELECT  c.customer_name, o.net_total,
  GROUP_CONCAT(
      'SUM(IF(ps.product_sku_name = ''',
      product_sku_name,
      ''',  o.net_total,0)) AS ',
      product_sku_name

  )
FROM products_sku ps
LEFT JOIN products  AS p
                    ON p.product_id = ps.product_id
                    left join order_lines ol on ol.product_sku_id = ps.product_sku_id
                    left join orders o on o.order_id = ol.order_id
                    left join customers c on c.customer_id = o.customer_id
                   GROUP BY ps.product_sku_id

And got result as
customer_name     net_total    GROUP_CONCAT( 'SUM(IF(ps.product_sku_name = ''', product_sku_name, ''', o.net_total,0)) AS ', product_sku_name )
Customer2         126.0000     SUM(IF(ps.product_sku_name = 'PSKU Name 1',  o.net_total,0)) AS PSKU Name 1,SUM(IF(ps.product_sku_name = 'PSKU Name 1',  o.net_total,0)) AS PSKU Name 1,SUM(IF(ps.product_sku_name = 'PSKU Name 1',  o.net_total,0)) AS PSKU Name 1
Customer1         105.0000     SUM(IF(ps.product_sku_name = 'PSKU Name2',  o.net_total,0)) AS PSKU Name2
NULL              NULL         SUM(IF(ps.product_sku_name = 'PSKU Name3',  o.net_total,0)) AS PSKU Name3
NULL              NULL        SUM(IF(ps.product_sku_name = 'Product SKU 4',  o.net_total,0)) AS Product SKU 4
Customer1         945.0000    SUM(IF(ps.product_sku_name = 'PSKU Name4',  o.net_total,0)) AS PSKU Name4
Customer1         2159.3600   SUM(IF(ps.product_sku_name = 'Jordon',  o.net_total,0)) AS Jordon,SUM(IF(ps.product_sku_name = 'Jordon',  o.net_total,0)) AS Jordon

And  i expect result as
customer_name       PSKU Name 1    PSKU Name 2    PSKU Name 3  PSKU Name 4 Jordon
Customer2           126            NULL           NULL         NULL        NULL
Customer1           NULL           105            NULL         945         2159

I have referred MySQL pivot table query with dynamic columns site for making this query
Please reply ... Thanks in advance

A: Your attempt got part way toward building a query.  But you need a stored procedure to build and execute it.
See http://mysql.rjweb.org/doc.php/pivot for such code.


text:
Q: Tensorflow shows errors after importing using python I installed Tensorflow using pyenv. But whenever i import it gives me this error.I am using Debian in raspberry pi4.My python version is 3.7.12 and tensorflow version is 2.5.0.
'''  pi@raspberrypi:~/project $ python
Python 3.7.12 (default, Mar 22 2022, 14:27:41)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.

import tensorflow
RuntimeError: module compiled against API version 0xe but this version of numpy is 0xd
Traceback (most recent call last):
File "", line 1, in
File "/home/pi/.pyenv/versions/3.7.12/lib/python3.7/site-packages/tensorflow/init.py", line 41, in
from tensorflow.python.tools import module_util as _module_util
File "/home/pi/.pyenv/versions/3.7.12/lib/python3.7/site-packages/tensorflow/python/init.py", line 40, in
from tensorflow.python.eager import context
File "/home/pi/.pyenv/versions/3.7.12/lib/python3.7/site-packages/tensorflow/python/eager/context.py", line 37, in
from tensorflow.python.client import pywrap_tf_session
File "/home/pi/.pyenv/versions/3.7.12/lib/python3.7/site-packages/tensorflow/python/client/pywrap_tf_session.py", line 23, in
from tensorflow.python._pywrap_tf_session import *
ImportError: SystemError: <built-in method contains of dict object at 0x7f741852d0> returned a result with an error set
'''

A: The error message tries to say that Tensorflow needs a recent version of numpy. So,try to upgrade numpy pip3 install --upgrade numpy


text:
Q: Git clone over http not asking for authentication I have implemented a private git server over http using the git documentation and added a few users.
The problem is that it allows me to clone or pull without authentication it only asks for user and pass when I make a push.

A: The documentation link only restricts pushes because it looks for git-receive-pack, which is the push code.  git-upload-pack is the clone and fetch code (the names refer to the server's activity).
If you want to restrict all access, remove the line which looks like this:
    Require expr !(%{QUERY_STRING} -strmatch '*service=git-receive-pack*' || %{REQUEST_URI} =~ m#/git-receive-pack$#)


text:
Q: GNU Prolog simple program doesn't work as expected EDIT : I've just compiled gprolog from sources.
It works fine. The version 1.4.5 in the Debian repo is bugged.
It's my first program in GNU Prolog (gprolog) without any success. :-(
I found these exercises in a Prolog tutorial.
GNU Prolog 1.4.5 (64 bits)
Compiled Feb  5 2017, 10:30:08 with gcc
By Daniel Diaz
Copyright (C) 1999-2016 Daniel Diaz
compiling /home/aubin/Dev/Prolog/overview/parents.prolog for byte code...
/home/aubin/Dev/Prolog/overview/parents.prolog compiled, 39 lines read - 2555 bytes written, 3 ms
| ?- grandPere( GrandPere, eve ).
uncaught exception: error(existence_error(procedure,pere/0),grandPere/0)
| ?- parent( PereOuMere, eve ).
uncaught exception: error(existence_error(procedure,pere/0),parent/0)
| ?- parents( Pere, Mere, eve).

no
| ?- parents( aubin, muriel, X ).

no
| ?- frere_ou_soeur( X, aubin ).

no
| ?- listing.

% file: /home/aubin/Dev/Prolog/overview/parents.prolog

pere(joseph, michel).
pere(michel, aubin).
pere(michel, brigitte).
pere(michel, sylvie).
pere(alain, muriel).
pere(aubin, eve).

mere(colette, muriel).
mere(muriel, eve).

grandPere(A, B) :-
    pere(A, C),
    pere(C, B).

parent(A, B) :-
    pere(A, B).
parent(A, B) :-
    mere(A, B).

frere_ou_soeur(A, B) :-
    A \= B,
    parent(C, A),
    parent(C, B).

parents(A, B, C) :-
    A \= B,
    A \= C,
    B \= C,
    pere(A, C),
    mere(B, C).

yes

The expected answers are :
grandPere( GrandPere, eve ). ==> GrandPere = michel
parent( PereOuMere, eve ).   ==> PereOuMere = aubin, PereOuMere = muriel
parents( Pere, Mere, eve).   ==> Pere = aubin, Mere = muriel
parents( aubin, muriel, X ). ==> Enfant = eve
frere_ou_soeur( X, aubin ).  ==> X = brigitte, X = sylvie

First line of the source is:
#!/usr/bin/gprolog --consult-file

And the invocation is:
$ gprolog --consult-file parents.prolog
GNU Prolog 1.4.5 (64 bits)
Compiled Feb  5 2017, 10:30:08 with gcc
By Daniel Diaz
Copyright (C) 1999-2016 Daniel Diaz
compiling /home/aubin/Dev/Prolog/overview/parents.prolog for byte code...
/home/aubin/Dev/Prolog/overview/parents.prolog compiled, 39 lines read - 2555 bytes written, 3 ms
| ?- grandPere( GrandPere, eve ).
uncaught exception: error(existence_error(procedure,pere/0),grandPere/0)
| ?-

A: It seems that invoked with a file name, gprolog validates it but does not load its content into the interpreter. In order to load the file content you have to use the --consult-file command line option:
$ gprolog --consult-file parents.prolog
GNU Prolog 1.4.5 (64 bits)
Compiled Jul 14 2018, 19:58:18 with clang
By Daniel Diaz
Copyright (C) 1999-2018 Daniel Diaz
compiling /private/tmp/parents.prolog for byte code...
/private/tmp/parents.prolog compiled, 31 lines read - 2474 bytes written, 9 ms
| ?- mere(muriel, eve).

yes
| ?- grandPere( GrandPere, eve ).

GrandPere = michel ?

yes

Read about the usage of gprolog on its documentation page.


text:
Q: How I know if my input type="file" has content selected i have a simple input file <input type="file" name="file" id="file">
but I'm trying to validate after the post if the input file has content.
I trying with $("#file").val() but, the dom of the controls is the same always.

A: try to get the value after the form submission like this
$('#yourform').submit(function(){
     var val = $("#file").val();
    if(val == ''){
       return false;
    }
});

A: What do you mean by: after the post, do you mean:
-After clicking on a submit button but before posting or submitting?
-Or you mean after it has been submitted and the content has reached the server?
If it is the first case, make sure to return false to the form so it doesn't submit, and you can validate, for example:
<form onsubmit="return false">

or try to return a boolean to the form after calling a validation function on submit:
<form onsubmit="return validate()">

Then using Jquery validate your data:
function validate(){

  valid = true;

     if($("#file").val() == ''){
         // your validation error action
        valid = false;

     }

    return valid //true or false
}

if you find errors return false, if the data is valid return true.
After understanding how it works, ultimately, all of this can be done with Jquery:
HTML:
<form id="fileform" action="nextpage.php">

JS:
$('#fileform').submit(function(){
     valid = true;

     if($("#file").val() == ''){
        // your error validation action
        valid =  false;
    }

    return valid
});

Also, if you are checking to see what type of file is being submitted, you can check this post: jQuery - INPUT type=File , Image FileType Validation options?
If what you want to do is validate the data AFTER submitting then you have to code the validation in a server scripting language like PHP.

A:
trying to validate after the post

This would be something you would do server-side not on the client via jQuery.  If you tag your question with the server-side language you're using we can then provide you with the help you need.


text:
Q: How to fix AppHarbor : Value cannot be null. Parameter name: EndpointHost.Config I deploy my ServiceStack to AppHarbor. On local, my ServiceStack work well. On AppHarbor build success but when i run http://cerp.apphb.com/api it has error
Value cannot be null.
Parameter name: EndpointHost.Config

How to fix this error

A: I changed
diff --git a/src/CloudErp/Web.config b/src/CloudErp/Web.config
index 7c971ea..94f71a8 100644
--- a/src/CloudErp/Web.config
+++ b/src/CloudErp/Web.config
@@ -28,6 +28,7 @@
   <!-- ServiceStack: CustomPath /api -->
   <location path="api">
     <system.web>
+      <customErrors mode="Off" />
       <httpHandlers>
         <add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
       </httpHandlers>
@@ -42,7 +43,7 @@
     </system.webServer>
   </location>
   <system.web>
-    <compilation debug="true" />
+    <compilation debug="true" targetFramework="4.0"/>
     <!--
       The <authentication> section enables configuration
       of the security authentication mode used by
@@ -70,6 +71,7 @@
   </system.web>
   <system.webServer>
     <validation validateIntegratedModeConfiguration="false" />
+    <modules runAllManagedModulesForAllRequests="true" />
   </system.webServer>
   <system.data>
     <DbProviderFactories>

And It worked now

A: You need to provide more information, like how and where you're initializing your AppHost, e.g
public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        new AppHost().Init();
    }
}

One reason why this could happen is that your AppHost was not initialized correctly like when an exception was thrown on Startup. You'd need to refer to the error logs to see what the issue was.


text:
Q: How to call a function from within another function? I am creating a simple GUI program to manage priorities. I am having troubles with accessing a function from within another function. In my program, I tried to create an instance of the GuiPart class and then calling g.addItem but it doesn't seem to work like that. I am getting an error:
/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
Traceback (most recent call last):
 File "/home/cali/PycharmProjects/priorities/priorities.py", line 70, in > <module>
   g.display()
 File "/home/cali/PycharmProjects/priorities/priorities.py", line 39, in > display
   command = g.addItem)
 File "/usr/lib/python3.5/tkinter/__init__.py", line 2077, in grid_configure
   + self._options(cnf, kw))
_tkinter.TclError: bad option "-command": must be -column, -columnspan, -in, > -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky

Here is what I have done:
# priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:

    def __init__(self, subject, priority):
        self.subject = subject
        self.priority = priority

    def subject(self):
        return self.subject

    def priority(self):
        return self.priority

class GuiPart:

    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def createWidgets(self):

        listBox = Listbox().grid(row=1)

        buttonAdd = Button(text = "Add").grid(row = 2,
                                  column = 0,
                                  sticky = W,
                                  command = g.addItem)

        buttonRemove = Button(text="Remove").grid(row = 2,
                                   column = 0,
                                   sticky = W,
                                   command = g.removeItem)

        buttonEdit = Button(text="Edit").grid(row = 2,
                                 column = 0,
                                 sticky = E,
                                 command = g.editItem)

        textBox = Text().grid(row = 3)

    def addItem(self, item):
        item = Priority(item.subject, item.priority)
        item.subject = g.textBox.get("1.0", 'end-1c')

        g.listBox.insert(END, self)

    def removeItem(self):
       pass

    def editItem(self):
        pass

class Client:
    pass

if __name__ == "__main__":
    g = GuiPart()
    g.createWidgets()
    g.root.mainloop()

A: Let's take a look at part of your code...
    buttonAdd = Button(text = "Add").grid(row = 2,
                              column = 0,
                              sticky = W,
                              command = g.addItem)

The primary problem here is that command is a parameter to the Button() constructor, not the .grid() method.  That's where your current error is coming from.
The second problem is that the value you're assigning to buttonAdd is the result of .grid() (which is always None), NOT the button itself.  If you actually need a reference to the button for later use (often, you don't), this would have to be split up into two statements:
    buttonAdd = Button(text = "Add", command = g.addItem)
    buttonAdd.grid(row = 2,
                   column = 0,
                   sticky = W)

A: See this:
buttonAdd = Button(text = "Add").grid(row = 2,
                             column = 0,
                             sticky = W,
                             command = g.addItem)
#                                   ^^^^^^^^^

buttonRemove = Button(text="Remove").grid(row = 2,
                             column = 0,
                             sticky = W,
                             command = g.removeItem)
#                                    ^^^^^^^^^^^^

buttonEdit = Button(text="Edit").grid(row = 2,
                            column = 0,
                            sticky = E,
                            command = g.editItem)
#                                   ^^^^^^^^^^

You are not calling functions you are assigning them.
In order to call them you have to pass parameter to them.
A small example explaining what happened:
>>> id(print)
1769760
>>> some_var = print
>>> id(some_var)
1769760
>>> some_var
<built-in function print>
>>> some_var('we assigned the built-in function "print" to the variable
... some_var')
we assigned the built-in function "print" to the variable some_var


text:
Q: mysqldump entire database/s Recently I used mysqldump to backup a database without any option, and when I open it with MySQL Workbench I only have the database without relationships on EER Diagram, views, etc.
How to use mysqldump to backup entire database?
Thanks.


text:
Q: two views ontouchlistener same area how to? I have a two ImageViews.
1.ImageView zoomImageMoveable : should zoom in,out and moveable.
2.ImageView zoomImageFixed : show zoom this is guide line.
I want run different functions from one touch.
{
 FrameLayout myFrame = new FrameLayout(this.getContext());
     myFrame.addView(zoomImageMoveable);
     myFrame.addView(zoomImageFixed);
}

Case 1. I tried to attach a listener to each of the view, as they are overlapping only one works.
Case 2. I also tried to wrap the two view with a FrameLayout and added an  OnTouchListener to that layout to have it forward the calls to each of the assigned methods. Yet this method also didn't work.
 myFrame.setOnTouchListener(new OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
           zoomImageMoveable.onTouchEvent(event);
           zoomImageFixed.onTouchEvent(event);
           return false;
      }
 });

How should I approach this issue?


text:
Q: Download Inventory File from AWS S3 I have configured AWS to automatically create an inventory file, in the following location. Just to explain an inventory file is a csv.gz file with a directory listing of an entire bucket (named Bucket1). On a weekly basis a file with a gibberish name is created here:
Location: Bucket2\Inventory\Data\filename_gibberish.csv.gz

Question: I wish for my bash script to locate the latest inventory file based on the "last modified" time-stamp on AWS. Then check if my local directory has this file? If not, download it.
Pls help!

A: This command will list the most recently created object:
aws s3api list-objects --bucket my-bucket --prefix Inventory/Data/ --query 'sort_by(Contents, &LastModified)[-1].Key' --output text

It can be combined with a copy command:
aws s3 cp s3://my-bucket/$(aws s3api list-objects --bucket my-bucket --prefix Inventory/Data/ --query 'sort_by(Contents, &LastModified)[-1].Key' --output text) inventory.csv.gz

(Note that the bucket name appears twice in that command.)


text:
Q: How to un-install sql server 2008 analysis service only? Initally I installed SQL server 2008 R2 Evaluation version. Then we bought licence key for SQL server 2008 R2 Web and wanted to update my licence, but unfortunately I installed analysis service when I was installing evaluation version which is not there in Web version so now I have to un-install analysis service. I googled this thing but found no real help.

A: To remove an instance of SQL Server Analysis Services:

*

*On the Microsoft Windows desktop click Start, click Control Panel, and then double-click Add or Remove Programs.

*Under Currently installed programs, select Microsoft SQL Server, and then click Change. This will start the Microsoft SQL Server Maintenance Wizard.
Note: If you click Remove instead of Change, you will not be able to uninstall an instance of Analysis Services without also uninstalling the SQL Server Database Engine and Reporting Services installed under the same instance name.

*On the Component Selection page, under SQL Server instances, select the instance that includes the instance of Analysis Services that you want to remove.

*On the Feature Maintenance page, select Analysis Services. The Microsoft SQL Server Maintenance Wizard then launches the Microsoft SQL Server Installation Wizard.

*On the Change or Remove Instance page, click Remove Microsoft SQL Server.

*Click Next, and then follow the instructions on subsequent wizard pages.


text:
Q: remember the last state of the Bool variable I'm doing a show. And I wanted to know how I saved the last status of my Bool variable so that when I leave the program and come back in it's the same as when I leave, someone has some idea of how to do it. Thank you!

A: Well, the app can be closed or killed by the system, so it surely needs some persistent storage usage. It can be on the phone or in the cloud. For your need the most simplest would be to use Shared Preferences library and keep your Boolean locally as a setting/configuration.


text:
Q: SQL Aggregation of text on joined table Pardon the lack of correct terminology, I'm a professional software engineer usually dealing with Direct3D frameworks. I'm self taught on databases.
I have a _People table and an _Ethnicities table.  Since people may have more than one cultural group I have a link table _linkPersonEthnicity.  Sample data is shown below:

What I want is output in the following form:

To illustrate the problem I present the following (runnable) query:
select lPE.Person, Sum(E.ID) as SumOfIDs,
   Ethnicity = stuff(
      (select ', ' + Max(E.Name) as [text()]
        from _linkPersonEthnicity xPE
        where xPE.Person = lPE.Person
        for xml path('')
      ),
    1, 2, '')
from _Ethnicities E
join _linkPersonEthnicity lPE on lPE.Ethnicity = E.ID
group by lPE.Person

It returns the Person's ID, a sum of the IDs found for the person's ethnicity, and concatenates the maximum Name with commas.  The data is grouped correctly, and the SumOfIDs works, proving the correct data is used.
Naturally I would like to take away the Max aggregate function, but cannot since it is not in the group by list.
Any ideas how to make this work?
Thanks in advance,
AM

(Many thanks to other answers on StackOverflow for getting me this far!  Particiularly @Jonathan Leffler for his explanation of the partitioning proceess and @Marc_s for illustrating a text concatenation technique.)
I've also tried coalesce from an answer to concatenating strings by @Chris Shaffer
declare @Names VARCHAR(8000)
select @Names = COALESCE(@Names + ', ', '') + E.Name
  from _Ethnicities E join _linkPersonEthnicity lPE on lPE.Ethnicity = E.ID
 where lPE.Person = 1001;
select @Names

Same problem.  If I remove the where and add group by the text field Name cannot be accessed.

A: If I understand correctly, you need for the join to be in the subquery rather than the outer query
select lPE.Person, Sum(lpe.ethnicity) as SumOfIDs,
       Ethnicity = stuff((select ', ' + E.Name as [text()]
                          from _linkPersonEthnicity lPE2 join
                               _Ethnicities e
                               on lpe2.Ethnicity = e.id
                          where lpe2.Person = lPE.Person
                          for xml path('')
                         ), 1, 2, '')
from _linkPersonEthnicity lPE
group by lPE.Person;

By the way, do you really want the sum of the ids or a count?


text:
Q: How to install Ubuntu 14.10 on an Asus Z87-Deluxe motherboard I have tried turning off Secure Boot, Fastboot, & CSM. But everything I try doesn't work.
I built my computer with the Asus Z87-Deluxe motherboard. I have Windows 7 64bit installed with no problems. I was having problems getting Ubuntu 14.04 loaded. I found that problem a couple of hours ago. I discovered that Linux won't work with ASMedia SATA.
Both of my DVD drives were plugged into those ports. Moving them to the Intel Z87 SATA allows Ubuntu to install. But it does not see the Windows 7 OS. And it can't set up the boot loader.


text:
Q: Need help with ui component and change sorting order of columns in magento 2 Have listing but need to change view of one column:
    <column name="status">
        <settings>
            <filter>text</filter>
            <label translate="true">Status</label>
        </settings>
    </column>

i need to display text as value instead of integer value since in database it has 0 or 1 so in overview i have numerical values.
also another question how to change sorting order of columns since it seem i have actions column in front of some other fields although in xml it's placed as last item

A: To change int value to text you can use below code :
<column name="yourcolumn" class="Vendor\Modulename\Ui\Component\Listing\Column\Yourcolumn">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="filter" xsi:type="string">false</item>
            <item name="label" xsi:type="string" translate="true">Column Label</item>
        </item>
    </argument>
</column>

Ref : https://magento.stackexchange.com/a/171412/49826


text:
Q: Magento 2 Create A custom grid for product using Ui component I want to create a gird using the UI component in Magento. The grid must have product id and product SKU.
I tried using the below code but it's not working. Here is the below code to create the grid.

  <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
    <item name="js_config" xsi:type="array">
        <item name="provider" xsi:type="string">level_inventory.entity_listing_data_source1</item>
        <item name="deps" xsi:type="string">level_inventory.entity_listing_data_source1</item>
    </item>
    <item name="spinner" xsi:type="string">spinner_columns</item>
    <item name="buttons" xsi:type="array">
        <item name="back" xsi:type="array">
            <item name="name" xsi:type="string">back</item>
            <item name="label" xsi:type="string" translate="true">Back</item>
            <item name="class" xsi:type="string">action-default scalable back</item>
            <item name="url" xsi:type="string">*/*/index</item>
        </item>
    </item>
</argument>
<dataSource name="entity_listing_data_source1">
    <argument name="dataProvider" xsi:type="configurableObject">
        <argument name="class" xsi:type="string">Vendor\Module\Ui\Component\DataProvider\InventoryDetail</argument>
        <argument name="name" xsi:type="string">entity_listing_data_source1</argument>
        <argument name="primaryFieldName" xsi:type="string">entity_id</argument>
        <argument name="requestFieldName" xsi:type="string">id</argument>
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
                <item name="update_url" xsi:type="url" path="mui/index/render"/>
                <item name="storageConfig" xsi:type="array">
                    <item name="indexField" xsi:type="string">entity_id</item>
                </item>
            </item>
        </argument>
    </argument>
</dataSource>
<listingToolbar name="listing_top">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="sticky" xsi:type="boolean">true</item>
        </item>
    </argument>
    <paging name="listing_paging"/>
</listingToolbar>
<columns name="spinner_columns">
    <column name="entity_id">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Product Id</item>
            </item>
        </argument>
    </column>
    <column name="sku">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">SKU</item>
                <item name="sortable" xsi:type="boolean">false</item>
            </item>
        </argument>
    </column>
</columns>

  use Magento\Ui\DataProvider\AbstractDataProvider;
  use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollection;

class InventoryDetail extends AbstractDataProvider
{

protected $productCollection;

public function __construct(
    $name,
    $primaryFieldName,
    $requestFieldName,
    ProductCollection $productCollection,
    array $meta = [],
    array $data = []
) {
    parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);

    $this->initCollection();
}

public function initCollection()
{
    $collection = $this->productCollection->create();
    $this->collection = $collection;
}

}

A: I can suggest that you are not defined you collection in di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
    <arguments>
        <argument name="collections" xsi:type="array">
            <item name="learnmodules_uitest_post_grid" xsi:type="string">Learnmodules\UiGridModule\Model\ResourceModel\Post\Grid\Collection</item>
        </argument>
    </arguments>
</type>
<virtualType name="Learnmodules\UiGridModule\Model\ResourceModel\Post\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
    <arguments>
        <argument name="mainTable" xsi:type="string">learn_uitest_post</argument>
        <argument name="resourceModel" xsi:type="string">Learnmodules\UiGridModule\Model\ResourceModel\Post</argument>
    </arguments>
</virtualType>

<virtualType name="Learnmodules\UiGridModule\Model\ResourceModel\Post\Grid\Collection">
    <arguments>
        <argument name="mainTable" xsi:type="string">learn_uitest_post</argument>
        <argument name="eventPrefix" xsi:type="string">learn_uitest_post_collection</argument>
        <argument name="eventObject" xsi:type="string">learn_uitest_post_collection</argument>
        <argument name="resourceModel" xsi:type="string">Learnmodules\UiGridModule\Model\ResourceModel\Post</argument>
    </arguments>
</virtualType>

my learnmodules_uitest_post_grid will be entity_listing_data_source1 in your code

A: Found the Solution.
Extended Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider for my custom provider (InventoryDetail).

A: Please, you replace only your following code
<columns name="spinner_columns">
<column name="entity_id">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="label" xsi:type="string" translate="true">Product Id</item>
        </item>
    </argument>
</column>
<column name="sku">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="label" xsi:type="string" translate="true">SKU</item>
            <item name="sortable" xsi:type="boolean">false</item>
        </item>
    </argument>
</column>

To,
<columns name="spinner_columns">
<column name="entity_id">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="filter" xsi:type="string">text</item>
            <item name="label" xsi:type="string" translate="true">Product Id</item>
            <item name="sortOrder" xsi:type="number">10</item>
            <item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>
        </item>
    </argument>
</column>
<column name="sku">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="filter" xsi:type="string">text</item>
            <item name="label" xsi:type="string" translate="true">Sku</item>
            <item name="sortOrder" xsi:type="number">20</item>
            <item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>
        </item>
    </argument>
</column>

After that, run php bin/magento cache:flush command and check your custom grid.
I hope, it is useful for you.


text:
Q: What does 'sharp' mean as it relates to being physical? Someone told me "You are very sharp, though I will leave it up to you to decide if I mean mentally or physically".
What does sharp mean in the 'physical' context?

A: Physically, sharp usually refers to your clothing (e.g., a coordinated outfit) or personal grooming (e.g., carefully combed hair).
Ref: Slang definitions & phrases for sharp (via Dictionary.com)
sharp (adj)

*

*stylish; of the latest and most sophisticated sort: He wore bow ties and sharp suits (1940+ Jive talk)

Also found in a line from a famous ZZ Top song: "'Cause every girl crazy 'bout a sharp dressed man."


text:
Q: Installing GConf on MSYS2 I try to build some project with MSYS2/MinGW64.
configure fails with:
checking for gconftool-2... no
configure: error: gconftool-2 executable not found in your path - should be installed with GConf

I have found no prebuild distributive at the home page.
I have tried to guess a package name for pacman:
gconf
gconf2
gconf-devel
mingw-w64-x86_64-gconf

and so on.
No success.
Also I have not found GConf package in msys2 package list.
Should I build GConf from sources or is there other way to get it?

A: I could not find gconf in the MINGW-packages repository so we do not have a recipe for building it from source.  You might consider developing such a recipe.  If it works for you, you could submit a pull request and maybe the MSYS2 maintainers will accept it and build it.


text:
Q: search input on JAVASCRIPT how to make an input like on the google site? I need that after entering the texts and in the input, Google opens with the desired request.
on JAVASCRIPT
google's input
1
2
my input(html)
<input class="finder" type="search" placeholder="Search in Google">

A: if you mean redirect to a google page after input this would work
document.querySelector('.finder').addEventListener('focusout',function(){
location.replace("https://www.google.com/search?q=" +     document.querySelector('.finder').textContent);
});

this will send the user to a google page with the needed requests when they leave the input fild
if you need to make something simular but on your oun website the best option would be to send the user to a nother page with the query data in the url and some back end to construct and return a needed page.
or you could send a fetch and get info back on focus out

A: You can add an event listener to let's say a button.
When that button is clicked, the value in your search field will be added to the end of a Google search link.
However, since you can expect people to type sentences (and urls don't use spaces), you can use replace() to replace all spaces with, in our case, a + (url format for spaces is %20, but spaces in queries are commonly replaced with a + character).
Lastly, you can use window.open(), to open a new window that uses our link.
UPDATE: You can use a keypress as a trigger for the eventlistener, and then check if the entered key is an "Enter", that way you don't need a button.
Here's an example:

*

*SEARCH_GOOGLE_VALUE is the textfield the user can type

const SEARCH_GOOGLE_VALUE = document.getElementById('SEARCH_GOOGLE_VALUE');

SEARCH_GOOGLE_VALUE.addEventListener("keypress", (keyboard) => {
if (keyboard.key == "Enter") {
    let value = SEARCH_GOOGLE_VALUE.value;
    value = value.replace(' ', '+');

    let link = "https://www.google.com/search?q=" + value;
    window.open(link);
}
});


text:
Q: Calling a javascript function in iFrame opened with Fancybox popup I'm trying to call a javascript function in a page opened in an iFrame using jQuery Fancybox.
            $(".testbox").fancybox({
                maxWidth    : 800,
                maxHeight   : 600,
                fitToView   : false,
                autoSize    : false,
                closeClick  : false,
                openEffect  : 'none',
                closeEffect : 'none',
                afterShow: function() {
                        //var frameID = $('#fancybox-frame')
                        //frameID.getParam("test");
                    }
            });

        $(".testbox").each(function() {
                var element = this;
                $(this).fancybox({
                    'titleFormat'   : function() {
                        var astring = '' + element.id + '';
                        alert(astring);
                    }
                });
            });

HTML:
    Iframe

The function in the testFrame.html I'm trying to call:
        function getParam(param) {
            alert(param);
        }

Normally I'd do this when calling functions in iFrame without using a Fancybox popup:
        document.getElementById('myFrame').contentWindow.getParam();

but I don't know how to get the ID of the whole iFrame when using Fancybox. Any help is appreciated!
Edit:
I also tried this code which also didn't work, I get the error in IE: Object doesn't support this property or method. I've made sure the page I'm loading has the function
    var $f = $("#fancybox-frame");
    var fd = $f[0].document || $f[0].contentWindow.document;
    fd.getparam("test");

A: You should use:
var $f = $("#fancybox-frame");
$f[0].contentWindow.getParam("test");

Reasons:

*

*The method is globally declared, not as a method of the document object.

*JavaScript is case-sensitive; getParam is distinct from getparam.


text:
Q: При щелчке на карту, она переворачивается

    document.addEventListener('click', function () {
        document.getElementById('card').classList.toggle('flip')
    })
        .container {
            margin: 100px auto auto 100px;
            position: relative;
            width: 190px;
            height: 266px;
        }

        #card {
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            position: absolute;
            transition: transform 0.5s;

            transform-style: preserve-3d; /*  */
        }

        #card.flip {
            transform: rotateY(180deg);
        }

        figure {
            width: 100%;
            height: 100%;
            position: absolute;
            display: block;
        }

        .back {
            background: url(http://www.xiper.net/examples/html-and-css-tricks/effects/card-back.png);
        }

        .front {
            background: url(http://www.xiper.net/examples/html-and-css-tricks/effects/card-front.png);
            transform: rotateY(180deg); /*  */
        }

У меня при щелчке на карту, она переворачивается, но работает даже если кликнул не по картинке.(типо в любую точку страницы)
Как сделать, что бы именно на картинку нужно было кликнуть

A: Ну а что вы хотите, раз вы на весь документ навесили обработчик события
document.addEventListener('click', function () {

Повесьте его на объект:

document.querySelector('#card').addEventListener('click', function () {
    document.querySelector('#card').classList.toggle('flip')
})
.container {
            margin: 100px auto auto 100px;
            position: relative;
            width: 190px;
            height: 266px;
        }

        #card {
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            position: absolute;
            transition: transform 0.5s;

            transform-style: preserve-3d; /*  */

            border: 1px solid black;
        }

        #card.flip {
            transform: rotateY(180deg);
        }


text:
Q: How to append/concat a string after a comma on a comma-separated value? I have column which stores values separated by a comma. It's something like this:
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| breakfast_id | breakfast_english_menu                                                                                |
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|            1 | Canned Orange Juice- Can of 5 to 7 oz, Oatmeal- ½ T, Almonds - (12 almonds), Milk with Coffee or Milk with Chocolate (1T.) (Only one)                                                                                |
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

and so I would like to add a string after each comma at the beginning of a 'new value'.  It would be something like
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| breakfast_id | breakfast_english_menu                                                                                |
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|            1 | Canned Orange Juice- Can of 5 to 7 oz, [HI]Oatmeal- ½ T, [HI]Almonds - (12 almonds), [HI]Milk with Coffee or Milk with Chocolate (1T.) (Only one)                                                                                |
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Any help or tip is welcomed.

A: As you have only a simple pattern use REPLACE

SELECT REPLACE('ned Orange Juice- Can of 5 to 7 oz, Oatmeal- ½ T, Almonds - (12 almonds), Milk with Coffee or Milk with Chocolate (1T.) (Only one)',', ',', [HI]')

| REPLACE('ned Orange Juice- Can of 5 to 7 oz, Oatmeal- ½ T, Almonds - (12 almonds), Milk with Coffee or Milk with Chocolate (1T.) (Only one)',', ',', [HI]') |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ned Orange Juice- Can of 5 to 7 oz, [HI]Oatmeal- ½ T, [HI]Almonds - (12 almonds), [HI]Milk with Coffee or Milk with Chocolate (1T.) (Only one)              |

db<>fiddle here
For more complicated patterns, you would use regular expressions to find and replace.
If need be, you can nest REPLACE comands one in another to repace more than one strintg


text:
Q: How to test an express rest api with header parameters using mocha and supertest? I have to test my rest api. Some routes require a value in the http requests headers for the user authentication token.
I have separated my interesting bussiness logic in pure javascript code but I can't find a way to test the routes that require a token in the headers of the http request.
Any other alternatives to mocha and/or supertest are welcome.

A: With supertest, you can set a header parameter with the set keyword :
api.get('/aroute/')
...
.set('headerParameterName', value)
...

Here is an example of testing a express server API with token authorization using supertest :
app.js:
var express = require('express');
var app = express();
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');

var secret = 'my-secret';

app.get('/get-token', function(req, res) {
  var token = jwt.sign({foo: 'bar'}, secret);
  res.send({token: token});
});

app.post(
  '/test',
  expressJwt({
    secret: secret
  }),
  function(req, res) {
    res.send({message: 'You could use the route!'});
  }
);

app.use(function(err, req, res, next) {
  res.status(err.status || 500).send({error: err.message});
});

app.listen(4040, function() {
  console.log('server up and running at 4040 port');
});

module.exports = app;

test.js:
var request = require('supertest');
var app = require('./app.js');

describe('Test Route with Token', function() {
  var token = '';

  before(function(done) {
    request(app)
      .get('/get-token')
      .end(function(err, res) {
        var result = JSON.parse(res.text);
        token = result.token;
        done();
      });
  });

  it('should not be able to consume the route /test since no token was sent', function(done) {
    request(app)
      .post('/test')
      .expect(401, done);
  });

  it('should be able to consume the route /test since token valid was sent', function(done) {
    request(app)
      .post('/test')
      .set('Authorization', 'Bearer ' + token)
      .expect(200, done);
  });
});


text:
Q: How do you calculate the magnitude of a directly represented flat in conformal geometric algebra? A flat connected to the origin point $o$ is represented by $X=o \wedge \textbf{A}_k \wedge \infty$, where $\textbf{A}_k$ is a k-blade of directions in the Euclidean subspace, and $\infty$ is the point at infinity. I want to calculate
$$||X||^2 = X \widetilde{X} = (o\wedge \textbf{A}_k \wedge \infty)(\infty \wedge \widetilde{\textbf{A}_k} \wedge o)$$
I am not sure how to simplify the expression. The answer is supposed to be $X\widetilde X = -||\textbf{A}_k||^2$.
It is scalar, so $X\widetilde X=\langle (p\wedge \textbf{A}_k \wedge \infty)(\infty \wedge \widetilde{\textbf{A}_k} \wedge p) \rangle$.
In this CGA, we have $\infty \cdot \infty=0$, $o\cdot o=0$, $o\cdot \infty = -1$.
If there was a left contraction between $X$ and $\widetilde X$, then the solution would follow, but how would that be justified?

A: Despite my comments, I can answer this directly.
Note that $A$ in the Euclidean subspace is orthogonal to both $o$ and $\infty$. (Some would be more comfortable writing these vectors as $e_o$ and $e_\infty$.) Therefore $A\wedge o\wedge\infty=A\,(o\wedge\infty)$.
$$X\,X^\sim=(A\wedge o\wedge\infty)(\infty\wedge o\wedge A^\sim)$$
$$=A\,(o\wedge\infty)(\infty\wedge o)\,A^\sim$$
$$=A\,(-1)\,A^\sim$$
$$=-\lVert A\rVert^2$$


text:
Q: Change variable based on which element is clicked It is possible to change variable inside function which is based on element is user clicks?
In my case this will fully work for one kind of menu but I need two fully identical menu
with one difference -
second click handler must load toggleDrawer with changed $sidebar to $navbar variable.
    /*
    Variables
    */

    var $sidebar = $('#sidebar'),
        $navbar = $('#navbar'),
        drawerOpen = false,

    /*
    Functions
    */

    closeDrawer = function() {
        drawerOpen = false;
        $body.css('overflow','').removeClass('sidebar-open');
        $sidebar.removeClass('open');
        $sidebar.animate({'right':'-50%'},{duration:300});
        $(this).hide();

    },

    openDrawer = function() {
        drawerOpen = true;
        $body.addClass('sidebar-open').css('overflow','hidden');
        $sidebar.addClass('open');
        $sidebar.animate({'right':'0%'},{duration:300});
    },

    toggleDrawer = function() {
        if (drawerOpen) {
            closeDrawer();
        }else{
            openDrawer();
        }
    },

    /*
    Bind Events
    */

    $document.on('click', '.drawer-toggle-sidebar', function(event){
        toggleDrawer();
        event.preventDefault();
    });

    $document.on('click', '.drawer-toggle-navbar', function(event){
        toggleDrawer();
        event.preventDefault();
    });

A: To elaborate on the above comment, and show an example:
Here are your functions with passing in the element you wish to open/close:

/*
    Functions
    */

    closeDrawer = function(drawer) {
        drawerOpen = false;
        $body.css('overflow','').removeClass('sidebar-open');
        drawer.removeClass('open');
        drawer.animate({'right':'-50%'},{duration:300});
        $(this).hide();

    },

    openDrawer = function(drawer) {
        drawerOpen = true;
        $body.addClass('sidebar-open').css('overflow','hidden');
        drawer.addClass('open');
        drawer.animate({'right':'0%'},{duration:300});
    },

    toggleDrawer = function(drawer) {
        if (drawerOpen) {
            closeDrawer(drawer);
        }else{
            openDrawer(drawer);
        }
    },

And your bind events:

/*
    Bind Events
    */

    $document.on('click', '.drawer-toggle-sidebar', function(event){
        toggleDrawer(event.currentTarget);
        event.preventDefault();
    });

    $document.on('click', '.drawer-toggle-navbar', function(event){
        toggleDrawer(event.currentTarget);
        event.preventDefault();
    });

You could even combine the two on click events into one and just pass in the currentTarget.
I hope this helps.


text:
Q: Checking if input has letters in it My error appears on this line:
if exclude3 not in Sent:

And it is:
TypeError: 'in <string>' requires string as left operand, not set

My code is:
import string

Word = input("Please give a word from the sentence")

exclude3 = set(string.ascii_letters)

if exclude3 not in Sent:
    print("")
elif exclude3 not in Word:
    print("")
else:

What is a left operand? What am I doing wrong and is there a simpler way to accomplish what I want? Should I be using something other than in and what should that be?

A: exclude3 is not a string it is a set.
You try to use the in operator to check if a set is contained in another set which is wrong.
Maybe you meant to write: if Sent not in exclude3 ?

A: You need to check if the set and the string overlap. Either
if not exclude3.intersection(Sent):

or
if not any(x in Sent for x in exclude3):

will have the desired result.
The in operator works by testing if the left-hand argument is an element of the right-hand argument. The exception is str1 in str2, which tests if the left-hand str is a substring of the other.

A: When you use in operand the left side and right side objects must be same type. And in this case exclude3 is a set object and you can not check its membership in a string.
Example:
>>> [] in ''
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list

If you want to check the existence of all the items of a set in a string you can use set.intersection() as following :
if exclude3.interection(Sent) == exclude3:
      # do stuff

And for any intersection just check the validation of exclude3.interection(Sent):
if exclude3.interection(Sent):
     # do stuff


text:
Q: On button click, find element with specific class, and access scope data within element Is it possible to access child elements within a button that has a specific class? There will be multiple buttons created. When a submit button is clicked, I want to iterate through the list of 'btnSelection' buttons created and if a 'btnSelection' button has the 'active' class, I want to push the span data into an array.
I imagine I'd need the parameters put into an object that itself will be a parameter going into the submit method on ng-click, but I'm not sure exactly how to write the Angular portion. Searching Google doesn't yield any specific examples. I'd appreciate any help.
Example HTML:

    <button id="btnSelection" class="active">
        {{item.value}}
    </button>

<button ng-click="submit()">Submit</button>

A: You shouldn't use an active class in you're controller, it's not the angular way. Instead use an active attribute in your items objects and set your active class afterward.
Here is a jsFiddle:
http://jsfiddle.net/L5z3j0gj/2/
HTML:

        <button type='button'
                ng-click='addContent($index)'
                ng-class="{active: item.active}"
                ng-disabled='!item.active'>
            {{item.value}}
        </button>

    <button type='button' ng-click='addContents(items)'>Submit</button>
    {{contentsArray}}

Controller:
angular.module('myApp', [])
.controller('myController', function($scope) {
    $scope.items = [
        { value: 'value1', active: true },
        { value: 'value2', active: false },
        { value: 'value3', active: true }
    ];
    $scope.contentArray = [];

    $scope.addContent = function(index) {
        console.log($scope.items[index]);
        $scope.contentArray.push($scope.items[index].value);
    };

    $scope.addContents = function(items) {
        $scope.contentsArray = [];
        for (var idx in items) {
            var item = items[idx];
            if (item.active) {
                $scope.contentsArray.push(item.value);
            }
        }
    };
});

CSS:
.active {
    background: green;
}

A: Demo: http://jsfiddle.net/bjbrc5wy/3/

        <button ng-click="toggleActive(item)" class="active-{{item.active}}">
          {{item.val}}
        </button>

    <button ng-click="submit()">Submit</button>

You need to use a controller which acts as a parent object, a container for children. Then when you press your submit button from within this controller, you can access other items from the same controller $scope. You can see I also tie my data to the CSS with class="active-{{btn.active}}", so it automatically updates according to its active status. The controller is defined like so:
function ItemCtrl($scope) {
  $scope.items = [ // sample data
    {val:1, active:true},
    {val:2, active:false}];

  $scope.submit = function() {
    var arr = [];
    angular.forEach($scope.items, function(item) {
      if(item.active) arr.push(item.val);
    });
    alert(arr); // here's the array of item values
  };
}


text:
Q: Apache cayenne - cdbimport task restores PK Generation strategy do default I have a problem with PK generation strategy in cayenne.
I'm using PostgreSQL 9.6 with Apache Cayenne 4.0.B1.
This is my table in postgres:
create table ui_template (
  id varchar(50) primary key default uuid_generate_v1(),
  path varchar(300) not null,
  type varchar(50) not null
);

Then I'm doing Tools -> Reengineer Database Schema in Cayenne Modeler.
I got table and enity.
And now i have to set PK Generation Strategy to Database-Generated, to let DB generate my PK's. Everything works fine when I'm inserting objects through ObjectContext. But, if I'm running gradle task cdbimport it overwrites my datamap.map.xml file with another one without Generation Strategy.
Please give me advice what I'm doing wrong.
This is my gradle task
buildscript {
    // add Maven Central repository
    repositories {
        mavenCentral()
    }
    // add Cayenne Gradle Plugin
    dependencies {
        classpath group: 'org.apache.cayenne.plugins', name: 'cayenne-gradle-plugin', version: '4.0.B1'
        classpath group: 'org.postgresql', name: 'postgresql', version: '42.1.3'

    }
}
// apply plugin
apply plugin: 'org.apache.cayenne'

// set default DataMap
cayenne.defaultDataMap 'resources/datamap.map.xml'

// add Cayenne dependencies to your project
dependencies {
    // this is a shortcut for 'org.apache.cayenne:cayenne-server:VERSION_OF_PLUGIN'
    compile cayenne.dependency('server')
    compile cayenne.dependency('java8')
}

cdbimport {
    dataSource {
        driver 'org.postgresql.Driver'
        url 'jdbc:postgresql://localhost:5432/my_db'
        username 'user'
        password 'pass'
    }
}

A: You are doing nothing wrong, it seems that you found a weak spot in cdbimport.
In your case Cayenne doesn't understand default values, for Postgres DB Cayenne marks only serial columns as db-generated.
You can either change your PK to serial (unless you have some special requirements it is always a good idea) or you can try to exclude those PKs from cdbimport task like this:
cdbimport {
    //...
    includeTable 'ui_template', {
        excludeColumns 'id'
    }
}

Be aware that excluding PKs can lead to problems with importing relationships. And moreover if you use includeTable you should explicitly list all required tables.


text:
Q: The Homeomorphy of The Tetrahedron, The Cube, and The Octahedron My question involves all possible dimensions, but this is the lowest dimension where these are qualitatively distinct shapes, so I phrase it in three dimensions for convenience. The analogs for higher dimensions will be apparent once I describe these sets.
The cube $\mathbf{I}^3$ is the product space $[0,1]\times[0,1]\times[0,1]$. The tetrahedron is the space $$\mathbf{T}^3=\lbrace (x,y,z)\in\mathbf{I}^3: x+y+z\leq 1\rbrace.$$ And the octahedron is the space $$\mathbf{K}^3=\lbrace (x,y,z)\in\mathbf{R}^3:\lvert x\rvert+\lvert y\rvert+\lvert z\rvert\leq 1\rbrace,$$ where $\mathbf{R}$ is the real line and $\mathbf{R}^3$ is $\mathbf{R}\times\mathbf{R}\times\mathbf{R}$.
The spaces $\mathbf{T}^3$, $\mathbf{I}^3$ and $\mathbf{K}^3$ are purported to be homeomorphic. I have been thinking about it, but I can't come up with a satisfactory homeomorphism between the three.
I can give an example for the type of homeomorphism I desire in the best case scenario: In the general case, for natural $n\geq 0$, if the unit disk is defined in the usual manner as $$\mathbf{D}^n=\lbrace (x_1,\cdots,x_n)\in\mathbf{R}^n:x_1^2+\cdots+x_n^2\leq 1\rbrace,$$ then the only one of these that is obviously homeomorphic to the unit disk $\mathbf{D}^n$ for me is the octahedron$^*$ $\mathbf{K}^n$ by the map $f:\mathbf{K}^n\to\mathbf{D}^n$ defined on any $p=(p_1,\cdots,p_n)$ in $\mathbf{K}^n$ as $$f(p)=\left(\sqrt[3]{p_1\sqrt{\lvert p_1\rvert}},\cdots, \sqrt[3]{p_n\sqrt{\lvert p_n\rvert}}\right),$$ with the inverse map $f^{-1}:\mathbf{D}^n\to\mathbf{K}^n$ defined on any $x=(x_1,\cdots,x_n)$ in $\mathbf{D}^n$ as $$f^{-1}(x)=(x_1\lvert x_1\rvert,\cdots,x_n\lvert x_n\rvert).$$ This kind of map is ideal, because it is built up only of the composition of elementary operations, and there is no case checking. In particular, for my predicament, if case checking is required, it would be best as a rule of thumb that all cases should constitute open sets—or, put another way, that the composite map is an appropriate gluing of compatible maps defined on open subsets that cover the whole space—but it's even better if this can just be avoided in the first place.
Apparently, there are similar maps from both $\mathbf{T}^n$ and $\mathbf{I}^n$ to $\mathbf{D}^n$. What are examples of such maps? Or, if it is easier to describe, what are instances of homeomorphisms between $\mathbf{K}^n$, $\mathbf{I}^n$ and $\mathbf{T}^n$?
$^*$In $n$ dimensions, $\mathbf{K}^n$ will actually have $2^n$ copies of $\mathbf{T}^n$, and within all of these copies there will be only one copy of $\mathbf{T}^{n-1}$ that constitutes a "face" or $n$ dimensional "room" of $\mathbf{K}^n$ as a geometric shape. So, for instance, $\mathbf{K}^4$ is most aptly called a hexadecachoron, $\mathbf{I}^4$ is an octachoron and $\mathbf{T}^4$ is a pentachoron. I suppose for $n\geq 5$, the general name for these in $n$ dimensions would be the $2^n$-tope, the $2n$-tope, and the $n+1$-tope, respectively.

Optional. The way this question comes to be setup makes me think about the remaining two Platonic solids in the following way: In what way can the dodecahedron and the icosahedron be implicitly described as subspaces of 3-Euclidean space, as were described the tetrahedron, the cube and the octahedron? With that, what are the homeomorphisms between the two and the remaining Platonic solids as described? There are also a few more regular polychorons in four dimensions for which one may ask the exactly analogous question, but the three I have found seem to be the only regular polytopes for dimensions no less than 5, so those cases are sorted.
Edit. The answer given for this question is satisfactory for the two and three dimensional cases.


text:
Q: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'payments' already exists (SQL: create table `payments` When I migrate a table I see this error,

SQLSTATE[42S01]: Base table or view already exists: 1050 Table
  'payments' already exists (SQL: create table payments

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePaymentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('resnumber');
            $table->string('course_id')->default('vip');
            $table->string('price');
            $table->boolean('payment')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('payments');
    }
}

Error

A: If you are on Laravel 5.5 you can do php artisan migrate:fresh. This command will drop all tables und then create them again. I hope it helps.

A: If you have table in DB and dont want migrate create it, you can ignore it by check Schema::hasTable before create
    public function up()
{
    if(Schema::hasTable('products')) return;       //add this line to migration file
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();

    });
}

A: If you want to recreate the table, run php migrate:rollback first to delete the existing one. This command will run the down() method in the migration.
Then run php migrate to create the table again.

A: In my case after php migrate:rollback resulted in Nothing to rollback and didn't solve. Because the migrations table in the database is empty.
So the solution is open up the tinker from the composer
$ php artisan tinker
>>> Schema::drop('users')
>>> Schema::drop('password_resets')
>>> Schema::drop('orders')
>>> exit
php artisan migrate

Here is the result of the above commands executed
nishanth@localhost:~/Desktop/html/hutch$ php artisan migrate

In Connection.php line 647:
                                                                                SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users'
  already exists (SQL: create table users (id int unsigned not
  null auto_incr     ement primary key, name varchar(255) not null,
  email varchar(255) not n     ull, password varchar(255) not null,
  remember_token varchar(100) null,      created_at timestamp null,
  updated_at timestamp null) default character      set utf8mb4
  collate utf8mb4_unicode_ci)
In Connection.php line 449:
                                                                                SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users'
  alre     ady exists

nishanth@localhost:~/Desktop/html/hutch$ php artisan migrate:rollback
Nothing to rollback.
nishanth@localhost:~/Desktop/html/hutch$ php artisan tinker
Psy Shell v0.8.17 (PHP 7.1.20-1+ubuntu16.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> Schema::drop('users')
=> null
>>> Schema::drop('password_resets')
=> null
>>> Schema::drop('orders')
=> null
>>> exit
Exit:  Goodbye.
nishanth@localhost:~/Desktop/html/hutch$ php artisan migrate
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table
Migrating: 2018_08_18_071213_create_orders_table
Migrated:  2018_08_18_071213_create_orders_table
nishanth@localhost:~/Desktop/html/hutch$

Also define the method down(), if it doesn't exist.
Otherwise, it'll show

SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'XYZ.ABC' (SQL: drop table ABC)

/**
  * Reverse the migrations.
  *
  * @return void
  */
public function down()
{
    Schema::dropIfExists('ABC');
}

A: first make php artisan migrate:rollback; then go to php my admin panel and drop the remaining table. then do php artisan migrate:fresh it will work :-)

A: This is my scenario:

Illuminate\Database\QueryException  : SQLSTATE[42S01]: Base table or
  view already exists: 1050 Table 'migrations' already exists (SQL:
  create table migrations (id bigint unsigned not null
  auto_increment primary key, created_at timestamp null, updated_at
  timestamp null) default character set utf8mb4 collate
  'utf8mb4_unicode_ci')

solution :

*

*delete the file located in YOUR-PROJECT/database/migrations/2020_02_04_031638_create_migrations_table.php

*run php artisan migrate, then your new table will create in your database

A: Please use this command if you are using laravel 9 version

php artisan migrate:fresh

This command will help to you. that's work for me.

A: According to the error, the database table already exists. Below are possible solutions that can be helpful.
Solution 1:
Drop the entire database tables manually including the migrations table then re-run the php artisan migrate command.
Solution 2:
If you have some records in some of the existing tables and you don't want to drop/delete them. Then, click on the migrations table from your phpMyAdmin or related to see the list of the migrated tables. Delete/Edit the particular table that's causing the error and run the php artisan migrate command again.
Solution 3:
For some reason, you may want to run a particular migration file, the command below is what you need.
php artisan migrate:refresh --path=/database/migrations/file-name.php
Remember to replace the file-name.php with your actual file name.
I hope this will be helpful to someone.
:)


text:
Q: Color Theme selector for web base app with Jquery I'm working on a web app and I want to have the user be able to change the theme of the content. I basically need to change the color of css backgrounds, texts and borders. The app has many different classes and Id's, but mainly 4 repeating colors that would need to be replaced.
My questions is:
What would be the most efficient way to change the colors with Jquery?
Thank you.

A: Set a class on the root element or body like:
<body class="raw_umber">

The write your CSS rules base on these classes, for example:
.raw_umber h1 {
    color:#7B4A12;
}
.blue h1 {
    color:#00c;
}
...

Then use jQuery to change that class.
EDIT
.raw_umber .some_class {
    border-color: #7B4A12;
}
.raw_umber .some_other_class {
    color:#7B4A12;
}

Those are examples of other rules.  But there's no way I could account for every possible rule you need.