问:
what are the possible ways to force mathematica to show -1+a as a-1
I am just getting started with pattern in mathematica. I want to know what the different ways to force mma to show -1+a as a-1. Many thanks!

答:
You could probably use a hack like this

```<code>$PrePrint = (# /. -1 + expr__ :> Interpretation[Row[{expr, -1}], expr - 1]) &
</code>```

But (as WReach suggests) it might be best to use the default Mathematica ordering of expressions and use TraditionalForm when you want it to look more like what a human would write.

Body:
You could probably use a hack like this

$PrePrint = (# /. -1 + expr__ :> Interpretation[Row[{expr, -1}], expr - 1]) &

But (as WReach suggests) it might be best to use the default Mathematica ordering of expressions and use TraditionalForm when you want it to look more like what a human would write.


来源: stackexchange

问:
Onclick function button inside a javascript
I want to direct the button to another page

```<code>function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit"
    onclick="location.href = "addnewcustomer.php";" id ="newcust"
    class="btnRegister" value = "New Customer">';
}
</code>```

I want when i click the New Customer button, it will redirect to addnewcustomer.php but when i run the code, nothing happened.

There are no errors. Just the button didn't function the way i want it to

答:
You can use following code to redirect page.

function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit" id ="newcust" class="btnRegister" value = "New Customer" />';
}

document.getElementById("newcust").onclick = function () {
    location.href = "addnewcustomer.php";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="demo"></div>
Click To Get Button</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to direct the button to another page

function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit"
    onclick="location.href = "addnewcustomer.php";" id ="newcust"
    class="btnRegister" value = "New Customer">';
}

I want when i click the New Customer button, it will redirect to addnewcustomer.php but when i run the code, nothing happened.

There are no errors. Just the button didn't function the way i want it to

Body:
You can use following code to redirect page.

function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit" id ="newcust" class="btnRegister" value = "New Customer" />';
}

document.getElementById("newcust").onclick = function () {
    location.href = "addnewcustomer.php";
}

<div id="demo"></div>
<a onclick="showInput()" >Click To Get Button</a>


问:
Calculate total value in table row, JavaScript jQuery

I just learned web design about a month ago, well I am slow learner and lazy, anyway here is my case. I had one row with 5 columns, but i just want to calculate 3 from those columns, here is my jQuery code

```<code>function sumrow(){
$(".isitable").on('keyup','.nsakit, .npuasa, .mnormal', function(){
    var $row=$(this).closest("table tr");
    var jumlahns=parseInt($row.find('.nsakit').val());
    var jumlahnp=parseInt($row.find('.npuasa').val());
    var jumlahmn=parseInt($row.find('.mnormal').val());
    $row.find('.totalqty').val(jumlahns + jumlahnp + jumlahmn);
});}
</code>```

It does work when I am using
, but when I try to do it by using
,
is not working at all,
 here is part of the table

```<code><tbody>
    <tr id="nmr0" name="roworder">
    <td>
      1
    </td>
    <td>
      <select name="shiftid" class="form-control">
            <option selected disabled value="">-Select An Option-</option>
            <option value="Normal Shift">Normal Shift</option>
            <option value="Long Shift">Long Shift</option>
        </select>
    </td>
    <td>
      <select name="breakid" class="form-control">
            <option selected disabled value="">-Select An Option-</option>
            <option value="break1">11.45-12.15</option>
            <option value="break2">20.30-21.00</option>
            <option value="break3">18.00-18.45</option>
            <option value="break4">00.00-00.30</option>
            <option value="break5">07.00-07.30</option>
        </select>
    </td>
    <div class="rownumber">
    <td>
      <input id="A0" type="text" min="0" class="nsakit" value="">
    </td>
    <td>
      <input id="B0" type="text" min="0" class="npuasa" value="">
    </td>
    <td>
      <input id="C0" type="text" min="0" class="mnormal" value="">
    </td>
    <td>
      <input id="D0" type="text" min="0" class="totalqty" value="">
    </td>
    </div>
    <td><input type="checkbox" name="recordi"></td>
  </tr>

</tbody>
</code>```

what should i change in my javascript code, to be able calculate total

答:
closest traverses through the ancestors from the given element in the DOM.

So, when it traverses to the parent element, it checks if the selector given as the parameter to closest method is matching the element. To match if the row is matching table tr, it needs to traverse further up which is where your selector was failing.

You just need to give tr instead of table tr

```<code>var $row = $(this).closest("table tr");
</code>```

Body:
I just learned web design about a month ago, well I am slow learner and lazy, anyway here is my case. I had one row with 5 columns, but i just want to calculate 3 from those columns, here is my jQuery code

function sumrow(){
$(".isitable").on('keyup','.nsakit, .npuasa, .mnormal', function(){
    var $row=$(this).closest("table tr");
    var jumlahns=parseInt($row.find('.nsakit').val());
    var jumlahnp=parseInt($row.find('.npuasa').val());
    var jumlahmn=parseInt($row.find('.mnormal').val());
    $row.find('.totalqty').val(jumlahns + jumlahnp + jumlahmn);
});}

It does work when I am using
, but when I try to do it by using
,
is not working at all,
 here is part of the table

      1

      <select name="shiftid" class="form-control">
            <option selected disabled value="">-Select An Option-</option>
            <option value="Normal Shift">Normal Shift</option>
            <option value="Long Shift">Long Shift</option>
        </select>

      <select name="breakid" class="form-control">
            <option selected disabled value="">-Select An Option-</option>
            <option value="break1">11.45-12.15</option>
            <option value="break2">20.30-21.00</option>
            <option value="break3">18.00-18.45</option>
            <option value="break4">00.00-00.30</option>
            <option value="break5">07.00-07.30</option>
        </select>

      <input id="A0" type="text" min="0" class="nsakit" value="">

      <input id="B0" type="text" min="0" class="npuasa" value="">

      <input id="C0" type="text" min="0" class="mnormal" value="">

      <input id="D0" type="text" min="0" class="totalqty" value="">

    <input type="checkbox" name="recordi">

what should i change in my javascript code, to be able calculate total

Body:
closest traverses through the ancestors from the given element in the DOM.

So, when it traverses to the parent element, it checks if the selector given as the parameter to closest method is matching the element. To match if the row is matching table tr, it needs to traverse further up which is where your selector was failing.

You just need to give tr instead of table tr

var $row = $(this).closest("table tr");


问:
Why is stack rewriting my .cabal file and throwing away my edits to add a new dependency?
Stack is suddenly misbehaving. I created a new project, wrote some code, needed a new dependency (containers, to get Data.Map.Strict), so I edited my project .cabal file to add the dependency and now stack is rewriting my .cabal file to throw away my edits (which makes the build fail).

What stupid simple thing have I missed?

(I committed what I had to git and started over.)

```<code>rm -fr Problem032
stack new Problem032
cd Problem032
stack setup
stack build
stack exec Problem032-exe
</code>```

all works fine.  But then...

```<code>vi Problem032.cabal
</code>```

to add ",containers" to the lib build-depends

```<code>cd src
git checkout -- Lib.hs
</code>```

to get my old broken code back

```<code>cd ..
stack build
</code>```

Results in my .cabal file getting rewritten (to lose the new dependency) and then the build fails.

答: This is because the default stack template now uses hpack for package descriptions. You can either delete package.yaml or instead edit it.  Stack 1.6.1 which was just released, has much better behavior for this circumstance.</p>

Body:
Stack is suddenly misbehaving. I created a new project, wrote some code, needed a new dependency (containers, to get Data.Map.Strict), so I edited my project .cabal file to add the dependency and now stack is rewriting my .cabal file to throw away my edits (which makes the build fail).

What stupid simple thing have I missed?

(I committed what I had to git and started over.)

rm -fr Problem032
stack new Problem032
cd Problem032
stack setup
stack build
stack exec Problem032-exe

all works fine.  But then...

vi Problem032.cabal

to add ",containers" to the lib build-depends

cd src
git checkout -- Lib.hs

to get my old broken code back

cd ..
stack build

Results in my .cabal file getting rewritten (to lose the new dependency) and then the build fails.


问:
Query for Merge values from 3 column and merge as Primary Key in Oracle
In one table few columns are there and in 3 columns i want to merge values from these 3 columns and generate as Primary key after merging these 3 values.
Col1 having Datatype length 4, While col2 & col3 having datatype length 5 & 3 respectively. In col2 & col3 if any values are less than the maximum length then use LPAD with 0 and then after Merge into the Primary Key.

Ex- If col1 = 1234, col2 = 142, col3 = 32 then after merging It should be like "123400142032" as Primary Key.

答:
```<code>with lp as
(select max(length(employee_id)) mp from employee),

llp as
(select max(length(first_name)) mf from employee)

select lp.*,lpad(employee_id,lp.mp,'0'),llp.*, lpad(first_name,llp.mf,'0'),
employee_id||lpad(employee_id,lp.mp,'0')||lpad(first_name,llp.mf,'0')from lp,llp,employee;
</code>```

note: here employee_id and first_name are the columns, you can assume it as column1 and column2..

Body:
with lp as
(select max(length(employee_id)) mp from employee),

llp as
(select max(length(first_name)) mf from employee)

select lp.*,lpad(employee_id,lp.mp,'0'),llp.*, lpad(first_name,llp.mf,'0'),
employee_id||lpad(employee_id,lp.mp,'0')||lpad(first_name,llp.mf,'0')from lp,llp,employee;

note: here employee_id and first_name are the columns, you can assume it as column1 and column2..


问:
How to decrease vertical space between two cell in collectionview?

How to decrease the vertical space between two cell in collectionview?

答:
In the attribute inspector, when clicking on your collection view, you have a tab "Show Size Inspector".
You can modify min spacing and section insets to get the result that you want.
screenshot </p>


问:
Angular 4 | How to use event emitter in for loop
How can i detect the changes of my for loop using event emitter?

```<code>getdata(){
for(let mydata of this.data) {
            if (mydata.Zone == 1) {
                this.zoneOne.push(mydata);
            }
            if (mydata.Zone == 2) {
                this.zoneTwo.push(mydata);
            }
            if (mydata.Zone == 3) {
                this.zoneThree.push(mydata);
            }
            if (mydata.Zone == 4) {
                this.zoneFour.push(mydata);
            }
            if (mydata.Zone == 5) {
                this.zoneFive.push(mydata);
            }
            if (mydata.Zone == 6) {
                this.zoneSix.push(mydata);
            }
            if (mydata.Zone == 7) {
                this.zoneSeven.push(mydata);
            }
            if (mydata.Zone == 8) {
                this.zoneEight.push(mydata);
            }
        }
    }

this.timer= setInterval(() => {
        this.getdata();
    }, (this.counter*1000));
</code>```

I want to display only once when the interval is done. but it seems it always pushing my data and i get multiple value on my screen. how can i handle this to change only the array if theres new data on it?

答:
If you use setInterval, it will keep firing the function after said intervals. You need to use setTimeout instead. Something like this:

```<code>setTimeout(() => {
    this.getdata();
}, (this.counter*1000));
</code>```

setTimeout will fire the function only once and not repeatedly.

Body:
How can i detect the changes of my for loop using event emitter?

getdata(){
for(let mydata of this.data) {
            if (mydata.Zone == 1) {
                this.zoneOne.push(mydata);
            }
            if (mydata.Zone == 2) {
                this.zoneTwo.push(mydata);
            }
            if (mydata.Zone == 3) {
                this.zoneThree.push(mydata);
            }
            if (mydata.Zone == 4) {
                this.zoneFour.push(mydata);
            }
            if (mydata.Zone == 5) {
                this.zoneFive.push(mydata);
            }
            if (mydata.Zone == 6) {
                this.zoneSix.push(mydata);
            }
            if (mydata.Zone == 7) {
                this.zoneSeven.push(mydata);
            }
            if (mydata.Zone == 8) {
                this.zoneEight.push(mydata);
            }
        }
    }

this.timer= setInterval(() => {
        this.getdata();
    }, (this.counter*1000));

I want to display only once when the interval is done. but it seems it always pushing my data and i get multiple value on my screen. how can i handle this to change only the array if theres new data on it?

Body:
If you use setInterval, it will keep firing the function after said intervals. You need to use setTimeout instead. Something like this:

setTimeout(() => {
    this.getdata();
}, (this.counter*1000));

setTimeout will fire the function only once and not repeatedly.


问:
parsing html, source code, javascript problem
http://booking.travel24.com/index.php?KID=610000&&id=lmpergebnis&showresult=1&detail=zielgebiet&region=-1&ziel=-1&termin=20.02.2011&ruecktermin=17.03.2011&dauer=-1&abflughafen=46&personen=25;25&kategorie=-1&verpflegung=-1&zimmer=-1

I am trying to parse some HTML parts of this page, but when I check the source code I can not find this: "Tunesien, Marokko".

If I check with xdeveloper I can see this as html:

```<code><a class="reglreg" href="javascript:s_hliste(20009);">Tunesien, Marokko</a>
</code>```

but if i check source code of the page I can't find this. Why?

答:
maybe the data is coming via AJAX call, so it's not there on the html at the start, but dynamically added to it.

if you need to parse this, you can try to "emulate" the ajax call yourself.

ContentLicense: CC BY-SA 2.5

Body:
http://booking.travel24.com/index.php?KID=610000&&id=lmpergebnis&showresult=1&detail=zielgebiet&region=-1&ziel=-1&termin=20.02.2011&ruecktermin=17.03.2011&dauer=-1&abflughafen=46&personen=25;25&kategorie=-1&verpflegung=-1&zimmer=-1

I am trying to parse some HTML parts of this page, but when I check the source code I can not find this: "Tunesien, Marokko".

If I check with xdeveloper I can see this as html:

Tunesien, Marokko

but if i check source code of the page I can't find this. Why?


问:
how to display the count of the images using java script or jquery in the count box, count display need to be in progressiveness counting
```<code><head>
  <style>
    #box {
      width: 300px;
      height: 60px;
      background: green;
      color: black;
      font-size: 20px;
    }
    .images {
      margin-top: 20px;
    }
  </style>
</head>
<body>
  <div id="box">
    <p style="padding: 20px;">Images Count:</p>
  </div>
  <div class="images">
    <img src="img001.jpg">
    <img src="img002.jpg">
    <img src="img003.jpg">
    <img src="img004.jpg">
    <img src="img005.jpg">
    <img src="img006.jpg">
  </div>
</code>```

Please help me with the code to display the count, count display needs to be in progressiveness counting.

答:
You can try below code

$(document).ready(function(){
    console.log("Images count="+ $(".images").find("img").length)

$("#imgcount").text( $(".images").find("img").length)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>

<p style="padding: 20px;">Images Count:</p>
</div>
<div class="images">
<img src="img001.jpg">
<img src="img002.jpg">
<img src="img003.jpg">
<img src="img004.jpg">
<img src="img005.jpg">
<img src="img006.jpg">

</div>

Total No. of Images in page are <label id="imgcount"></code>```

Body:
Images Count:

Please help me with the code to display the count, count display needs to be in progressiveness counting.

Body:
You can try below code

$(document).ready(function(){
    console.log("Images count="+ $(".images").find("img").length)

$("#imgcount").text( $(".images").find("img").length)
});

<div id="box">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>

<p style="padding: 20px;">Images Count:</p>
</div>
<div class="images">
<img src="img001.jpg">
<img src="img002.jpg">
<img src="img003.jpg">
<img src="img004.jpg">
<img src="img005.jpg">
<img src="img006.jpg">

</div>

Total No. of Images in page are <label id="imgcount">


问:
Django formset doesn't validate
I am trying to save a formset but it seems to be bypassing is_valid() even though there are required fields.

To test this I have a simple form:

```<code>class AlbumForm(forms.Form):
  name = forms.CharField(required=True)
</code>```

The view:

```<code>@login_required
def add_album(request, artist):
  artist = Artist.objects.get(slug__iexact=artist)
  AlbumFormSet = formset_factory(AlbumForm)
  if request.method == 'POST':
    formset = AlbumFormSet(request.POST, request.FILES)
    if formset.is_valid():
      return HttpResponse('worked')
  else:
    formset = AlbumFormSet()
  return render_to_response('submissions/addalbum.html', {
   'artist': artist,
   'formset': formset,
  }, context_instance=RequestContext(request))
</code>```

And the template:

```<code><form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ formset.management_form }}
{% for form in formset.forms %}
  <ul class="addalbumlist">
    {% for field in form %}
     <li>
        {{ field.label_tag }}
        {{ field }}
        {{ field.errors }}
     </li>
    {% endfor %}
  </ul>
{% endfor %}
   <div class="inpwrap">
    <input type="button" value="add another">
    <input type="submit" value="add">
   </div>
</form>
</code>```

What ends up happening is I hit "add" without entering a name then HttpResponse('worked') get's called seemingly assuming it's a valid form.

I might be missing something here, but I can't see what's wrong. What I want to happen is, just like any other form if the field is required to spit out an error if its not filled in. Any ideas?

答:
For each of the fields that are required, add an extra entry in the attrs parameter

```<code>
    resident_status = forms.ChoiceField(widget=forms.Select(
        attrs={'class': 'form-control', 'required': 'required'}), choices=President.RESIDENT_STATUS,
        required=True)

</code>
```

As you can see, I maintain the required=True for django's form validation but specify 'required':'required' for the template to insist for the field be required.

Hope that helps.

Title: Django formset doesn't validate

Body:
I am trying to save a formset but it seems to be bypassing is_valid() even though there are required fields.

To test this I have a simple form:

class AlbumForm(forms.Form):
  name = forms.CharField(required=True)

The view:

@login_required
def add_album(request, artist):
  artist = Artist.objects.get(slug__iexact=artist)
  AlbumFormSet = formset_factory(AlbumForm)
  if request.method == 'POST':
    formset = AlbumFormSet(request.POST, request.FILES)
    if formset.is_valid():
      return HttpResponse('worked')
  else:
    formset = AlbumFormSet()
  return render_to_response('submissions/addalbum.html', {
   'artist': artist,
   'formset': formset,
  }, context_instance=RequestContext(request))

And the template:

<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ formset.management_form }}
{% for form in formset.forms %}

    {% for field in form %}

        {{ field.label_tag }}
        {{ field }}
        {{ field.errors }}

    {% endfor %}

{% endfor %}

    <input type="button" value="add another">
    <input type="submit" value="add">

</form>

What ends up happening is I hit "add" without entering a name then HttpResponse('worked') get's called seemingly assuming it's a valid form.

I might be missing something here, but I can't see what's wrong. What I want to happen is, just like any other form if the field is required to spit out an error if its not filled in. Any ideas?

Body:
For each of the fields that are required, add an extra entry in the attrs parameter

    resident_status = forms.ChoiceField(widget=forms.Select(
        attrs={'class': 'form-control', 'required': 'required'}), choices=President.RESIDENT_STATUS,
        required=True)

As you can see, I maintain the required=True for django's form validation but specify 'required':'required' for the template to insist for the field be required.

Hope that helps.


问:
order by str_to_date query return error while using php
I have created a query it was working perfectly on phpmyadmin

```<code>SELECT *,STR_TO_DATE(horoaccess_validity_enddate , '%d-%m-%y') as horo FROM userlogin WHERE type='user' ORDER BY horo  DESC
</code>```

but when I pass this query on PHP return error as query was empty
my PHP code is

```<code>$selectorders=sprintf("SELECT *,STR_TO_DATE(horoaccess_validity_enddate , '%d-%m-%y') as hor FROM userlogin WHERE type='user' ORDER BY horo  DESC");
$myorderquery = mysql_query($selectorders) or die(mysql_error());
$row_rsselect = mysql_fetch_assoc($myorderquery);
</code>```

答:
You are using sprintf for no reason. Since your date format use '%' characters, you need to double them if you want to use this function anyway :

```<code>$selectorders=sprintf("SELECT *,STR_TO_DATE(horoaccess_validity_enddate , '%%d-%%m-%%y') as hor FROM userlogin WHERE type='user' ORDER BY horo  DESC");
</code>```

Just use a string declaration and it will work.

Body:
I have created a query it was working perfectly on phpmyadmin

SELECT *,STR_TO_DATE(horoaccess_validity_enddate , '%d-%m-%y') as horo FROM userlogin WHERE type='user' ORDER BY horo  DESC

but when I pass this query on PHP return error as query was empty
my PHP code is

$selectorders=sprintf("SELECT *,STR_TO_DATE(horoaccess_validity_enddate , '%d-%m-%y') as hor FROM userlogin WHERE type='user' ORDER BY horo  DESC");
$myorderquery = mysql_query($selectorders) or die(mysql_error());
$row_rsselect = mysql_fetch_assoc($myorderquery);

Body:
You are using sprintf for no reason. Since your date format use '%' characters, you need to double them if you want to use this function anyway :

$selectorders=sprintf("SELECT *,STR_TO_DATE(horoaccess_validity_enddate , '%%d-%%m-%%y') as hor FROM userlogin WHERE type='user' ORDER BY horo  DESC");

Just use a string declaration and it will work.


问:
NativeScript Sidekick won't run since CLI 3.2.1 update doesn't work
I opened NativeScript Sidekick on my Mac and it updated to the latest version 0.2.5.

It shows a dialog stating I need to update NativeScript CLI to 3.2.1 and the only option is to quit.

I went to Terminal and tried tns update but it won't update to 3.2.1 saying the platforms for 3.2.1 are not available. (I posted to the NativeScript forums and was told that is correct -- the platforms are at 3.2.0 while only the CLI is updated to 3.2.1.)

I also tried tns update 3.2.1 which simply says 3.2.1 platforms are not available.

tns doctor says 3.2.1 update is available.

NativeScript CLI version is 3.2.0
npm version is 5.4.1
node version is 6.11.3

I've tried creating a new project and it gives me the same issues.

How can I update to NativeScript CLI 3.2.1 so that I can run NativeScript Sidekick?

答:
If you are using nvm to manage your NodeJS versions you can try to set the default version to the one that has installed NativeScript CLI. For example if you have NativeScript CLI on NodeJS version 8.9.2, execute:

```<code>nvm alias default 8.9.2
</code>```

To check the packages installed on your active NodeJS version, execute:

```<code>npm list -g --depth 0
</code>```

Body:
If you are using nvm to manage your NodeJS versions you can try to set the default version to the one that has installed NativeScript CLI. For example if you have NativeScript CLI on NodeJS version 8.9.2, execute:

nvm alias default 8.9.2

To check the packages installed on your active NodeJS version, execute:

npm list -g --depth 0


问:
How can I use arrayExists function when the array contains a null value?
I have a nullable array column in my table: Array(Nullable(UInt16)). I want to be able to query this column using arrayExists (or arrayAll) to check if it contains a value above a certain threshold but I'm getting an exception when the array contains a null value:

Exception: Expression for function arrayExists must return UInt8, found Nullable(UInt8)

My query is below where distance is the array column:

```<code>SELECT * from TracabEvents_ArrayTest
where arrayExists(x -> x > 9, distance);
</code>```

I've tried updating the comparison in the lambda to "(isNotNull(x) and x > 9)" but I'm still getting the error. Is there any way of handling nulls in these expressions or are they not supported yet?

答:
Add a condition to filter rows with empty list using notEmpty and assumeNotNull for x in arrayExists.</p>

```<code>SELECT * FROM TracabEvents_ArrayTest WHERE notEmpty(distance) AND arrayExists(x -> assumeNotNull(x) > 9, distance)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a nullable array column in my table: Array(Nullable(UInt16)). I want to be able to query this column using arrayExists (or arrayAll) to check if it contains a value above a certain threshold but I'm getting an exception when the array contains a null value:

Exception: Expression for function arrayExists must return UInt8, found Nullable(UInt8)

My query is below where distance is the array column:

SELECT * from TracabEvents_ArrayTest
where arrayExists(x -> x > 9, distance);

I've tried updating the comparison in the lambda to "(isNotNull(x) and x > 9)" but I'm still getting the error. Is there any way of handling nulls in these expressions or are they not supported yet?

Body:
Add a condition to filter rows with empty list using notEmpty and assumeNotNull for x in arrayExists.

SELECT * FROM TracabEvents_ArrayTest WHERE notEmpty(distance) AND arrayExists(x -> assumeNotNull(x) > 9, distance)


问:
Get json data at the end of a file upload data task
I am trying to upload a file to the server and after the completion of upload, I'm supposed to get a JSON response.
I can see the data when I use the completion block

```<code>uploaderSession.dataTask(with: request, completionHandler: { (data, response, error) in
                print("\(NSString(data: data!, encoding: 4))")
            }).resume()
</code>```

I need the same data but using the custom delegates

```<code>    let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    session.dataTask(with: request).resume()
</code>```

I implemented

```<code>func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
</code>```

but  didReceiveData is not called.
Please suggest what can  be done to get the JSON data at the end of completion of file upload

Thanks in advance

答:
ok so got the answer just posting cause it can help somebody

we have to call

```<code>completionHandler(URLSession.ResponseDisposition.allow)
</code>```

in

```<code>func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
</code>```

Body:
I am trying to upload a file to the server and after the completion of upload, I'm supposed to get a JSON response.
I can see the data when I use the completion block

uploaderSession.dataTask(with: request, completionHandler: { (data, response, error) in
                print("\(NSString(data: data!, encoding: 4))")
            }).resume()

I need the same data but using the custom delegates

    let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    session.dataTask(with: request).resume()

I implemented

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)

but  didReceiveData is not called.
Please suggest what can  be done to get the JSON data at the end of completion of file upload

Thanks in advance

Body:
ok so got the answer just posting cause it can help somebody

we have to call

completionHandler(URLSession.ResponseDisposition.allow)

in

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)


问:
Java balanced expressions check {[()]}
I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expression. It needs to handle ( { [ ] } ) each open needs to balance with its corresponding closing bracket. For example a user could input [({})] which would be balanced and }{ would be unbalanced. This doesn't need to handle letters or numbers. I need to use a stack to do this.

I was given this pseudocode but can not figure how to implement it in java. Any advice would be awesome.

Update- sorry forgot to post what i had so far. Its all messed up because at first i was trying to use char and then i tried an array.. im not exactly sure where to go.

```<code>import java.util.*;

public class Expression
{
  Scanner in = new Scanner(System.in);
  Stack<Integer> stack = new Stack<Integer>();

  public boolean check()
  {
    System.out.println("Please enter your expression.");
    String newExp = in.next();
    String[] exp = new String[newExp];
    for (int i = 0; i < size; i++)
    {

      char ch = exp.charAt(i);
      if (ch == '(' || ch == '[' || ch == '{')
        stack.push(i);
      else if (ch == ')'|| ch == ']' || ch == '}')
      {
        //nothing to match with
        if(stack.isEmpty())
        {
          return false;
        }
        else if(stack.pop() != ch)
        {
          return false;
        }

      }
    }
    if (stack.isEmpty())
    {
      return true;
    }
    else
    {
      return false;
    }
  }

}
</code>```

答:
Similar to one of the code above in JAVA but It needs one more else statement added in order to avoid stack comparison with characters other than braces :

else if(bracketPair.containsValue(strExpression.charAt(i)))

```<code>public boolean isBalanced(String strExpression){
 Map<Character,Character> bracketPair = new HashMap<Character,Character>();
  bracketPair.put('(', ')');
  bracketPair.put('[', ']');
  bracketPair.put('{', '}');
  Stack<Character> stk = new Stack<Character>();
        for(int i =0;i<strExpression.length();i++){
            if(bracketPair.containsKey(strExpression.charAt(i)))
                stk.push(strExpression.charAt(i));
            else if(bracketPair.containsValue(strExpression.charAt(i)))
                if(stk.isEmpty()||bracketPair.get(stk.pop())!=strExpression.charAt(i))
                return false;
        }

        if(stk.isEmpty())
            return true;
            else
                return false;
        }
</code>```

Title: Java balanced expressions check {[()]}

Body:
I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expression. It needs to handle ( { [ ] } ) each open needs to balance with its corresponding closing bracket. For example a user could input [({})] which would be balanced and }{ would be unbalanced. This doesn't need to handle letters or numbers. I need to use a stack to do this.

I was given this pseudocode but can not figure how to implement it in java. Any advice would be awesome.

Update- sorry forgot to post what i had so far. Its all messed up because at first i was trying to use char and then i tried an array.. im not exactly sure where to go.

import java.util.*;

public class Expression
{
  Scanner in = new Scanner(System.in);
  Stack<Integer> stack = new Stack<Integer>();

  public boolean check()
  {
    System.out.println("Please enter your expression.");
    String newExp = in.next();
    String[] exp = new String[newExp];
    for (int i = 0; i < size; i++)
    {

      char ch = exp.charAt(i);
      if (ch == '(' || ch == '[' || ch == '{')
        stack.push(i);
      else if (ch == ')'|| ch == ']' || ch == '}')
      {
        //nothing to match with
        if(stack.isEmpty())
        {
          return false;
        }
        else if(stack.pop() != ch)
        {
          return false;
        }

      }
    }
    if (stack.isEmpty())
    {
      return true;
    }
    else
    {
      return false;
    }
  }

}

Body:
Similar to one of the code above in JAVA but It needs one more else statement added in order to avoid stack comparison with characters other than braces :

else if(bracketPair.containsValue(strExpression.charAt(i)))

public boolean isBalanced(String strExpression){
 Map<Character,Character> bracketPair = new HashMap<Character,Character>();
  bracketPair.put('(', ')');
  bracketPair.put('[', ']');
  bracketPair.put('{', '}');
  Stack<Character> stk = new Stack<Character>();
        for(int i =0;i<strExpression.length();i++){
            if(bracketPair.containsKey(strExpression.charAt(i)))
                stk.push(strExpression.charAt(i));
            else if(bracketPair.containsValue(strExpression.charAt(i)))
                if(stk.isEmpty()||bracketPair.get(stk.pop())!=strExpression.charAt(i))
                return false;
        }

        if(stk.isEmpty())
            return true;
            else
                return false;
        }


答:
If you view the source and search for "Marokko" you will see there are several places where it occurs (loaded as data in several JavaScript arrays).

It appears as if some of the content is produced dynamically through the JavaScript loaded onto the page.  That JavaScript builds HTML and changes the page to include the content you are looking for.

Title: parsing html, source code, javascript problem


问:
Spring Test HTMLUnit NoSuchMethod CookieManager.getCookies(URL)
I'm having an problem running HTMLUnit tests using spring-test-htmlunit. When calling getPage() on an instance of WebClient, I get a noSuchMethod error as follows:

```<code>java.lang.NoSuchMethodError: com.gargoylesoftware.htmlunit.CookieManager.getCookies(Ljava/net/URL;)Ljava/util/Set;
    at org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilder.cookies(HtmlUnitRequestBuilder.java:267)
    at org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilder.buildRequest(HtmlUnitRequestBuilder.java:104)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:141)
    at org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection.getResponse(MockMvcWebConnection.java:111)
    at org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection.getResponse(MockMvcWebConnection.java:96)
    at org.springframework.test.web.servlet.htmlunit.DelegatingWebConnection.getResponse(DelegatingWebConnection.java:68)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1357)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1274)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:382)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:304)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:451)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:436)
</code>```

I've tried excluding the HTMLUnit version from spring-test-htmlunit and adding the latest version. I also have a dependency for nekoHTML that is needed for thymeleaf template compilation.

relevant pom.xml

```<code> <dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.21</version>
 </dependency>
 <dependency>
    <groupId>org.springframework.test.htmlunit</groupId>
    <artifactId>spring-test-htmlunit</artifactId>
    <version>1.0.0.RC1</version>
    <scope>test</scope>
 </dependency>
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</code>```

the offending call

```<code>HtmlPage page = webClient.getPage("http://localhost:8080/");
</code>```

答:
Usually, this is a dependency conflict, you can print down the currently used JARs by something like:

```<code>System.out.println(WebClient.class.getProtectionDomain().getCodeSource().getLocation());
System.out.println(HTMLElements.class.getProtectionDomain().getCodeSource().getLocation());
</code>```

And ensure the Neko version is compatible with the corresponding HtmlUnit version.

Also, spring boot includes specific HtmlUnit version, which may not be what you want.

Body:
I'm having an problem running HTMLUnit tests using spring-test-htmlunit. When calling getPage() on an instance of WebClient, I get a noSuchMethod error as follows:

java.lang.NoSuchMethodError: com.gargoylesoftware.htmlunit.CookieManager.getCookies(Ljava/net/URL;)Ljava/util/Set;
    at org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilder.cookies(HtmlUnitRequestBuilder.java:267)
    at org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilder.buildRequest(HtmlUnitRequestBuilder.java:104)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:141)
    at org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection.getResponse(MockMvcWebConnection.java:111)
    at org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection.getResponse(MockMvcWebConnection.java:96)
    at org.springframework.test.web.servlet.htmlunit.DelegatingWebConnection.getResponse(DelegatingWebConnection.java:68)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1357)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1274)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:382)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:304)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:451)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:436)

I've tried excluding the HTMLUnit version from spring-test-htmlunit and adding the latest version. I also have a dependency for nekoHTML that is needed for thymeleaf template compilation.

relevant pom.xml

 <dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.21</version>
 </dependency>
 <dependency>
    <groupId>org.springframework.test.htmlunit</groupId>
    <artifactId>spring-test-htmlunit</artifactId>
    <version>1.0.0.RC1</version>
    <scope>test</scope>
 </dependency>
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

the offending call

HtmlPage page = webClient.getPage("http://localhost:8080/");

Body:
Usually, this is a dependency conflict, you can print down the currently used JARs by something like:

System.out.println(WebClient.class.getProtectionDomain().getCodeSource().getLocation());
System.out.println(HTMLElements.class.getProtectionDomain().getCodeSource().getLocation());

And ensure the Neko version is compatible with the corresponding HtmlUnit version.

Also, spring boot includes specific HtmlUnit version, which may not be what you want.


问:
In SQL how to split an select a string which is not present i a table?
Here is my query I used to get UserID present in both where condition and TSTable

```<code>                    SELECT  UserID
                    FROM    TSTable
                    WHERE UserID IN (@UserID)
</code>```

I need to to get the UserId from @UserID

```<code>  where    @UserID = ''IMS080'',''IMS108'',''IMS218''
</code>```

which are not present in TSTable. How can I do this?
For example, if I Execute the Query it should return value from IN condition
'IMS080' which is not present in TSTable.

Thanks in Advance

答:
Try this</p>

```<code>;WITH CTE AS
(
    SELECT Split.a.value('.', 'VARCHAR(100)') AS USERID
    FROM
    (
        SELECT CAST ('<M>' + REPLACE('IMS080,IMS108,IMS218', ',', '</M><M>') + '</M>' AS XML) AS Data
    )AS A CROSS APPLY Data.nodes ('/M') AS Split(a)
)
SELECT * FROM CTE
WHERE USERID NOT IN (SELECT UserId FROM #TSTable)
</code>```

Body:
Here is my query I used to get UserID present in both where condition and TSTable

                    SELECT  UserID
                    FROM    TSTable
                    WHERE UserID IN (@UserID)

I need to to get the UserId from @UserID

  where    @UserID = ''IMS080'',''IMS108'',''IMS218''

which are not present in TSTable. How can I do this?
For example, if I Execute the Query it should return value from IN condition
'IMS080' which is not present in TSTable.

Thanks in Advance

Body:
Try this

;WITH CTE AS
(
    SELECT Split.a.value('.', 'VARCHAR(100)') AS USERID
    FROM
    (
        SELECT CAST ('<M>' + REPLACE('IMS080,IMS108,IMS218', ',', '</M><M>') + '</M>' AS XML) AS Data
    )AS A CROSS APPLY Data.nodes ('/M') AS Split(a)
)
SELECT * FROM CTE
WHERE USERID NOT IN (SELECT UserId FROM #TSTable)


问:
Get currency from setting in device android
How can I get currency from my android device.

Ex: I set English language then I can get dollar currency. But I live in Singapore, how can the device returns SGD? (Singapore doesn't use dollar).

Ex: Samsung Galaxy J5 use English language
I live in USA -> dollar.

My friend lives in Singapore -> Singapore dollar

答:
Use this method to getCurrency Symbol , write this method in Common.java class

```<code>public static SortedMap<Currency, Locale> currencyLocaleMap;

static {
    currencyLocaleMap = new TreeMap<Currency, Locale>(new Comparator<Currency>() {
        public int compare(Currency c1, Currency c2) {
            return c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
        }
    });
    for (Locale locale : Locale.getAvailableLocales()) {
        try {
            Currency currency = Currency.getInstance(locale);
            currencyLocaleMap.put(currency, locale);
        } catch (Exception e) {
        }
    }
}

public static String getCurrencySymbol(String currencyCode) {
    Currency currency = Currency.getInstance(currencyCode);
    System.out.println(currencyCode + ":-" + currency.getSymbol(currencyLocaleMap.get(currency)));
    return currency.getSymbol(currencyLocaleMap.get(currency));
}
</code>```

now to get Currency Symbol use this way.

```<code>    String currencySymbol =Common.getCurrencySymbol(Currency.getInstance(Locale.US).getCurrencyCode());
    String currencySymbol =Common.getCurrencySymbol(Currency.getInstance(Locale.JAPAN).getCurrencyCode());
    String currencySymbol =Common.getCurrencySymbol(Currency.getInstance(Locale.UK).getCurrencyCode());

    //for your case that you want to get Euro symbol because France are with Euro symnol
    String currencySymbol =Common.getCurrencySymbol(Currency.getInstance(Locale.FRANCE).getCurrencyCode());
    //you can get symbol also if you write string of your desired currency
    String currencySymbol =Common.getCurrencySymbol("INR");
    String currencySymbol = CommonClass.getCurrencySymbol("ZAR");
</code>```

Hope this help.

Body:
Use this method to getCurrency Symbol , write this method in Common.java class

public static SortedMap<Currency, Locale> currencyLocaleMap;

static {
    currencyLocaleMap = new TreeMap<Currency, Locale>(new Comparator<Currency>() {
        public int compare(Currency c1, Currency c2) {
            return c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
        }
    });
    for (Locale locale : Locale.getAvailableLocales()) {
        try {
            Currency currency = Currency.getInstance(locale);
            currencyLocaleMap.put(currency, locale);
        } catch (Exception e) {
        }
    }
}

public static String getCurrencySymbol(String currencyCode) {
    Currency currency = Currency.getInstance(currencyCode);
    System.out.println(currencyCode + ":-" + currency.getSymbol(currencyLocaleMap.get(currency)));
    return currency.getSymbol(currencyLocaleMap.get(currency));
}

now to get Currency Symbol use this way.

    String currencySymbol =Common.getCurrencySymbol(Currency.getInstance(Locale.US).getCurrencyCode());
    String currencySymbol =Common.getCurrencySymbol(Currency.getInstance(Locale.JAPAN).getCurrencyCode());
    String currencySymbol =Common.getCurrencySymbol(Currency.getInstance(Locale.UK).getCurrencyCode());

    //for your case that you want to get Euro symbol because France are with Euro symnol
    String currencySymbol =Common.getCurrencySymbol(Currency.getInstance(Locale.FRANCE).getCurrencyCode());
    //you can get symbol also if you write string of your desired currency
    String currencySymbol =Common.getCurrencySymbol("INR");
    String currencySymbol = CommonClass.getCurrencySymbol("ZAR");

Hope this help.


问:
TYPO3 Extension: I changed my extension folder name and now TYPO3 throws an error message
So today my extension_builder overwrote my entire TCAs while saving, so I did something stupid: I changed the folder name of my extension via winscp and uploaded the backupfolder of my extension I made yesterday. Now I get the error message

```<code>Oops, an error occurred!
TYPO3 Fatal Error: Extension key "icingaconfgen" is NOT loaded!
</code>```

I know the error could be fixed with changing the state of the extension in the PackageStates.php to inactive, but the problem is: The extension doesn't appear in this file. Interesting enough the foldername I changed my old old extension folder to ("x") appears in the file as inactive though. What should I do now?

答:
I assume you meant the extension key. This key is used in differnt files of an extension.

If you rename an extension folder the old key still is used in some files. TYPO3 analyses all extensions and joined (active) parts into cached files, so be careful as what is active executed and what is stored on the disk can differ (always clear all caches - there are a lot of caches!)

One part of your problem may occur of two folders with the usage of the same extension key. here especially the foder you renamed, as there the foldername and the internal extension key do not match.

TLDR:

NEVER rename an extension folder inside of typo3conf/ext/.

If you want to backup an extension move it to e.g. typo3conf/ext.bak/.

Always clear all caches after such a manipulation. (With newer versions of TYPO3 it is at least typo3temp/Cache/Code/, but also have a look at typo3temp/autoload/ and the internal caches tables in the database.)

Body:
So today my extension_builder overwrote my entire TCAs while saving, so I did something stupid: I changed the folder name of my extension via winscp and uploaded the backupfolder of my extension I made yesterday. Now I get the error message

Oops, an error occurred!
TYPO3 Fatal Error: Extension key "icingaconfgen" is NOT loaded!

I know the error could be fixed with changing the state of the extension in the PackageStates.php to inactive, but the problem is: The extension doesn't appear in this file. Interesting enough the foldername I changed my old old extension folder to ("x") appears in the file as inactive though. What should I do now?


问:
How can I programmatically center UITextview across all devices?
My current code is below

```<code>    class SetupScene: SKScene{
        let myTextField: UITextField = UITextField(frame: CGRect(x: 208, y: 175, width: 230.00, height: 33.00));

    override func didMove(to view: SKView) {
        let background = SKSpriteNode(imageNamed: "pixelBackground")
        background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        background.size = self.size
        background.zPosition = -10
        self.addChild(background)

        self.view?.addSubview(myTextField)

        myTextField.backgroundColor = UIColor.white
        myTextField.text = "Enter your name:"
        myTextField.borderStyle = UITextBorderStyle.line
        myTextField.textAlignment = .center
        myTextField.font = UIFont(name: "04b_25", size: 25)

    }
}
</code>```

With the code above myTextField is at the top left of my screen(my screens in landscape orientation). I can manually move it where I want by inputing numbers into the x and y values but then it moves to different places depending on the device. And when I try to do:

```<code>    myTextField = UITextField(frame: CGRect(x: self.size.width/2, y: self.size.height/2, width: 230.00, height: 33.00))
</code>```

myTextField is missing from the screen. How can I center across all devices like I would in SpriteKit with: (x: self.size.width/2, y: self.size.height/2)

*Note I want to do this programmatically not with Storyboards

答:
Create a Custom class and use it as globally where you need.

```<code>class CustomTextField: UITextField {
    override init (frame : CGRect) {
        super.init(frame : frame)
    }
     func setUp() {
    //Setting constraints of CustomTextField with centerX, centerY
    self.translatesAutoresizingMaskIntoConstraints = false
    self.centerYAnchor.constraint(equalTo: (self.superview?.centerYAnchor)!).isActive = true
    self.centerXAnchor.constraint(equalTo: (self.superview?.centerXAnchor)!).isActive = true
    //use if you want fixed width
    self.widthAnchor.constraint(equalToConstant: 250).isActive = true
    //self.heightAnchor.constraint(equalToConstant: 250).isActive = true
    self.backgroundColor = .red
    self.textAlignment = .center
}
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
class ViewController: UIViewController{
    var demoText = CustomTextField()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(demoText)
        demoText.setUp()
        demoText.text = "hello"
    }
}
</code>```

Output:

Body:
My current code is below

    class SetupScene: SKScene{
        let myTextField: UITextField = UITextField(frame: CGRect(x: 208, y: 175, width: 230.00, height: 33.00));

    override func didMove(to view: SKView) {
        let background = SKSpriteNode(imageNamed: "pixelBackground")
        background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        background.size = self.size
        background.zPosition = -10
        self.addChild(background)

        self.view?.addSubview(myTextField)

        myTextField.backgroundColor = UIColor.white
        myTextField.text = "Enter your name:"
        myTextField.borderStyle = UITextBorderStyle.line
        myTextField.textAlignment = .center
        myTextField.font = UIFont(name: "04b_25", size: 25)

    }
}

With the code above myTextField is at the top left of my screen(my screens in landscape orientation). I can manually move it where I want by inputing numbers into the x and y values but then it moves to different places depending on the device. And when I try to do:

    myTextField = UITextField(frame: CGRect(x: self.size.width/2, y: self.size.height/2, width: 230.00, height: 33.00))

myTextField is missing from the screen. How can I center across all devices like I would in SpriteKit with: (x: self.size.width/2, y: self.size.height/2)

*Note I want to do this programmatically not with Storyboards

Body:
Create a Custom class and use it as globally where you need.

class CustomTextField: UITextField {
    override init (frame : CGRect) {
        super.init(frame : frame)
    }
     func setUp() {
    //Setting constraints of CustomTextField with centerX, centerY
    self.translatesAutoresizingMaskIntoConstraints = false
    self.centerYAnchor.constraint(equalTo: (self.superview?.centerYAnchor)!).isActive = true
    self.centerXAnchor.constraint(equalTo: (self.superview?.centerXAnchor)!).isActive = true
    //use if you want fixed width
    self.widthAnchor.constraint(equalToConstant: 250).isActive = true
    //self.heightAnchor.constraint(equalToConstant: 250).isActive = true
    self.backgroundColor = .red
    self.textAlignment = .center
}
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
class ViewController: UIViewController{
    var demoText = CustomTextField()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(demoText)
        demoText.setUp()
        demoText.text = "hello"
    }
}

Output:


问:
How a multidimensional array value assignation works in this case?
Why this function does not return an string with the first letter of each word on upper case?</p>

```<code>function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i][0] = str[i][0].toUpperCase();
         console.log(str);
     }
     return str;
}
</code>```

答:
You need to replace the whole array element with a new string. All you are doing is modifying a string but not what is in the array.

Then you need to join() the array again to get a string returned

```<code>function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i] = str[i][0].toUpperCase() + str[i].slice(1);
       // ^^ reassign array element with new string ^^
     }
     return str.join(' ');
}
</code>```

Body:
Why this function does not return an string with the first letter of each word on upper case?

function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i][0] = str[i][0].toUpperCase();
         console.log(str);
     }
     return str;
}

Body:
You need to replace the whole array element with a new string. All you are doing is modifying a string but not what is in the array.

Then you need to join() the array again to get a string returned

function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i] = str[i][0].toUpperCase() + str[i].slice(1);
       // ^^ reassign array element with new string ^^
     }
     return str.join(' ');
}


问:
React-Router v4 - pass parameters to withRouter
This code works fine:

```<code>const LinkButton = withRouter(({ history }) => (

  <ListItem button onClick={() => history.push('/url1')}>
    <ListItemIcon>
      <ListIcon />
    </ListItemIcon>
    <ListItemText primary="name1" />
  </ListItem>
))
</code>```

Now I try to map array to the same component and get error:

```<code>const navItems = [{ name: 'name1', url: '/url1' }, { name: 'name2', url: '/url2' }];

 const items = navItems.map(
  item => withRouter(({ history }) => (

    <ListItem button onClick={() => history.push(item.url)}>
      <ListItemIcon>
        <ListIcon />
      </ListItemIcon>
      <ListItemText primary={item.name} />
    </ListItem>
  ))()
);
</code>```

And the error text: TypeError: Cannot read property 'wrappedComponentRef' of undefined.

Any ideas?

答:
withRouter is a high-order component which returns a component class  (MyComponent ) NOT component instance (<MyComponent /> ) .

Also , LinkButton is hard coded ; it does not accept props for items.

Then, you need to update to following :

```<code>let LinkButton = ({ history, ...item }) => (

  <ListItem button onClick={() => history.push(item.url)}>
    <ListItemIcon>
      <ListIcon />
    </ListItemIcon>
    <ListItemText primary={item.name} />
  </ListItem>
);

LinkButton = withRouter(LinkButton);
</code>```

Now , the loop should be :

```<code>navItems.map(item => <LinkButton {...item} key={item.name} />);
</code>```

Body:
This code works fine:

const LinkButton = withRouter(({ history }) => (

  <ListItem button onClick={() => history.push('/url1')}>
    <ListItemIcon>
      <ListIcon />
    </ListItemIcon>
    <ListItemText primary="name1" />
  </ListItem>
))

Now I try to map array to the same component and get error:

const navItems = [{ name: 'name1', url: '/url1' }, { name: 'name2', url: '/url2' }];

 const items = navItems.map(
  item => withRouter(({ history }) => (

    <ListItem button onClick={() => history.push(item.url)}>
      <ListItemIcon>
        <ListIcon />
      </ListItemIcon>
      <ListItemText primary={item.name} />
    </ListItem>
  ))()
);

And the error text: TypeError: Cannot read property 'wrappedComponentRef' of undefined.

Any ideas?

Body:
withRouter is a high-order component which returns a component class  (MyComponent ) NOT component instance (<MyComponent /> ) .

Also , LinkButton is hard coded ; it does not accept props for items.

Then, you need to update to following :

let LinkButton = ({ history, ...item }) => (

  <ListItem button onClick={() => history.push(item.url)}>
    <ListItemIcon>
      <ListIcon />
    </ListItemIcon>
    <ListItemText primary={item.name} />
  </ListItem>
);

LinkButton = withRouter(LinkButton);

Now , the loop should be :

navItems.map(item => <LinkButton {...item} key={item.name} />);


问:
Jquery load function throws "XML Parsing Error: not well-formed" error in firefox
Trying to load an xml file and getting the xml parsing error.

```<code>$("#analyticForm_description").load('https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt', function() { MD.ui.editPallets.editform_definition(); } );
</code>```

Should not throw any error. Note the url provided is valid and accessible from a browser directly. The function is also being called. Somehow even after the error reported on console, page loads successfully.

Do not want to see any errors reported on console.

答:
I think Firefox expects an Content-Type and Chrome ignores it.

```<code>$.ajax({
    url : "https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt",
    contentType: "text/xml",
    success : function(response) {
        $("#analyticForm_description").html(response);
    }
});
</code>```

or for the load method use ajaxSetup:

Description: Set default values for future Ajax requests. Its use is
  not recommended.

```<code>$.ajaxSetup({
  contentType: "text/xml"
});

$("#analyticForm_description").load('https://192.168.23.10/SystemServices/...', function() {
  MD.ui.editPallets.editform_definition();
});
</code>```

Body:
Trying to load an xml file and getting the xml parsing error.

$("#analyticForm_description").load('https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt', function() { MD.ui.editPallets.editform_definition(); } );

Should not throw any error. Note the url provided is valid and accessible from a browser directly. The function is also being called. Somehow even after the error reported on console, page loads successfully.

Do not want to see any errors reported on console.

Body:
I think Firefox expects an Content-Type and Chrome ignores it.

$.ajax({
    url : "https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt",
    contentType: "text/xml",
    success : function(response) {
        $("#analyticForm_description").html(response);
    }
});

or for the load method use ajaxSetup:

Description: Set default values for future Ajax requests. Its use is
  not recommended.

$.ajaxSetup({
  contentType: "text/xml"
});

$("#analyticForm_description").load('https://192.168.23.10/SystemServices/...', function() {
  MD.ui.editPallets.editform_definition();
});


问:
What to choose to store just one integer? Sqlite? or Text file?
I've build a small web-service in PHP. I want to control the number of calls to a specific API method.

I thought at first of using a text file, because it's just an integer. But after taking a good look at SQLite it seemed much more convenient.
So the code is just: get the "counter" from SQLite and increment it when that method is called, then store it back on SQLite db.

Is this a right way of doing it? Would it be simpler and more scalable to just use a file or... maybe something else?

Thanks in advance.

答:
a third possibility: memcachedb. it's compatible with memcached, but stores it's key-value store to a BDB file.  it not only has read-write commands, but also atomic increment/decrement for numeric values.

one more alternative would be to write a 'counter server'. an independent process that gets 'read' and 'increment' commands over a socket. the advantage is that it's really easy to do 'atomic' increments.  it stores it's counter(s) on a simple file, without concurrency problems since there's never more than one server.

it should be easy to write in less than a hundred lines of C.  just a tight loop processing one command at a time, flushing to disk every few seconds.  since the processing is so simple, the latency is minimal.

OwnerDisplayName: rogeriopvl

OwnerDisplayName: Javier


问:
Execute Alert Before location.reload
I am using jQuery confirm min js. and use alert in my ajax code.

The problem is when my ajax code runs first it gives priority to locationReload and reload. I want to run alert first then reload.

One thing I note that if I use Simple ALERT('some') so it works but this can't.

My code is as follow

```<code>success:   function(data) {
  $.alert({
      title: 'Message!',
      content: data,
      theme: 'material',
      animation: 'zoom',
      animationBounce: 2.5,
  });
  //$('#thmb_prev').html(data);
  $('#loader').hide();
  location.reload();
}
</code>```

答:
you can use confirm box instead of alert then. So once you click on ok, then it will get reloaded. Try the below. you can find samples here</p>

```<code>$.confirm({
    title: 'Message!',
      content: data,
    buttons: {
        OK: {
            location.reload();
            }
        }
    }
});
</code>```

Title: Execute Alert Before location.reload

Body:
I am using jQuery confirm min js. and use alert in my ajax code.

The problem is when my ajax code runs first it gives priority to locationReload and reload. I want to run alert first then reload.

One thing I note that if I use Simple ALERT('some') so it works but this can't.

My code is as follow

success:   function(data) {
  $.alert({
      title: 'Message!',
      content: data,
      theme: 'material',
      animation: 'zoom',
      animationBounce: 2.5,
  });
  //$('#thmb_prev').html(data);
  $('#loader').hide();
  location.reload();
}

Body:
you can use confirm box instead of alert then. So once you click on ok, then it will get reloaded. Try the below. you can find samples here

$.confirm({
    title: 'Message!',
      content: data,
    buttons: {
        OK: {
            location.reload();
            }
        }
    }
});


问:
How to end the Completion Block in Next ViewController
I am having the below block in ViewController A

```<code>dispatch_async(dispatch_get_main_queue(), ^{
    [self dismissAnimated:YES completion:^(BOOL finished) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"adjustNavBar"
                                                            object:self];
    }];
});
</code>```

After the execution of 'dismissAnimated' block method the NSNotificationCenter is getting called and the Observer in ViewController B is executing the below code

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                            selector:@selector(adjustNavBar)
                            name:@"adjustNavBar"
                            object:nil];
}

-(void)adjustNavBar {
    [self checkForPartialScroll];
}
</code>```

after execution of the above code, it is ending in ViewController A.

But i want to end the process in ViewController B. How to do this, i am newly trying this callback functions.

using Delegates or Callbacks, can i achieve what i am trying ?

答:
write that code above your code ,
HomeVC name of your next VC &
@"HomeVC" identifier of your next VC  </p>

```<code> dispatch_async(dispatch_get_global_queue(0, 0), ^{
  HomeVC *homeVC = (HomeVC *) [self.storyboard instantiateViewControllerWithIdentifier:@"HomeVC"];
    }
</code>```

Body:
I am having the below block in ViewController A

dispatch_async(dispatch_get_main_queue(), ^{
    [self dismissAnimated:YES completion:^(BOOL finished) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"adjustNavBar"
                                                            object:self];
    }];
});

After the execution of 'dismissAnimated' block method the NSNotificationCenter is getting called and the Observer in ViewController B is executing the below code

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                            selector:@selector(adjustNavBar)
                            name:@"adjustNavBar"
                            object:nil];
}

-(void)adjustNavBar {
    [self checkForPartialScroll];
}

after execution of the above code, it is ending in ViewController A.

But i want to end the process in ViewController B. How to do this, i am newly trying this callback functions.

using Delegates or Callbacks, can i achieve what i am trying ?

Body:
write that code above your code ,
HomeVC name of your next VC &
@"HomeVC" identifier of your next VC

 dispatch_async(dispatch_get_global_queue(0, 0), ^{
  HomeVC *homeVC = (HomeVC *) [self.storyboard instantiateViewControllerWithIdentifier:@"HomeVC"];
    }


问:
jQuery SimplyScroll plugin breaks on some zoom levels
You can actually see this effect on the SimplyScroll demo page: use Safari, Chrome or Firefox, and zoom out to the point that page elements are very small, and the scroller stops moving.

I've tested and experimented, and it appears that the scrollLeft value is being incremented within a setInterval loop, but it doesn't "stick", and just stays at the previous scroll value instead. Even more strangely, altering the scroll value manually from the console works just fine.

Here is the relevant snippet:

```<code>self.interval = setInterval(function() {
    // snip

    // increment by 1 pixel
    self.$clip[0].scrollLeft += self.o.speed;

    // scrollLeft value is unchanged

    // snip

},self.intervalDelay); // usually set to 41
</code>```

I've tried replacing setInterval with requestAnimationFrame, and also drastically turning down the speed, and no results; I'm stumped. Any ideas on why zoom level is affecting the ability to scroll within a timer callback?

答:
step 1: Add function below

```<code>fixScrollNotRunWhenBrowserZoomout: function(){
    var self = this;
    var speed = self.o.speed;
    var sp = self.$clip[0].scrollLeft;
    var intervalHandle = setInterval(function(){
        self.$clip[0].scrollLeft += speed;
        if (Math.floor(self.$clip[0].scrollLeft) !== sp || speed == 100){
            clearInterval(intervalHandle);
            self.o.speed = speed;
        }
        speed++;
    }, 100);
}
</code>```

Step 2: call it on init function

```<code>init: function() {

    this.$items = this.$list.children();
    this.$clip = this.$list.parent(); //this is the element that scrolls
    this.$container = this.$clip.parent();
    this.$btnBack = $('.simply-scroll-back',this.$container);
    this.$btnForward = $('.simply-scroll-forward',this.$container);

    this.fixScrollNotRunWhenBrowserZoomout();
</code>```

Body:
You can actually see this effect on the SimplyScroll demo page: use Safari, Chrome or Firefox, and zoom out to the point that page elements are very small, and the scroller stops moving.

I've tested and experimented, and it appears that the scrollLeft value is being incremented within a setInterval loop, but it doesn't "stick", and just stays at the previous scroll value instead. Even more strangely, altering the scroll value manually from the console works just fine.

Here is the relevant snippet:

self.interval = setInterval(function() {
    // snip

    // increment by 1 pixel
    self.$clip[0].scrollLeft += self.o.speed;

    // scrollLeft value is unchanged

    // snip

},self.intervalDelay); // usually set to 41

I've tried replacing setInterval with requestAnimationFrame, and also drastically turning down the speed, and no results; I'm stumped. Any ideas on why zoom level is affecting the ability to scroll within a timer callback?

Body:
step 1: Add function below

fixScrollNotRunWhenBrowserZoomout: function(){
    var self = this;
    var speed = self.o.speed;
    var sp = self.$clip[0].scrollLeft;
    var intervalHandle = setInterval(function(){
        self.$clip[0].scrollLeft += speed;
        if (Math.floor(self.$clip[0].scrollLeft) !== sp || speed == 100){
            clearInterval(intervalHandle);
            self.o.speed = speed;
        }
        speed++;
    }, 100);
}

Step 2: call it on init function

init: function() {

    this.$items = this.$list.children();
    this.$clip = this.$list.parent(); //this is the element that scrolls
    this.$container = this.$clip.parent();
    this.$btnBack = $('.simply-scroll-back',this.$container);
    this.$btnForward = $('.simply-scroll-forward',this.$container);

    this.fixScrollNotRunWhenBrowserZoomout();


问:
TFS Online and Visual Studio 2013

I am trying to automate my builds/releases. I'm using VS 2013 for development and I put my team project on VSTS (Visual Studio Team Services). I downloaded "Build and Release Agent" and installed a private agent on my machine. Agent connected successfully and listening for jobs as well. But when I am trying to create a build from Visual Studio Online it doesn't build and fails. The error that I am getting is

Error: Visual Studio 2015 is not found. Try again with a version that exists on your build agent machine

Do I need to get Visual Studio 2015? But I don't have a license for that.

答:
VSTS checks the agent to see what capabilities it supports - basically what other dev tools are installed on the agent machine - and it sounds like that's the check that's failing here.

But why not update to Visual Studio 2017, the latest, now? The Community edition is free and quite full featured. I expect you'd be happy going that route.

Title: TFS Online and Visual Studio 2013


问:
SVG resources? Good forums, help sites, examples?
I am currently doing a SVG project for school and I was wondering if I could be given any good sites with some awesome SVG examples? I can't even find a forum where I can ask questions specific to SVG. </p>

<p>Any help would be appreciated. </p>

答:
Check out the courses offered by the W3C on SVG, and read the SVG primer.

A good place for asking questions is e.g stackoverflow (hey, you're here already, good for you!), the #svg channel on the freenode IRC network and the svg-developers mailinglist.

If you're looking for examples etc, feel free to have a look through the links here.

Body:
I am currently doing a SVG project for school and I was wondering if I could be given any good sites with some awesome SVG examples? I can't even find a forum where I can ask questions specific to SVG.

Any help would be appreciated.


问:
How to write selenium code for autocomplete text box withe list selection
I'm trying to write Selenium code for below HTML source code..

This field is the auto populated field for input selection

```<code><input id="ctl00_ContentPlaceHolder1_txtBranch" class="textbox_service ui-autocomplete-input" name="ctl00$ContentPlaceHolder1$txtBranch" style="width: 200px;" onblur="return branch();" onchange="return CheckBranchName();" tabindex="6" autocomplete="off" type="text"/>
</code>```

Any one can help me out to write the code?

Web element screen shot attached.
Thanks in advance.

答:
This is the best I could do with the information you provided. If you could show the HTML for what the autocomplete list looks like that would be great. You didn't specify any language so I'll assume it's Java.  </p>

```<code>WebElement field = driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtBranch"));
field.click();
field.sendKeys(Keys.SPACE);

List<WebElement> items = driver.findElements(By.tagName("li");

for (int i=0; i<items.size();i++) {
WebElement elementYouWantToClick = items.get(i);
     String x = elementYouWantToClick.getText();
     if(x.contains("TextThatIsInYourElementYouWantToChoose")){
         elementYouWantToClick.click();
}
</code>```

<p>Best I could do for now with such limited information. </p>

Body:
I'm trying to write Selenium code for below HTML source code..

This field is the auto populated field for input selection

<input id="ctl00_ContentPlaceHolder1_txtBranch" class="textbox_service ui-autocomplete-input" name="ctl00$ContentPlaceHolder1$txtBranch" style="width: 200px;" onblur="return branch();" onchange="return CheckBranchName();" tabindex="6" autocomplete="off" type="text"/>

Any one can help me out to write the code?

Web element screen shot attached.
Thanks in advance.

Body:
This is the best I could do with the information you provided. If you could show the HTML for what the autocomplete list looks like that would be great. You didn't specify any language so I'll assume it's Java.

WebElement field = driver.findElement(By.id("ctl00_ContentPlaceHolder1_txtBranch"));
field.click();
field.sendKeys(Keys.SPACE);

List<WebElement> items = driver.findElements(By.tagName("li");

for (int i=0; i<items.size();i++) {
WebElement elementYouWantToClick = items.get(i);
     String x = elementYouWantToClick.getText();
     if(x.contains("TextThatIsInYourElementYouWantToChoose")){
         elementYouWantToClick.click();
}

Best I could do for now with such limited information.


问:
How to decrease vertical space between two cell in collectionview?

How to decrease the vertical space between two cell in collectionview?

答:
Add these lines while creating collection view layout </p>

```<code>layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0

 let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
        layout.itemSize = CGSize(width: screenWidth/2, height: screenWidth/2)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView!.collectionViewLayout = layout

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if indexPath.row == 0
    {
        return CGSize(width: screenWidth, height: screenWidth/2)
    }
    return CGSize(width: screenWidth/2, height: screenWidth/2);

}
</code>```

Body:
Add these lines while creating collection view layout

layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0

 let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
        layout.itemSize = CGSize(width: screenWidth/2, height: screenWidth/2)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView!.collectionViewLayout = layout

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if indexPath.row == 0
    {
        return CGSize(width: screenWidth, height: screenWidth/2)
    }
    return CGSize(width: screenWidth/2, height: screenWidth/2);

}


问:
JS Regex url validation
I tried to validate url with or without http No matter what i did the function return false.
I checked my regex string in this site:
http://regexr.com/
And its seen as i expect.

```<code>    function isUrlValid(userInput) {
        var regexQuery = "/(http(s)?://.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/";
        var url = new RegExp(regexQuery,"g");
        if (url.test(userInput)) {
            alert('Great, you entered an E-Mail-address');
            return true;
        }
        return false;
    }
</code>```

I fix the problem by change the .test to .match and leave the regex as is.

答:
Try this code.</p>

```<code>function CheckURL(fieldId, alertMessage) {
    var url = fieldId.value;
    if(url !== "")
    {
        if (url.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g) !== null)
            return true;
        else {
            alert(alertMessage);
            fieldId.focus();
            return false;
        }
    }
}

var website = document.getElementById('Website');
if (!CheckURL(website, "Enter a valid website address")) {
    return false;
}
</code>```

Title: JS Regex url validation

Body:
I tried to validate url with or without http No matter what i did the function return false.
I checked my regex string in this site:
http://regexr.com/
And its seen as i expect.

    function isUrlValid(userInput) {
        var regexQuery = "/(http(s)?://.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/";
        var url = new RegExp(regexQuery,"g");
        if (url.test(userInput)) {
            alert('Great, you entered an E-Mail-address');
            return true;
        }
        return false;
    }

I fix the problem by change the .test to .match and leave the regex as is.

Body:
Try this code.

function CheckURL(fieldId, alertMessage) {
    var url = fieldId.value;
    if(url !== "")
    {
        if (url.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g) !== null)
            return true;
        else {
            alert(alertMessage);
            fieldId.focus();
            return false;
        }
    }
}

var website = document.getElementById('Website');
if (!CheckURL(website, "Enter a valid website address")) {
    return false;
}


问:
Active record query on will_paginate
I want to use this query on will_paginate:

```<code>@courses = Course.where("id not in (?)", current_user.courses).paginate :page => params[:page], :order => 'code asc'
</code>```

It doesn't get me the results I want, unfortunately.

答: I added the :per_page parameter. Courtesy brian.

Title: Active record query on will_paginate

Body:
I want to use this query on will_paginate:

@courses = Course.where("id not in (?)", current_user.courses).paginate :page => params[:page], :order => 'code asc'

It doesn't get me the results I want, unfortunately.


问:
how to apply skip and limit filters in controller on Laravel API
## This is My controller Index method.

    How can I apply filters for this method. Here bookFormat method is custom method to get results. Thanks in advance.

```<code>public function index(){
        $input = Input::only('skip','limit');
        $books = Book::all();
        $results = [];
        foreach ($books as $book) {
         $results [] = $this->bookFormat($book);
     }
     $skip = null;
     if(isset($input['skip'])){
        $skip = $input['skip'];
     return $results->skip($skip);
     }
      $limit = null;
     if(isset($input['limit'])){
        $limit = $input['limit'];
        return $results->limit($limit)->get();
     }
     return $results;
 }
</code>```

答:
You can do it by checking isset and at last apply skip,take or limit,offset.

```<code>public function index(){
    $input = Input::only('skip','limit');
    $query = new Book();
    if(isset($input['skip']) && $input['skip']){
        $query = $query->skip($input['skip']);
    }
    if(isset($input['limit']) && $input['limit']){
        $query = $query->take($input['limit']);
    }

    $books = $query->get();

    $results = [];
    foreach ($books as $book) {
        $results [] = $this->bookFormat($book);
    }
    return $results;
}
</code>```

OR you can use Request $request to get skip and limit value

```<code>public function index(Request $request){
    $skip = (isset($request->skip) && $request->skip) ? $request->skip : '';
    $limit = (isset($request->limit) && $request->limit) ? $request->limit : '';
    .......................
    .......................
}
</code>```

Body:
## This is My controller Index method.

    How can I apply filters for this method. Here bookFormat method is custom method to get results. Thanks in advance.

public function index(){
        $input = Input::only('skip','limit');
        $books = Book::all();
        $results = [];
        foreach ($books as $book) {
         $results [] = $this->bookFormat($book);
     }
     $skip = null;
     if(isset($input['skip'])){
        $skip = $input['skip'];
     return $results->skip($skip);
     }
      $limit = null;
     if(isset($input['limit'])){
        $limit = $input['limit'];
        return $results->limit($limit)->get();
     }
     return $results;
 }

Body:
You can do it by checking isset and at last apply skip,take or limit,offset.

public function index(){
    $input = Input::only('skip','limit');
    $query = new Book();
    if(isset($input['skip']) && $input['skip']){
        $query = $query->skip($input['skip']);
    }
    if(isset($input['limit']) && $input['limit']){
        $query = $query->take($input['limit']);
    }

    $books = $query->get();

    $results = [];
    foreach ($books as $book) {
        $results [] = $this->bookFormat($book);
    }
    return $results;
}

OR you can use Request $request to get skip and limit value

public function index(Request $request){
    $skip = (isset($request->skip) && $request->skip) ? $request->skip : '';
    $limit = (isset($request->limit) && $request->limit) ? $request->limit : '';
    .......................
    .......................
}


答:
The reason Why this function does not return an string with the first letter of each word on upper case is because strings are immutable.

You cannot change a character within a string.

Therefore this does not work in javascript:

```<code>str[i][0] = 'c';
</code>```

This does not change the string str[i].

However in order to achieve your goal you can make a new string with first letter uppercase and assign it to the variable containing your string.

Title: How a multidimensional array value assignation works in this case?

Body:
Why this function does not return an string with the first letter of each word on upper case?

function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i][0] = str[i][0].toUpperCase();
         console.log(str);
     }
     return str;
}

Body:
The reason Why this function does not return an string with the first letter of each word on upper case is because strings are immutable.

You cannot change a character within a string.

Therefore this does not work in javascript:

str[i][0] = 'c';

This does not change the string str[i].

However in order to achieve your goal you can make a new string with first letter uppercase and assign it to the variable containing your string.


问:
iPhone X safe area not working
Currently I’m working in this project where I need to resolve a UI issue for iPhone X. I did some reading that said developers can use safe areas in XIB and it will resolve the problem. So I did it, and the simulator looks fine, but not my real device.

All the UI Components are attached to safe area. But only iPhone X simulator looks okay. How do I resolve this?

答: I found out the answer. Apparently, it was because XIB files were cached. I have to clean the project and re-run it. And it's working perfectly.</p>

Title: iPhone X safe area not working


问:
Java N-Dimensional Arrays
I need to be able to have an n-dimensional field where n is based on an input to the constructor.  But I'm not even sure if that's possible.  Is it?</p>

答:
Quick solution: you could approximate it with a non-generic ArrayList of ArrayList of ... going as deep as you need to. However, this may get awkward to use pretty fast.

An alternative requiring more work could be to implement your own type using an underlying flat array representation where you calculate the indexing internally, and providing accessor methods with vararg parameters. I am not sure if it is fully workable, but may be worth a try...

Rough example (not tested, no overflow checking, error handling etc. but hopefully communicates the basic idea):

```<code>class NDimensionalArray {
  private Object[] array; // internal representation of the N-dimensional array
  private int[] dimensions; // dimensions of the array
  private int[] multipliers; // used to calculate the index in the internal array

  NDimensionalArray(int... dimensions) {
    int arraySize = 1;

    multipliers = new int[dimensions.length];
    for (int idx = dimensions.length - 1; idx >= 0; idx--) {
      multipliers[idx] = arraySize;
      arraySize *= dimensions[idx];
    }
    array = new Object[arraySize];
    this.dimensions = dimensions;
  }
  ...
  public Object get(int... indices) {
    assert indices.length == dimensions.length;
    int internalIndex = 0;

    for (int idx = 0; idx < indices.length; idx++) {
      internalIndex += indices[idx] * multipliers[idx];
    }
    return array[internalIndex];
  }
  ...
}
</code>```

Title: Java N-Dimensional Arrays

Body:
Quick solution: you could approximate it with a non-generic ArrayList of ArrayList of ... going as deep as you need to. However, this may get awkward to use pretty fast.

An alternative requiring more work could be to implement your own type using an underlying flat array representation where you calculate the indexing internally, and providing accessor methods with vararg parameters. I am not sure if it is fully workable, but may be worth a try...

Rough example (not tested, no overflow checking, error handling etc. but hopefully communicates the basic idea):

class NDimensionalArray {
  private Object[] array; // internal representation of the N-dimensional array
  private int[] dimensions; // dimensions of the array
  private int[] multipliers; // used to calculate the index in the internal array

  NDimensionalArray(int... dimensions) {
    int arraySize = 1;

    multipliers = new int[dimensions.length];
    for (int idx = dimensions.length - 1; idx >= 0; idx--) {
      multipliers[idx] = arraySize;
      arraySize *= dimensions[idx];
    }
    array = new Object[arraySize];
    this.dimensions = dimensions;
  }
  ...
  public Object get(int... indices) {
    assert indices.length == dimensions.length;
    int internalIndex = 0;

    for (int idx = 0; idx < indices.length; idx++) {
      internalIndex += indices[idx] * multipliers[idx];
    }
    return array[internalIndex];
  }
  ...
}


问:
simple text toggle that opens just the next p
First I have to say I'm a beginner and my very question could be too obvious to some of you. But please be nice though.
We need a small text toggle based on jquery. It works perfectly so far but it opens every text on a given page. Is there a possibility that it opens just the next "p" and not every "Text2" on the page? Thanks for your help.

$('.show').click(function() {
  $('.hidden').slideToggle();
  $(this).text($(this).text() == 'more' ? 'less' : 'more');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>more</p>
<p style="display: none;" class="hidden">Text2</p>

<p>more</p>
<p style="display: none;" class="hidden">Text2</p>

<p>more</p>
<p style="display: none;" class="hidden">Text2</p></code>```

答:
You can use .closest() to traverse up to parent paragraph then use .next() to target following sibling to get .hidden paragraph.

```<code>$('.show').click(function() {
  $(this).closest('p').next('.hidden').slideToggle();
  $(this).text(function(_, text) {
    return text == 'more' ? 'less' : 'more';
  });
});
</code>```

$('.show').click(function() {
  $(this).closest('p').next('.hidden').slideToggle();
  $(this).text(function(_, text) {
    return text == 'more' ? 'less' : 'more';
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>more</p>
<p style="display: none;" class="hidden">Text1</p>

<p>more</p>
<p style="display: none;" class="hidden">Text2</p>

<p>more</p>
<p style="display: none;" class="hidden">Text3</p></code>```

Body:
First I have to say I'm a beginner and my very question could be too obvious to some of you. But please be nice though.
We need a small text toggle based on jquery. It works perfectly so far but it opens every text on a given page. Is there a possibility that it opens just the next "p" and not every "Text2" on the page? Thanks for your help.

$('.show').click(function() {
  $('.hidden').slideToggle();
  $(this).text($(this).text() == 'more' ? 'less' : 'more');
});

more

Text2

more

Text2

more

Text2

Body:
You can use .closest() to traverse up to parent paragraph then use .next() to target following sibling to get .hidden paragraph.

$('.show').click(function() {
  $(this).closest('p').next('.hidden').slideToggle();
  $(this).text(function(_, text) {
    return text == 'more' ? 'less' : 'more';
  });
});

$('.show').click(function() {
  $(this).closest('p').next('.hidden').slideToggle();
  $(this).text(function(_, text) {
    return text == 'more' ? 'less' : 'more';
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><a href="javascript:void(0)" class="show">more</a></p>
<p style="display: none;" class="hidden">Text1</p>

<p><a href="javascript:void(0)" class="show">more</a></p>
<p style="display: none;" class="hidden">Text2</p>

<p><a href="javascript:void(0)" class="show">more</a></p>
<p style="display: none;" class="hidden">Text3</p>


问:
Looking for a way to press a button in directive programmatically (Angular 2-5)
Hello guys I have an issue where i use this angular2 directive ng2-dual-listbox and I have no idea on how to reset/move the value on the selected item to available item of this directive (went and open issue on github but no response yet) even if I use .reset() to reset the reactive form where this directive is in and set the value to null but still, no luck.

Sample Image of the directive

But I got an idea. There is a move all selected item to available item button and I am going to press this button programmatically.
The problem is I don't know how to or if it is possible or not.

So I am looking for a way to press the specific button in the directive.
or are there any other way to workaround this.
I am in need of use this ng2-dual-listbox badly.
Thank you in advanced guys!

答:
I found the workaround!
I use ViewChild to call the function in the directive

How can I call function from directive after component's rendering?


问:
How to set random cookie value using rand function in PHP
How to set random cookie value using rand function in PHP

I don't want to change the value while page refreshed when it once assigned.. until cookie destroy

My code is as follows

```<code><?php
    global $random;
    $random= rand(0, 9999999);
    if(!isset($_COOKIE[$random])) {
        setcookie('user_cookie',$random, time() + (1), "/"); echo $_COOKIE[$random];
    }
    else {
        echo "Cookie '" . $_COOKIE[$random] . "' is set!<br>";
    }
    exit();
?>
</code>```

答:
Your set cookie code is incorrect and the cookie time is only 1 second

change your code as follows...

```<code><?php
//cookie_start();
global $random;
$random= rand(0, 9999999);
if(!isset($_COOKIE['user_cookie'])) {
    setcookie('user_cookie',$random, time() + (86400), "/");//86400 = 1 day
}
else {
    echo "Cookie '" . $_COOKIE['user_cookie'] . "' is set!<br>";
}
exit();
?>
</code>```

Body:
How to set random cookie value using rand function in PHP

I don't want to change the value while page refreshed when it once assigned.. until cookie destroy

My code is as follows

<?php
    global $random;
    $random= rand(0, 9999999);
    if(!isset($_COOKIE[$random])) {
        setcookie('user_cookie',$random, time() + (1), "/"); echo $_COOKIE[$random];
    }
    else {
        echo "Cookie '" . $_COOKIE[$random] . "' is set!
";
    }
    exit();
?>

Body:
Your set cookie code is incorrect and the cookie time is only 1 second

change your code as follows...

<?php
//cookie_start();
global $random;
$random= rand(0, 9999999);
if(!isset($_COOKIE['user_cookie'])) {
    setcookie('user_cookie',$random, time() + (86400), "/");//86400 = 1 day
}
else {
    echo "Cookie '" . $_COOKIE['user_cookie'] . "' is set!<br>";
}
exit();
?>


问:
Jest how to assert that function is not called
In Jest there are functions like tobeCalled or toBeCalledWith to check if a particular function is called.
Is there any way to check that a function is not called?

答:
Just use not.

expect(mockFn).not.toHaveBeenCalled()
```

See the jest documentation

Body:
Just use not.

expect(mockFn).not.toHaveBeenCalled()

See the jest documentation


问:
Bootstrap collapse not working even though js loaded
I have the following data-toggle i want to collapse for the menu. I have provided the necessary bootstrap classes, but it's still not working either.

Html code:

```<code><div class="navbar navbar-compact">
  <div class="navbar-inner">
    <div class="container">
      <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
      <a rel="nofollow" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse" title="Toggle menu">
        <span class="menu-name">Menu</span>
        <span class="menu-bars">
                    <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        </span>
      </a>
      <!-- Everything you want hidden at 940px or less, place within here -->
      <div class="nav-collapse collapse">
        <ul class="nav" id="topMenu" data-submenu="horizontal">
          <li class=" active ">
            <a rel="nofollow" href="//ss-template-blog03.simplesite.com/434337774">FRONT PAGE</a>
          </li>
          <li class="  ">
            <a rel="nofollow" href="//ss-template-blog03.simplesite.com/434337775">BLOG</a>
          </li>
          <li class="  ">
            <a rel="nofollow" href="//ss-template-blog03.simplesite.com/434337777">CONTACT</a>
          </li>
        </ul>
      </div>
    </div>
  </div>
</div>
</code>```

My Bootstrap classes that i have loaded into my project

bootstrap.collapse-2.3.2.js

bootstrap.dropdown-2.3.2.js

bootstrap.modal-2.3.2.js

I have my own CSS for the styling

This is how i load my js files

答:
You have 2 copy of Jquery.js files...
remove one of them
And include Bootstrap.js file after Jquery.js file.

Update:
Do not remove dot in ".nav-collapse" as suggested in another answer.

if this does not work.. try removing all other Bootstrap includes

I have Created Jsfidle:

```<code>[https://jsfiddle.net/DTcHh/40014/]
</code>```

Body:
I have the following data-toggle i want to collapse for the menu. I have provided the necessary bootstrap classes, but it's still not working either.

Html code:

        Menu

            FRONT PAGE

            BLOG

            CONTACT

My Bootstrap classes that i have loaded into my project

bootstrap.collapse-2.3.2.js

bootstrap.dropdown-2.3.2.js

bootstrap.modal-2.3.2.js

I have my own CSS for the styling

This is how i load my js files

Body:
You have 2 copy of Jquery.js files...
remove one of them
And include Bootstrap.js file after Jquery.js file.

Update:
Do not remove dot in ".nav-collapse" as suggested in another answer.

if this does not work.. try removing all other Bootstrap includes

I have Created Jsfidle:

[https://jsfiddle.net/DTcHh/40014/]


问:
CSS How to put 4 divs on each side of a parent div
I wish to include 4 divs inside a parent div in the following manner:

I could use fixed position and set right/left/top/bottom = 0 accordingly for each child div if they were not inside in a div, but right now, I can't figure out how to do this.

答:
Here you go, but I'm not sure how this will fare in responsiveness since the parent has fixed sizes, but the child div should be able to adapt if the parent changes size. Some css can be combined, but I separated them all for reference

.parent {
  width: 300px;
  height: 300px;
  position: relative;
  border: 1px solid black;
}

.div1 {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 80%;
  height: 20%;
  background-color: green;
}

.div2 {
  position: absolute;
  top: 0;
  right: 0;
  width: 20%;
  height: 80%;
  background-color: blue;
}

.div3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 80%;
  height: 20%;
  background-color: red;
}

.div4 {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 20%;
  height: 80%;
  background-color: brown;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="div1">
    DIV1
  </div>
  <div class="div2">
    DIV2
  </div>
  <div class="div3">
    DIV3
  </div>
  <div class="div4">
    DIV4
  </div>
</div></code>```

Body:
Here you go, but I'm not sure how this will fare in responsiveness since the parent has fixed sizes, but the child div should be able to adapt if the parent changes size. Some css can be combined, but I separated them all for reference

.parent {
  width: 300px;
  height: 300px;
  position: relative;
  border: 1px solid black;
}

.div1 {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 80%;
  height: 20%;
  background-color: green;
}

.div2 {
  position: absolute;
  top: 0;
  right: 0;
  width: 20%;
  height: 80%;
  background-color: blue;
}

.div3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 80%;
  height: 20%;
  background-color: red;
}

.div4 {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 20%;
  height: 80%;
  background-color: brown;
}

<div class="parent">
  <div class="div1">
    DIV1
  </div>
  <div class="div2">
    DIV2
  </div>
  <div class="div3">
    DIV3
  </div>
  <div class="div4">
    DIV4
  </div>
</div>