text:
Q: All Music Off iPhone I have an iPhone 4S, and I recently upgraded to Spotify Premium (it's awesome) and want to clear all the music off my iPhone (through the normal iPod app).
Thing is, I use iTunes Match so plugging into iTunes won't let me wipe it all out - and there are a lot of artists that I want to delete - it would take a long time.
Is there any way to expedite the process?

A: This isn't through the iPod app, but it (should) delete all the music from your device.
Settings > General > Usage > Music > Edit (button, upper right hand corner) > "-" button > Delete.


text:
Q: multiple file validation using javascript I am trying to upload multiple files via
<input type="file" id="uploadFiles" multiple onchange="checkFileUploadExt(this);"/>

using javascript
function checkFileUploadExt(fieldObj)
{
    var control = document.getElementById("uploadFiles");
    var filelength = control.files.length;
    var FileName = fieldObj.value;
    var FileExt = FileName.substr(FileName.lastIndexOf('.') + 1);
    if ((FileExt.toUpperCase() != "PDF"))
        if ((FileExt !== "pdf") || (FileExt !== "PDF"))
        {
            var error = "File type : " + FileExt + "\n\n";
            error += "Please make sure your file is in pdf  format .\n\n";
            alert(error);
            fieldObj.value = '';
            return false;
        }

    return true;
}

but here

multiple pdf files->success
single other files(.txt,.doc etc)->success
pdf+(txt or doc)-> fail

my need is only pdf files can accept when multiple selection.
and also it shows errors in files.length on Interner Explorer
how to do this

A: try this:

function checkFileUploadExt(fieldObj) {
  var control = document.getElementById("uploadFiles");
  var filelength = control.files.length;

  for (var i = 0; i < control.files.length; i++) {
    var file = control.files[i];
    var FileName = file.name;
    var FileExt = FileName.substr(FileName.lastIndexOf('.') + 1);
    if ((FileExt.toUpperCase() != "PDF")) {
      var error = "File type : " + FileExt + "\n\n";
      error += "Please make sure your file is in pdf  format .\n\n";
      console.error(error);
    }
  }
}
<input type="file" id="uploadFiles" multiple onchange="checkFileUploadExt(this);" />

A: Try using the accept filter instead.
Here's a demo:

<input name="file1" type="file" accept="application/pdf" multiple />

PS: It doesnt work in Firefox.

Alternate and Promising solution:

document.getElementById("uploadFiles").onchange = function(){  // on selecting file(s)
    for(var file in this.files){ // loop over all files
        if(isNaN(file) === false){  // if it is actually a file and not any other property
            if(this.files[file].type !== "application/pdf"){ // if NOT PDF!!
                alert('Please select PDF files only.');
                return false;
            }
        }
    }

    alert('Yay!! All selected files are in PDF format.');
    return true;
}
<input type="file" id="uploadFiles" multiple accept="application/pdf" />

PS: This works in Firefox too!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calendar in list but not in sidebar I loaded the My Meetups Calendar from meetup.com into my gmail account which I synchronize with Calendar.app. The My Meet up a calendar is in the calendars list in the menu, but not in the sidebar, and that means I have to specifically open a separate window to see the events on my meetups.
Illustration:
How can I fix thhis?

A: I solved this by going to Preferences (⌘+,) -> Accounts -> Google Account -> Delegation (tab) -> Click on My Meetups.
I can now see the meetups in the calendar :)
Warning: This is a viable solution only, of course, if you don't use the delegation feature -> If you do, you will give (unneccesary?) access to your Meet ups to your delegates, which may not be what you want.


text:
Q: Floating Label with Css not working in edge, internet explorer I made Floating Label input field using Css it is working properly with chrome, firefox but not working with internet explorer and edge.

All other browsers show input field same as shown in first image when not focused and like second image when focused.
Internet explorer and edge always show the input field like 2nd image.
Here is snippet of my code.

.has-float-label {
  display: block;
  position: relative;
}

.has-float-label label,
.has-float-label>span {
  color: grey;
  position: absolute;
  left: 0;
  top: 0;
  cursor: text;
  font-size: 120%;
  opacity: 1;
  -webkit-transition: all .3s;
  transition: all .3s;
}

.has-float-label select {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

.has-float-label textarea {
  width: 100%;
}

.has-float-label input,
.has-float-label select,
.has-float-label textarea {
  font-size: 15px;
  font-weight: normal !important;
  padding-top: 1.3em;
  margin-bottom: 2px;
  border: 0;
  height: 45px;
  border-radius: 0;
  border-bottom: 2px solid rgba(0, 0, 0, .1);
}

.has-float-label input::-webkit-input-placeholder,
.has-float-label select::-webkit-input-placeholder,
.has-float-label textarea::-webkit-input-placeholder {
  opacity: 1;
  -webkit-transition: all .2s;
  transition: all .2s;
}

.has-float-label input::-moz-placeholder,
.has-float-label select::-moz-placeholder,
.has-float-label textarea::-moz-placeholder {
  opacity: 1;
  transition: all .2s;
}

.has-float-label input:-ms-input-placeholder,
.has-float-label select:-ms-input-placeholder,
.has-float-label textarea:-ms-input-placeholder {
  opacity: 1;
  transition: all .2s;
}

.has-float-label input::placeholder,
.has-float-label select::placeholder,
.has-float-label textarea::placeholder {
  opacity: 1;
  -webkit-transition: all .2s;
  transition: all .2s;
}

.has-float-label input:placeholder-shown:not(:focus)::-webkit-input-placeholder,
.has-float-label select:placeholder-shown:not(:focus)::-webkit-input-placeholder,
.has-float-label textarea:placeholder-shown:not(:focus)::-webkit-input-placeholder {
  opacity: 0;
}

.has-float-label input:placeholder-shown:not(:focus)::-moz-placeholder,
.has-float-label select:placeholder-shown:not(:focus)::-moz-placeholder,
.has-float-label textarea:placeholder-shown:not(:focus)::-moz-placeholder {
  opacity: 0;
}

.has-float-label input:placeholder-shown:not(:focus):-ms-input-placeholder,
.has-float-label select:placeholder-shown:not(:focus):-ms-input-placeholder,
.has-float-label textarea:placeholder-shown:not(:focus):-ms-input-placeholder {
  opacity: 0;
}

.has-float-label input:placeholder-shown:not(:focus)::placeholder,
.has-float-label select:placeholder-shown:not(:focus)::placeholder,
.has-float-label textarea:placeholder-shown:not(:focus)::placeholder {
  opacity: 0;
}

.has-float-label input:placeholder-shown:not(:focus)+*,
.has-float-label select:placeholder-shown:not(:focus)+*,
.has-float-label textarea:placeholder-shown:not(:focus)+* {
  font-size: 140%;
  opacity: .5;
  top: 1.3em;
}

.has-float-label input:focus,
.has-float-label select:focus,
.has-float-label textarea:focus {
  outline: 0;
  border-color: #4285f4;
}

.has-float-label select {
  padding-right: 1em;
  background: url("data:image/svg+xml);
 charset=utf8, %3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23333' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .5em bottom .25em;
 background-size: 8px 10px;
}

      <input type = "text" id="first_name" name="fname" placeholder="Enter your First Name" required="required" autofocus="autofocus"/>
       FIRST NAME

          *

A: Here is my solution,
This Code is working fine and providing the same functionality as needed in all the browsers.
Add Required tag to the input field in html.
example :

  .has-float-label {
  display: block;
  position: relative;
}

.has-float-label label,
.has-float-label>span {
  color: grey;
  position: absolute;
  left: 0;
  top: 0;
  cursor: text;
  font-size: 120%;
  opacity: 1;
  -webkit-transition: all .3s;
  transition: all .3s;
}

.has-float-label select {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

.has-float-label textarea {
  width: 100%;
}

.has-float-label input,
.has-float-label select,
.has-float-label textarea {
  font-size: 15px;
  font-weight: normal !important;
  padding-top: 1.3em;
  margin-bottom: 2px;
  border: 0;
  height: 45px;
  border-radius: 0;
  border-bottom: 2px solid rgba(0, 0, 0, .1);
}

.has-float-label input::-webkit-input-placeholder,
.has-float-label select::-webkit-input-placeholder,
.has-float-label textarea::-webkit-input-placeholder {
  opacity: 1;
  -webkit-transition: all .2s;
  transition: all .2s;
}

.has-float-label input::-moz-placeholder,
.has-float-label select::-moz-placeholder,
.has-float-label textarea::-moz-placeholder {
  opacity: 1;
  transition: all .2s;
}

.has-float-label input:-ms-input-placeholder,
.has-float-label select:-ms-input-placeholder,
.has-float-label textarea:-ms-input-placeholder {
  opacity: 1;
  transition: all .2s;
}

.has-float-label input::placeholder,
.has-float-label select::placeholder,
.has-float-label textarea::placeholder {
  opacity: 1;
  -webkit-transition: all .2s;
  transition: all .2s;
}

.has-float-label input:invalid:not(:focus)::-webkit-input-placeholder,
.has-float-label select:invalid:not(:focus)::-webkit-input-placeholder,
.has-float-label textarea:invalid:not(:focus)::-webkit-input-placeholder {
  opacity: 0;
}

.has-float-label input:invalid:not(:focus)::-moz-placeholder,
.has-float-label select:invalid:not(:focus)::-moz-placeholder,
.has-float-label textarea:invalid:not(:focus)::-moz-placeholder {
  opacity: 0;
}

.has-float-label input:invalid:not(:focus):-ms-input-placeholder,
.has-float-label select:invalid:not(:focus):-ms-input-placeholder,
.has-float-label textarea:invalid:not(:focus):-ms-input-placeholder {
  opacity: 0;
}

.has-float-label input:invalid:not(:focus)::placeholder,
.has-float-label select:invalid:not(:focus)::placeholder,
.has-float-label textarea:invalid:not(:focus)::placeholder {
  opacity: 0;
}

.has-float-label input:invalid:not(:focus)+*,
.has-float-label select:invalid:not(:focus)+*,
.has-float-label textarea:invalid:not(:focus)+* {
  font-size: 140%;
  opacity: .5;
  top: 1.3em;
}

.has-float-label input:focus,
.has-float-label select:focus,
.has-float-label textarea:focus {
  outline: 0;
  border-color: #4285f4;
}

.has-float-label select {
  padding-right: 1em;
  background: url("data:image/svg+xml);
 charset=utf8, %3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23333' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .5em bottom .25em;
 background-size: 8px 10px;
}

       <input type = "text" id="first_name" name="fname" placeholder="Enter your First Name" autofocus="autofocus" required>
        FIRST NAME

         *

A: Adding required to your input allowed me to use the :invalid pseudo-element in place of :placeholder-shown. It didn't get everything working perfectly with the placeholder styles but now you should see the Label animation triggered in IE.
I'd say, update your code and see if you can narrow the problems down to smaller elements of the whole UI that you have here to see if anyone can fix one thing at a time.

.has-float-label {
  display: block;
  position: relative;
}

.has-float-label label,
.has-float-label>span {
  color: grey;
  position: absolute;
  left: 0;
  top: 0;
  cursor: text;
  font-size: 120%;
  opacity: 1;
  -webkit-transition: all .3s;
  transition: all .3s;
}

.has-float-label select {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

.has-float-label textarea {
  width: 100%;
}

.has-float-label input,
.has-float-label select,
.has-float-label textarea {
  font-size: 15px;
  font-weight: normal !important;
  padding-top: 1.3em;
  margin-bottom: 2px;
  border: 0;
  height: 45px;
  border-radius: 0;
  border-bottom: 2px solid rgba(0, 0, 0, .1);
}

.has-float-label input::-webkit-input-placeholder,
.has-float-label select::-webkit-input-placeholder,
.has-float-label textarea::-webkit-input-placeholder {
  opacity: 1;
  -webkit-transition: all .2s;
  transition: all .2s;
}

.has-float-label input::-moz-placeholder,
.has-float-label select::-moz-placeholder,
.has-float-label textarea::-moz-placeholder {
  opacity: 1;
  transition: all .2s;
}

.has-float-label input:-ms-input-placeholder,
.has-float-label select:-ms-input-placeholder,
.has-float-label textarea:-ms-input-placeholder {
  opacity: 1;
  transition: all .2s;
}

.has-float-label input::placeholder,
.has-float-label select::placeholder,
.has-float-label textarea::placeholder {
  opacity: 1;
  -webkit-transition: all .2s;
  transition: all .2s;
}

.has-float-label input:invalid:not(:focus)::-webkit-input-placeholder {
  opacity: 0;
}

.has-float-label input:invalid:not(:focus)::-moz-placeholder {
  opacity: 0;
}

.has-float-label input:focus:-ms-input-placeholder {
  opacity: 0;
}

.has-float-label input:invalid:not(:focus):-ms-input-placeholder {
  color:transparent;
}

.has-float-label input:placeholder-shown:not(:focus)::placeholder,
.has-float-label select:placeholder-shown:not(:focus)::placeholder,
.has-float-label textarea:placeholder-shown:not(:focus)::placeholder {
  opacity: 0;
}

.has-float-label input:invalid:not(:focus)+*,
.has-float-label select:invalid:not(:focus)+*,
.has-float-label textarea:invalid:not(:focus)+* {
  font-size: 140%;
  opacity: .5;
  top: 1.3em;
}

.has-float-label input:focus,
.has-float-label select:focus,
.has-float-label textarea:focus {
  outline: 0;
  border-color: #4285f4;
}

.has-float-label select {
  padding-right: 1em;
  background: url("data:image/svg+xml);
 charset=utf8, %3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23333' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .5em bottom .25em;
 background-size: 8px 10px;
}

      <input type = "text" id="first_name" name="fname" placeholder="Enter your First Name" required="required" autofocus="autofocus" required/>
       FIRST NAME

          *

A: For me, I am using Angular 7 and I found a fix that works for all browsers (but again is only in Angular as far as I know).  Essentially,  I had this code that worked fine in Chrome/Firefox:
input:not(:placeholder-shown) + span {
    color: blue;
    transform: translateY(-1.25rem) scale(0.75);
}

It created a floating blue label when a value in the input is entered/exists.   To get it to work in Edge, I replaced the code above and made a new scss class:
.entered-value + span {
    color: blue;
    transform: translateY(-1.25rem) scale(0.75);
}

and added an [Ngclass] on the input itself that creates that class when a value exists on the input (where the value of the input is modeled to the value variable in the angular component).
<input [ngClass]="{'entered-value': value}"
       [(ngModel)]="value"
...

Hope this helps someone.

A: Create Directive for placeholder selector and handle adding and removing class for floating label as below
 @Directive({
       selector:"[placeholder]"
    })
    export class PlaceHolderShownDirective
    implements
    DoCheck {
     constructor(private el:ElementRef, private renderer:Renderer2){

    }

    ngDoCheck():void {

    this.modify();
    }

    modify() {
element=this.el.nativeElement;
           const labelSibling = this.renderer.nextSibling(element);
            labelSibling.classList[element.value?"add":"remove"]("placeholder-shown");
            }

        }

/// CSS

label.placeholder-shown {
  font-size:12px;
  top: -12px;
  background: #04031d;
  padding:5px;
  margin: 0 0 0 8px;
  color: #fff;
}

.form-control:focus + label, .form-control:focus + label.placeholder-shown {
  font-size:12px;
  top: -12px;
  background: #04031d;
  padding:5px;
  margin: 0 0 0 8px;
  color: #fff;
}

For Firefox version <51 placeholder:shown support is not there so add directive based on below condition
 //AppModule ts

     const userAgent = window.navigator.userAgent;
        const isFireFox = /msie\s|trident\/|firefox\//i.test(userAgent);

        // Add directive based on condition
        declaration : [
        ...
        ...
        isFirefox ? PlaceHolderShownDirective : []
    ]

Css will be added based on input value and floating label will work in firefox version < 51 and ie browsers
/// HTML
<input placeholder=" " name="password" type="password" class="form-control"/>
Password


text:
Q: Not valid UTF8! byte A7 in state 0 I have a pdf printer which I don't know much about. The pdf that is generated has some images inside. The problem is that images that start with character '§' are not visible in the generated pdf because of this Exception:
2016-03-01 20:25:30.424 [qtp1181496842-69] WARN  org.eclipse.jetty.io.nio - handle failed
org.eclipse.jetty.util.Utf8Appendable$NotUtf8Exception: Not valid UTF8! byte A7 in state 0
    at org.eclipse.jetty.util.Utf8Appendable.appendByte(Utf8Appendable.java:178) ~[org.eclipse.jetty.util_8.1.16.v20140903.jar:8.1.16.v20140903]
    at org.eclipse.jetty.util.Utf8Appendable.append(Utf8Appendable.java:117) ~[org.eclipse.jetty.util_8.1.16.v20140903.jar:8.1.16.v20140903]
    at org.eclipse.jetty.http.HttpURI.toUtf8String(HttpURI.java:503) ~[na:na]
    at org.eclipse.jetty.http.HttpURI.getPathAndParam(HttpURI.java:687) ~[na:na]
    at org.eclipse.jetty.server.Request.getRequestURI(Request.java:1024) ~[na:na]
    at org.eclipse.jetty.server.Response.sendError(Response.java:364) ~[na:na]
    at org.eclipse.jetty.server.Response.sendError(Response.java:419) ~[na:na]
    at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:603) ~[na:na]
    at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:971) ~[na:na]
    at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1033) ~[na:na]
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:644) ~[na:na]
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235) ~[na:na]
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82) ~[na:na]
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696) ~[org.eclipse.jetty.io_8.1.16.v20140903.jar:8.1.16.v20140903]
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53) [org.eclipse.jetty.io_8.1.16.v20140903.jar:8.1.16.v20140903]
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608) [org.eclipse.jetty.util_8.1.16.v20140903.jar:8.1.16.v20140903]
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543) [org.eclipse.jetty.util_8.1.16.v20140903.jar:8.1.16.v20140903]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_65]

Any idea why this character causes this or how to fix this ?

A:
Jetty 8 is EOL (End of Life), please upgrade.

That stacktrace is telling you that in the process of reporting an error to the user, it encountered a bad RequestURI that included invalid UTF8 encodings in either the path or the query parameters.
The Request URI you are using is bad/invalid.
If you upgrade to Jetty 9, your error messages and stacktraces should become more clear as to the source of the issue well.


text:
Q: Data e Hora POSTGRESQL Olá, bom dia! Estou criando um relatório no fastreport para conseguir consultar o ticket médio de um restaurante, uma das informações que tenho que colocar nesse relatório é quanto tempo a mesa ficou aberta. Eu tenho duas tabelas na minha database, uma de dataHora que a mesa é aberta e uma de dataHora que ela é fechada, eu precisava saber se há uma função no SQL que eu possa pegar esse tempo que elas ficaram abertas, sendo mais específico eu gostaria de calcular a diferença de tempo entre as duas datas, sabe? Assim eu teria quanto tempo a mesa ficou aberta
Print da DataBase Como na imagem ao lado, a primeira mesa indicada ficou aberta apenas por 11 segundos, eu gostaria de saber se há alguma função disponível para me retornar que a mesa ficou aberta apenas 11 segundos entende? Eu pesquisei sobre isso e não achei nada relacionado e também não tenho ideia de como poderia fazer.
Eu já tentei pesquisar no próprio site do PostgreSQL e também no youtube, mas não encontrei nada relacionado, acredito que eu esteja procurando errado também.

A: Você pode utilizar a função AGE passando as duas colunas como parâmetro:
SELECT
    AGE(pve_dt_hr_fechamento_pedido, pve_dt_hr_emissao) as duracao
FROM ...


text:
Q: How do i remove default route in cakephp 3.0 I can do it easily with other framework. I'm also search google but just see how to solve it in cakephp 2.
I can access same action with these urls
ad/contact/edit/10
contact/edit-genre/10
i want to delete the first one which is default.
My router file
 Router::prefix('ad', function ($routes) {
    $routes->connect('/login', ['controller' => 'Users', 'action' => 'login']);
    $routes->connect('/contact/add-genre', ['controller' => 'Contact', 'action' => 'add']);
    $routes->connect('/contact/edit-genre/:id', ['controller' => 'Contact', 'action' => 'edit'],['id' => '\d+', 'pass' => ['id']]);
    $routes->fallbacks('InflectedRoute');
});

A: Remove this line
$routes->fallbacks('InflectedRoute');

After that you will need to connect the the rest of the routes yourself for that prefix.

A: Now in CakePHP 3.1, default fallbacks is DashedRoute
Then remove this line:
$routes->fallbacks('DashedRoute');

Assuming you have fully customised all of your other routes.


text:
Q: android app crashing while sending Message to a list of 50 people My android application crashes while sending Message to a list of 50 people.
Anyone knows why this is happening then please do let me know.
  public class SendSMS extends AsyncTask<Void, Void, Void>{

private ArrayList<SearchResults>  list;
private String message;

public SendSMS(ArrayList<SearchResults> obj,String msg){
    this.list=obj;
    this.message=msg;
}

@Override
protected Void doInBackground(Void...params) {
    // TODO Auto-generated method stub

    String sms=message;
    SmsManager smsManager = SmsManager.getDefault();
    ArrayList<String> parts = smsManager.divideMessage(sms);

     for (int i=0;i<list.size();i++){

        Log.d("ListPhoneNumbers....", list.get(i).getPhoneNumber());

        smsManager.sendMultipartTextMessage(list.get(i).getPhoneNumber(), null, parts, null, null);
    }
    Toast.makeText(getApplicationContext(), "SMS Sent!",
            Toast.LENGTH_LONG).show();

    return null;
}

     }

A: You should add some more details to the question. In particular:

LogCat
Piece of code involved

EDIT: try this
public class SendSMS extends AsyncTask < Void, Void, Void > {

    private ArrayList < SearchResults > list;
    private String message;
    private Object context;

    public SendSMS(ArrayList < SearchResults > obj, String msg, Object context) {
        this.list = obj;
        this.message = msg;
        this.context = context;
    }

    @Override
    protected void doInBackground(Void... params) {

        String sms = message;
        SmsManager smsManager = SmsManager.getDefault();
        ArrayList < String > parts = smsManager.divideMessage(sms);

        for (int i = 0; i < list.size(); i++) {

            Log.d("ListPhoneNumbers....", list.get(i).getPhoneNumber());

            smsManager.sendMultipartTextMessage(list.get(i).getPhoneNumber(), null, parts, null, null);
        }

    }

    @Override
    protected void onPostExecute(Void result) {
        Toast.makeText(this.context, "SMS Sent!",
            Toast.LENGTH_LONG).show();
    }

}

that you call from the main UI in this way:
(new SendSMS(/*PARAMS*/)).execute(this);

A: Your Toast message should be in runonui thread. You cant update the UI inside Async Task directly..


text:
Q: Python find sub string I have a very special work to do, here is my input
Period End Date         12/30/    12/31/   12/29/    12/28/    12/31/2007
                         2011      2010     2009      2008

You can see this is a wrong input file:

*

*year is on the second line

*but last date is correct

So I want to dig out the correct date:
12/31/2011 12/31/2012 12/31/2009 12/31/2008 12/31/2007
Here is what I am trying to do
 input_file = open("input", "r")
 for line in input_file:
   index = line.find("Period End Date", 0)
   if index != -1:
     line = line[index+len("Period End Date"):len(line)]
     temp_line = " ".join(line.split())
     temp_line.split(" ")

     year_line= input_file.next()
     #remove space, split,append on temp_line[i]

But it doesn't work:
temp_line.split(" ")

returns ['1','2','/', ...] not ['12/31/', '12/30', ...]
What's wrong with that?

A: Let's look at your code:
temp_line = " ".join(line.split())

This replaces multiple whitespace with one single space. So far, so okay. Next line:
temp_line.split(" ")

Now what? Splitting it again at single space? This only reverses the join you've done before. Why didn't you just stick with line.split(), then? Also, you're not assigning the result back to temp_line, so the result is discarded, which is probably the main issue here.
You could use something like that instead:
 with open("input", "rb") as f:
   lines = list(f)
   for date_line, year_line in zip(lines, lines[1:])[::2]:
     parts = date_line.strip().split()
     if ' '.join(parts[0:3]) != 'Period End Date': continue

     dates, years = parts[3:], year_line.strip().split()[1:]
     year_index = 0
     for date in dates:
       if not date.split('/')[-1]:
         date = date + years[year_index]
         year_index += 1
       print date

A: I am going to presume that the number of dates varies, but always consists of N day-month entries, followed by a complete day-month-year entry, followed by N year entries:
def getHeadings(s):
    head = s.split()
    num_dates = (len(head) - 4)/2
    return [dm+y for dm,y in zip(head[3:3+num_dates], head[4+num_dates:])] + head[3+num_dates:4+num_dates]

getHeadings("""    Period End Date 12/30/ 12/31/ 12/29/ 12/28/ 12/31/2007

                        2011      2010     2009      2008""")

returns
['12/30/2011', '12/31/2010', '12/29/2009', '12/28/2008', '12/31/2007']

A: it works
>>> temp_line = " ".join(line.split())
>>> temp_line
'12/30/ 12/31/ 12/29/ 12/28/ 12/31/2007'
>>> temp_line.split(" ")
['12/30/', '12/31/', '12/29/', '12/28/', '12/31/2007']

if you are iterating over each item in temp_line then you will get '1','2','/'... etc.
Also, may I suggest some pythonic adjustments to your code? use line.split('Period End Date ')[1].strip().split(" ") instead of
line = line[index+len("Period End Date"):len(line)]
temp_line = " ".join(line.split())
temp_line.split(" ")

Plus file is an iterator in python you can simply do -
with open(...) as f:
    for line in f:
        <do something with line>

The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered IO


text:
Q: How Meta classes works in python? Origin of question I'm recently working with django and became used to of Meta class in models, Serializers, and Forms.

My Understanding so far I learned that meta classes are used for creating classes.

When one class is defined, Python will go inside the class and collect all attributes and methods and store as dictionary, after that it searches for __metaclass__ attribute. If defined, it will use that class to create the defined class else it will use default object.
Object is default class which is inherited to all classes, and this object class must have __metaclass__ which is type by default.

type class have __new__ and __init__ methods which is used to create classes.

My question
What is the flow of creating a class when we declare Meta class inside definition of class
For example
class Transformer(models.Model):
    name = models.CharField(max_length=150, unique=True)

    class Meta:
        ordering = ('name',)

Where and When this Meta class is used?

Edit 1:
Cleared one thing that metaclasses and django Meta are different.
So Meta is just nested class of Transformer Model Class.

Question: Still my quesition is how this Meta class is used by Model Class?

A: As put in the comments: Python metaclasses are different from django metaclasses:  Django just, for historical reasons, use the same terminology for the inner class where one annotates extra parameters about a class, where the primary members of the outer class are meant to correspond to fields in a model or form.
A Python metaclass, on the other hand, are what you are describing in your example, though you have checked some Python 2 documentation. In current Python, the metaclass is determined by passing the keyword argument "metaclas=" in the declaration of a new class, where the base classes go:
class MyClass(Base1, Base2, metaclass=MyMeta):
   ...

As far as I know it, the Django behavior had origin in which early versions of Django actually used a custom (Python) metaclass to annotate some of the parameters now used in the nested Meta - and in doing so, it took a shortcut of defining the metaclass inline inside the class body: instead of assigning the __metaclass__ name to an externally defined metaclass, as the usual for normal use, it would just define the class inplace: from the point of view of the language runtime, it would find the name __metaclass__ bound to a valid metaclass and use that to build the class.
Later versions, even in Python 2, modified this approach - the inner class was no longer the actual "metaclass" of the Model or Form (as the previous approach was clearly overkill).

A: Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name_plural, and a lot of other options. It's completely optional to add a Meta class to your model.
example:
class Category (models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)

    def __str__(self):
    return self.name

    class Meta:
         verbose_name_plural= 'Categories'


text:
Q: it must be scrupulousess run mad The following quote is from "Mansfield Park" by Jane Austen:

Their mother had no objection to the plan, and they were not in the
least afraid of their father's disapprobation. There could be no harm
in what had been done in so many respectable families, and by so many
women of the first consideration; it must be scrupulousness run
mad, that could see anything to censure in a plan like theirs,
comprehending only brothers and sisters, intimate friends, and which
would never be heard of beyond themselves.

My question is: I wonder if there is an ellipsis of a relative pronoun in between "scrupulousness" and "run mad". This sentence will read:"It must be scrupulousness THAT has run mad. And another thing,
what does "that" refer back to?

A: You can understand it like that, but English does not require a relative pronoun in that position

It is chicken cooked perfectly.

The participle phrase "cooked perfectly" describes the chicken, just as "run mad" (which was one of Austen's favourite collocations) describes the "scrupulousness"
"Run mad", means "continued to an absurd degree".
The "that" which follows refers to "scrupulousness run mad", or by extension a person who practices scrupulousness to that degree.  But the style is "flighty" and rather 18th century, rather than how a modern person would speak or write.

A: A modern version of this is the phrase  "political correctness gone mad"
The idea is that the modern tendency of people to be politically correct or to advocate political correctness has become excessive almost to the point of insanity.

Note: I make no judgement on this. I am merely relating the meaning of the phrase.


text:
Q: Подгрузка данных по готовности Добрый день!
Есть сайт на php (стоит wordpress, но вопрос с ним вряд ли связан).
Я хочу осуществить загрузку данных из удаленного источника, через API и вывести данные на странице. Я реализовал получение данных на php, но проблема в том, что данные приходят частями в интервале от 2с до 2минут. Пробовал сделать проверку на готовность и выдать сразу все данные, но тогда приходится ждать загрузки страницы до тех пор пока не придут все данные.
В php я не силен, и не знаю, как сделать, чтобы загрузка страницы происходила при получении первых данных, а остальные бы догружались динамически, когда страница уже выдана пользователю.
Понимаю, что это скорее всего надо как-то делать через Ajax, но как можно их объединить, чтобы Ajax догружал то, что php не успел догрузить?
И возможно я не знаю, есть ли в Wordpress какие-то инструменты, чтобы работать не с собственной базой данной, а с данными поступающими через api?


text:
Q: Laravel route to same depth I have a site in a subfolder, example.com/mysite. I have a route there, login, which is accessed via example.com/mysite/login. This is the route:
Route::group(array('domain' => 'example.com'), function()
{

    Route::get('/', function()
    {
        return Redirect::to('login');
    });

    Route::get('/login/', array('as' => 'login', 'uses' => 'AccountController@login'));

})

The problem is, when I have a link in my view like so:
Login page

It displays the path example.com/login instead of example.com/mysite/login. It think this has something to do with  the domain group, but I don't know how to tell it to keep the current subdirectory. I've tried changing the domain to example.com/mysite in the group command, but that just causes an error. The redirection to login works, but how do I get the correct link in the view?

A: Turns out, this is because when it generates the route, it uses the domain provided in the group instead of getting it from the url. It can be overriden though, by specifying an empty domain in the individual route match, like so:
Route::get('/login/', array('as' => 'login', 'uses' => 'AccountController@login', 'domain' => ''));

This will allow it to ignore the domain specified in the group function. Unfortunately, from what I can tell, you need to do this for all of them.

A: Your routes do not follow a relative path. Even if you are in example.com/mysite, your route is made within the example.com domain.
Your redirect redirects you to example.com/login.
This is where your route is. Your redirect is redirecting to 'login'.
You named your route vendor_login. Therefore within the view, you have to write  to access your correct route.
Still, going to example.com/mysite/login will not show you your login page. It is available via example.com/login.
If you want to be available via example.com/mysite/login, use the following code.
Route::group(array('domain' => 'example.com'), function()
{

  Route::get('/', function()
  {
      return Redirect::route('vendor_login');
  });

  Route::group(array('prefix' => 'mysite'), function()
  {
    Route::get('/login/', array('as' => 'vendor_login', 'uses' => 'AccountController@login'));
  });

});

The difference here is that the login route is now placed within a group that uses the 'mysite' prefix. In this case, your login route is available via example.com/mysite/login.
The redirect is changed from Redirect::to('login') (which redirected to example.com/login, to Redirect::route('vendor_login') which redirects to the named route vendor_login, independent of its path.
EDIT:
Routes are absolute. If you want to make a link that is relative to the same depth, in your view just do Login. But this is not recommended. In that case you can not show the same view/link from routes with a different depth. Instead use named routes (as you did) which give you the most flexibility. Just put in your view the correct name vendor_login and change your Redirect::to to Redirect::route('vendor_login')
Hope this helps


text:
Q: email experience manager sitecore email bounce list report im using exm version 3.1, my csv has 12000 recepients but with only 2 email correct. I send the email, but in the exm report says the actual recepients is 12000 and my bounce list still empty. is it exm behavior or do i have to set something in sitecore?enter image description here

A: Work of bounce detection have list of thing that are not obvious when you try to use it.
What version of ExM do you use? If it is lower than 3.3 then you should use delivery via AppCenter for ability to detect bounce messages.
If you use ExM 3.3 then follow this article to setup receiving of delivery status notifications.


text:
Q: Function call on button added by eventContent in FullCalendar Calendar

I am integrating full Calendar in Angular. I have added different events in full Calendar. On each event I have added button inside event. Where ever I click on the event , event click of full Calendar gets called. I want to call a function when user click on the button inside event content. Can someone assist me how can I do that.
Below is my code of button inside event of a full Calendar.

A: If I really understand what you are asking for then ans is
event.stopPropagation();

Snippet example

function parent(event) {

console.log(alert("parent"))
}

function child(event) {

event.stopPropagation();

console.log(alert("child"))
}
.parent{
  width: 200px;
 height: 200px;
 background-color: red;
 margin :auto ;

}
.child {
  width:100px;
  height:100px;
  margin:auto;
  background-color: blue;
}

 child


text:
Q: Comparing a returned "value" with a string in python I have a python script which makes a Linked List of the input and then compares the characters to make sure that all opened brackets have close brackets in the right order.
Eg. (9-{5*2(1+1)}) == True
    (9-{5*2{1+1))) == False
My problem comes to when I'm comparing the return value of a function with a string. The if function just halts at the line 152. When I interrupt the script I get this error:
Traceback (most recent call last):
  File "lab2.py", line 195, in <module>
    bracketCheck(list)
  File "lab2.py", line 152, in bracketCheck
    if list.getNodeAtPosition(i) == '(' or list.getNodeAtPosition(i) == '{' or list.getNodeAtPosition(i) == '[':
      File "lab2.py", line 114, in getNodeAtPosition
    currentNode = currentNode.getNext()
KeyboardInterrupt

The Code of my script where the Linked List is heavily inspired by atraub from DreamInCode is below. Also, the inputs have to be entered one at a time until you type in "done":
import sys

stack = []
openbrackets = ['(','{','[']
closebrackets = [')','}',']']

class LinkedList:
    class Node:
        def __init__ (self, cargo=None):
            self.cargo = cargo
            self.next = None

        def __str__ (self):
            return str(self.cargo)

        def __len__ (self):
            return self.length

        def isEmpty (self):
            if length == 0:
                return True
            else:
                return False

        def getElement(self):
            print self.__str__()

        def getNext (self):
            return self.next

        def setElement(self, cargo):
            self.cargo = cargo

        def setNext(self, cargo):
            self.next = cargo

        def hasNext(self):
            return self.next != None

    def __init__(self):
        self.first = LinkedList.Node()
        self.length = 0

    def __len__ (self):
        return self.length

    def __add__(self, other):
        retList = LinkedList()
        for item in self:
            retList.append(item)
        for item in other:
            retList.append(item)

        return retList

    def getFirst(self):
        return self.first.getNext()

    def currentPoint(self):
        current = self.first.getNext()

    def setFirst(self, cargo):
        toAdd = LinkedList.Node(cargo)
        toAdd.setNext(self.first.getNext())
        self.first.setNext(toAdd)
        self.length += 1

    def removeFirst(self):
        if self.length > 0:
            value = self.first.getNext().getElement()
            self.first.setNext(self.first.getNext().getNext())
            self.length -= 1
            return value
        else:
            print "Error: List is empty"

    def addLast(self, cargo):
        current = self.first

        while current.hasNext():
            current = current.getNext()

        current.setNext(LinkedList.Node(cargo))
        self.length += 1

    def removeLast(self,index=None):
        if index ==None:
            index = self.length-1

        previous = self.getNodeAtPosition(self.checkIndex(index)-1)
            toRemove = previous.getNext()
            afterNext = None
            if toRemove.hasNext():
                    afterNext = toRemove.getNext()
            previous.setNext(afterNext)
            self.length-=1
            return toRemove.getElement()

    def getLast(self):
        current = self.first

        while current.hasNext():
            current = current.getNext()

        return current

    def moveNext(self):
        current = self.first

    def getNodeAtPosition(self, index):
        currentNode = self.first
        for i in range(index+1):
            currentNode = currentNode.getNext()
        return currentNode

    def __str__ (self):
        if self.length == 0:
            return '[]'

        retString = "["
        currentElement = self.first.getNext()

        for i in range(self.length):
            retString += str(currentElement) + ", "
            currentElement = currentElement.getNext()

        return retString[:-2] + ']'

    def checkIndex(self, index):
        if type(index) != int:
            raise TypeError("Index must be an integer or a slice not a")

        if index < 0:
            index += self.length

        if index >= self.length or index < 0:
            raise IndexError("Index out of bounds")

        return index

def bracketCheck(list):
    checkList = LinkedList()
    opencount=0
    closecount=0

    while(list.first.hasNext):
        isEqual = True
        i=0
        i=i+1
        if list.getNodeAtPosition(i) == '(' or list.getNodeAtPosition(i) == '{' or list.getNodeAtPosition(i) == '[':
            checkList.addLast(list.first.getNodeAtPosition(i))
            opencount = opencount + 1

        if list.getNodeAtPosition(i) == ')':
            closecount = closecount + 1

            if list.first.getLast() == openbrackets[0]:
                checkList.removeLast()
            else:
                isEqual = False

        if list.getNodeAtPosition(i) == '}':
            closecount = closecount + 1

            if list.first.getLast() == openbrackets[1]:
                checkList.removeLast()
            else:
                isEqual = False

        if list.getNodeAtPosition(i) == ']':
            closecount = closecount + 1

            if list.first.getLast() == openbrackets[2]:
                checkList.removeLast()
            else:
                isEqual = False
    '''print checkList'''
    print opencount
    print closecount
    if isEqual == False:
        print "an extra is missing."
    else:
        print "win!"

print "Enter list:"
list = LinkedList()
while input != "done":
    input = raw_input()
    if input == "done":
        break
    list.addLast(input)

print list
bracketCheck(list)

A: Why would while(list.first.hasNext) terminate?
There are some cases when you remove items from the list, some cases where you don't modify it. If you keep the list unchanged, it will loop forever.
And what's the thing with i=0; i=i+1?

A: brmap = dict(['()', '[]', '{}'])
closebr = set(brmap.values())

def check_brackets(expr):
    stack = []
    for c in expr:
        if c in brmap:
            stack.append(brmap[c])
        elif c in closebr and (not stack or stack.pop() != c):
            return False
    return not stack

A: There are so many logical errors in your code that I lost count..
The following modified code works well (based on my basic testing), please do a diff and try to see the errors in your original code:
def bracketCheck(myList):
    checkmyList = LinkedList()
    opencount=0
    closecount=0
    i=0
    isEqual = True
    while(i < myList.length):
        i=i+1
        if myList.getNodeAtPosition(i-1).cargo == '(' or myList.getNodeAtPosition(i-1).cargo == '{' or myList.getNodeAtPosition(i-1).cargo == '[':
            checkmyList.addLast(myList.getNodeAtPosition(i-1))
            opencount = opencount + 1
        if myList.getNodeAtPosition(i-1).cargo == ')':
            closecount = closecount + 1
            if checkmyList.getLast().__str__() == openbrackets[0]:
                checkmyList.removeLast()
            else:
                isEqual = False

        if myList.getNodeAtPosition(i-1).cargo == '}':
            closecount = closecount + 1
            if checkmyList.getLast().__str__() == openbrackets[1]:
                checkmyList.removeLast()
            else:
                isEqual = False

        if myList.getNodeAtPosition(i-1).cargo == ']':
            closecount = closecount + 1
            if checkmyList.getLast().__str__() == openbrackets[2]:
                checkmyList.removeLast()
            else:
                isEqual = False
    '''print checkmyList'''
    print opencount
    print closecount
    if isEqual == False:
        print "an extra is missing."
    else:
        print "win!"

print "Enter myList:"
myList = LinkedList()
while input != "done":
    input = raw_input()
    if input == "done":
        break
    myList.addLast(input)

print myList
bracketCheck(myList)

Please bare in mind the code above isn't pythonic or even "decent". It is barely here for you to see the logical flaws in your original code.
If you want a pythonic solution, please refer to @yak's answer.


text:
Q: How to parse Certificate Revocation List (CRL) in Node.js I am using the below code to read serial numbers of revoked crl from a crl list file with ext .crl downloaded.
import forge, { pki, asn1 } from 'node-forge';

const crlFil = asn1.fromDer(crlFile); // crlfile with a .crl extension

console.log(crlFileDer.value[0].value[5].value[0].value[0]);

I am following this guide,
but when I try to read the serial no. of revoked certificates, it gives me values that appear to be junk. I am not sure what format it is and want to convert it into the correct value.
Example value received \u0003-\tÊ$v¥L

A: You can parse a CRL and get revoked certificates serial numbers with help of asn1js, pkijs and pvutils libraries. Here is an example that prints revoked certificate serial numbers to console:
const asn1 = require('asn1js');
const pkijs = require('pkijs');
const pvutils = require('pvutils');
const fs = require('fs');

fs.readFile('./yourCrlFile.crl', (err, crlData) => {
  if (err) {
    throw err;
  }
  const buffer = new Uint8Array(crlData).buffer;
  const asn1crl = asn1.fromBER(buffer);
  const crl = new pkijs.CertificateRevocationList({
    schema: asn1crl.result
  })

  for (const { userCertificate } of crl.revokedCertificates) {
    console.log(pvutils.bufferToHexCodes(userCertificate.valueBlock.valueHex))
  }
})


text:
Q: Inversions count using Merge sort I am trying to implement the famous : Counting inversions using merge sort.
I wrote the code for the same. The code works well for small data. I had a few test cases using which I verified the answer. But the code takes an awful long time when the input is large (100000). So, I just want to make sure that the complexity of my code is O(N lgN) and not higher (being of higher complexity, it might be taking longer time).
Here is my code in Python:
    def merge_sort(u_list,inv):
    if(len(u_list) == 1): return 0
    if(len(u_list)>1):
        mid=len(u_list)//2
        l_list=u_list[:mid]
        r_list=u_list[mid:]
        a=merge_sort(l_list,inv)
        b=merge_sort(r_list,inv)
        count=0

        i=0
        j=0
        k=0
        track=0
        while i<len(l_list) and j<len(r_list) :
            if l_list[i]<=r_list[j]:
                u_list[k]=l_list[i]
                track+=1
                i+=1
                k+=1

            else: #r_list[j]<l_list[i]
                u_list[k]=r_list[j]
                inv=inv+(len(l_list)-track)
                j+=1
                k+=1

        while i<len(l_list) :
            u_list[k]=l_list[i]
            i+=1
            k+=1

        while j<len(r_list):
            u_list[k]=r_list[j]
            j+=1
            k+=1
        count=inv+a+b
        return count

inv=0
m=0
u_list=[]
x=0
for m in range(0,100000):
    x=int(input())
    u_list.append(x)

foo = merge_sort(u_list,inv)
print(foo)

A: I replaced
for m in range(0,100000):
    x=int(input())
    u_list.append(x)

with
from random import *
u_list = list(range(100000))
shuffle(u_list)

and ran the code and it took about a second, which seems normal. I think your merge sort is fine and something is going wrong on input. How are you passing input to the script? If you are streaming in some big text file is it possible the file isn't 100000 lines and the program just waits forever?

A: Since I was having the input data in a text file, I replaced :
x=0
for m in range(0,100000):
    x=int(input())
    u_list.append(x)

with this:
fileName = 'IntegerArray.txt'
u_list = []
with open(fileName) as f:
    for line in f:
        u_list.append(int(line))

And got the output in a second or so.


text:
Q: Response for FileUploader's uploadComplete-Event is undefined I'm developing a SAPUI5 app and use the FileUploader control in my app to upload documents to a server. The uploading works and I also receive a response from the server (I can see this in the DevTools of Chrome).The problem is that the event-object inside the 'uploadComplete' event-handler always returns undefined for the response parameter.
Do you know why this is the case and how I can fix it?
Here is the initialization of the FileUploader:
var oFileUploader = new sap.ui.unified.FileUploader({
    uploadUrl: "/fileupload",
    name: "documentUploader",
    uploadOnChange: false,
    multiple: false,
    width: "400px",
    uploadComplete: this.onDocumentUploadComplete
});

And here is the 'uploadComplete' event-handler:
onDocumentUploadComplete: function(oEvent) {
    var response = oEvent.getParameter("response");
    console.log(response);      // response = undefined
}

A: I still haven't figured out how to receive the server's response but I have found a workaround.After uploading the file I just send a request to the server and tell it to check whether the file exists.If it exists the server returns "true" and if it doesn't the server returns "false". Here's my code:
// eventhandler for the "uploadComplete"-event of the FileUploader-control
onDocumentUploadComplete: function(oEvent) {
    var uploaderControl = oEvent.getSource();
    var documentname = uploaderControl.getValue();

    var fileURI = "/file/" + documentname + "?exists";
    $.get(fileURI, function(data) {
        if (data === "true") {
            console.log("Successfully uploaded: " + documentname);
            this.handleDocumentUploadSuccess(documentname);
        } else {
            console.log("Error when uploading document: " + documentname);
            this.handleDocumentUploadError(documentname);
        }
    }.bind(this));
}

A: According to the documentation the parameter response is subject to some conditions.

Response message which comes from the server. On the server side this
  response has to be put within the "body" tags of the response document
  of the iFrame. It can consist of a return code and an optional
  message. This does not work in cross-domain scenarios.

That means the response fom the server must be XML or HTML.


text:
Q: How to best create and store APPLICATION variables? I am using ColdFusion 9.0.1
I am taking over a site and the guy before me created about 100 variables and put them into the APPLICATION scope. I believe that his 100 variables were continuously being overwritten with each page load.
Basically, he had this in Application.cfc:
APPLICTION.VariableOne = "SomeStringOne";
APPLICTION.VariableTwo = "SomeStringTwo";
APPLICTION.VariableThree = "SomeStringThree";

My plan is to keep it simple and yet very readable is to test for a specific structure in the application scope.  If it's not there, create the structure and variables:
if (not isDefined("APPLICTION.AppInfo") or not isStruct(APPLICTION.AppInfo)) {
    APPLICTION.AppInfo = structNew();
    APPLICTION.AppInfo.VariableOne = "SomeStringOne";
    APPLICTION.AppInfo.VariableTwo = "SomeStringTwo";
    APPLICTION.AppInfo.VariableThree = "SomeStringThree";
}

Of course, once the site is live and we are done creating all of the application variables, I'd move this into the into the onApplicationStart() method.
The solution that I want has to be more about "readability" and less about "efficiency".  Several non-CFers, but very experience coders will be using this and will need to "get it" quickly.
Does my plan have any gaping holes or is it too inefficient?
Is there a more readable way of creating and managing application variables?

A: Why not move the definition into onApplicationStart() right now?  If you need to reset them during development, you could always pass in a URL variable to flag it for reset, like so:
<!--- in Application.cfc --->

<cffunction name="onRequestStart">
<cfif IsDefined("url.resetApp")>
  <cfset ApplicationStop()>
  <cfabort><!--- or, if you like, <cflocation url="index.cfm"> --->
</cfif>
</cffunction>

A: I would go ahead and just use OnApplicationStart but back in the pre Application.cfc days we used to do something like Application.Build and if the Build value was different then we did all of our sets on Application variables.  So quick and dirty would be something like:
<cfparam name="Application.Build" default="" />

<cfset Build = "28-Nov-2011" />

<cfif Application.Build IS NOT Variables.Build OR StructKeyExists(URL, "Rebuild")>
 <cfset Application.Build = Variables.Build />
 <!--- A bunch of other CFSETs --->
</cfif>

This method though was something we used back when all we had was the Application.cfm

A: Actually, after re-reading the OP, and reading the suggested solutions, I'm going to have to agree with the OP on his setup, for this very important reason:
This, in onApplicationStart()
APPLICTION.AppInfo = structNew();
APPLICTION.AppInfo.VariableOne = "SomeStringOne";
APPLICTION.AppInfo.VariableTwo = "SomeStringTwo";

Can then later be turned into this, within onRequestStart()
<cflock name="tmp" type="readonly" timeout="15">
   <cfset REQUEST.AppInfo = APPLICATION.AppInfo />
</cflock>

Your app can then go on to access the REQUEST vars conveniently, esp, if you decide you want to cache CFCs in the same scope--they would simply go into a separate key:
   APPLICATION.Model.MyObject = CreateObject('component','myobject');

Which, of course, also gets poured into REQUEST (if you choose)
Want to go Jake Feasel's route above? No problem:
   <cfif isDefined('URL.reload')>
      <cfset APPLICATION.Model = StructNew() />
   </cfif>

Now you're able to flexibly kill your object cache but maintain your vars (or vice versa as you choose).
This is a great setup for another reason: If you want to build in your own Development/Production "mode", in which the development mode always recompiles the CFCs, but the production mode keeps them cached. The only change you have to make on top of this, is the REQUEST set noted above:
<cfif (isProduction)>
    <cflock name="tmp" type="readonly" timeout="15">
       <cfset REQUEST.AppInfo = APPLICATION.AppInfo />
    </cflock>
<cfelse>
   <cfset REQUEST.AppInfo = StructNew() />
   <cfset REQUEST.AppInfo.VariableOne = "SomeStringOne" />
   ...etc...
</cfif>

You can also make the setting of vars and the creation of objects into a private method within Application.cfc, for even further convenience.


text:
Q: Cannot update to Drupal 8.7.1 because of taxonomy_post_update_make_taxonomy_term_revisionable After running composer update drupal/core webflo/drupal-core-require-dev --with-dependencies to update to v8.7.1, and then running drush updb, the update fails here:
[notice] Update started: taxonomy_post_update_make_taxonomy_term_revisionable [4.77 sec, 33.46 MB]
[error]  Drupal\Core\Database\IntegrityConstraintViolationException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null: INSERT INTO {tmp_b3edd9taxonomy_term_field_data} (tid, revision_id, vid, langcode, name, description__value, description__format, weight, changed, default_langcode, status, revision_translation_affected) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11);
Array
(
   [:db_insert_placeholder_0] => 1
   [:db_insert_placeholder_1] => 1
   [:db_insert_placeholder_2] => tags
   [:db_insert_placeholder_3] => zxx
   [:db_insert_placeholder_4] =>
   [:db_insert_placeholder_5] =>
   [:db_insert_placeholder_6] =>
   [:db_insert_placeholder_7] =>
   [:db_insert_placeholder_8] =>
   [:db_insert_placeholder_9] =>
   [:db_insert_placeholder_10] =>
   [:db_insert_placeholder_11] => 1
)
in Drupal\Core\Database\Connection->handleQueryException() (line 689 of /mnt/www/html/optivode42/docroot/core/lib/Drupal/Core/Database/Connection.php). [7.12 sec, 45.21 MB]
[error]  The entity update process failed while processing the entity type taxonomy_term, ID: 1. [8.17 sec, 45.24 MB]
[error]  Update failed: taxonomy_post_update_make_taxonomy_term_revisionable [8.17 sec, 38.9 MB]

Other solutions suggested bad data in the taxonomy_term_field_data field, but that doesn't seem to be the problem here.
I checked taxonomy_term_field_data and there are no records where name is NULL, nor do I even have any records with langcode zxx, so I'm a bit at a loss now. Seems like there's nothing I can delete to fix this like in the other answers.
*Edit: I do have langcode zxx records in the taxonomy_term_data, so I deleted these records, and I get the same error, but with:
Array
(
   [:db_insert_placeholder_0] => 2
   [:db_insert_placeholder_1] => 2
   [:db_insert_placeholder_2] => tags
   [:db_insert_placeholder_3] => en
   [:db_insert_placeholder_4] =>
   [:db_insert_placeholder_5] =>
   [:db_insert_placeholder_6] =>
   [:db_insert_placeholder_7] =>
   [:db_insert_placeholder_8] =>
   [:db_insert_placeholder_9] =>
   [:db_insert_placeholder_10] =>
   [:db_insert_placeholder_11] => 1
)

A: I found that this is linked to a bug in the replicate-ui module which actually creates taxonomies without creating a real parent record in the taxonomy_index table.
Thus, I have opened up a bug report with the developer to fix this.
In the meantime, I actually upgraded to Drupal v8.6.16 since that has the security update that I needed, and I don't need to go all the way to v8.7 just yet.


text:
Q: How to assert a function is called from within another function? I have a component in React with an onChange event. In the code below, I need to assert that the correct method is called when
this.props.onChangeImage()

is invoked in the Gallery component.
export class Form extends React.PureComponent {

  componentDidMount = () => {
    this.props.getUser();
    this.props.getImages();
    this.props.getBoards();
  }

  render() {
    if (this.props.pin === null) {
      let boards = [];
      boards = this.props.boards;
      boards = boards.data.map(
        (item) => <MenuItem key={item.id.toString()} value={item.name} primaryText={item.name} />
      );
      return (

          <Helmet
            title="Form"
            meta={[
              { name: 'description', content: 'Description of Form' },
            ]}
          />
          <Gallery images={this.props.images} onChange={this.props.onChangeImage} />

      );
    }
    return (
<CircularProgress />
);
  }
}

Below, in the onChangeImage method, I am trying to assert that the sendEventToParentWindow method is called.
function mapDispatchToProps(dispatch) {
  return {

    onChangeImage: (event) => {
      dispatch(createPinImage(event.target.value));
      sendEventToParentWindow({
        action: 'change-image',
        description: 'Change image',
      });
    },
  };
}

function sendEventToParentWindow(message) {
  window.postMessage(message, window.location.href);
}

export default connect(mapStateToProps, mapDispatchToProps)(Form);

I've looked at a number of answers here, and while this one seemed closest, it's not quite getting me there: Jest - mocking a function call
EDIT: Here is my test which I believe is wrong because it's assigning the mocked function to be called directly onChange when it really should be calling the function that in turn calls the mock. I need somehow to invoke the onImageChange function and then verify that my spy was called.
import Gallery from '../index';
import * as formIndex from '../../../containers/Form';

describe('<Gallery />', () => {
  it('Expect sendMessageToParentWindow to be called on image change', () => {
    const sendEventToParentWindowMock = jest.spyOn(formIndex, 'sendEventToParentWindow');
    const gallery = shallow(<Gallery images={imagesMockData} onChange={sendEventToParentWindowMock} />);
    gallery.find('input#image-1').simulate('change');

    expect(sendEventToParentWindowMock).toBeCalled();
  });
}

A: As I mentioned in the comment, You can pass a mocked function as prop whose implementation will contain a call to your sendEventToParentWindow function. i.e. You'll need to create two mocked function.

*

*sendEventToParentWindow mock function.

*onChangeImage mock function with implementation, where implementation will only contain call to your sendEventToParentWindow mock function.

So the test will look something like this,
describe('<Gallery />', () => {
  it('Expect sendMessageToParentWindow to be called on image change', () => {
    const sendEventToParentWindowMock = jest.fn();
    const onChangeImageMock = jest.fn(() => {
         sendEventToParentWindowMock();
    });

    const gallery = shallow(<Gallery images={imagesMockData} onChange={onChangeImageMock} />); // Passing the mocked onChangeImage as prop
    gallery.find('input#image-1').simulate('change');

    expect(sendEventToParentWindowMock).toBeCalled();
  });
}

Hope it helps :)


text:
Q: How to update an array stored in the localStorage using hooks? So I have a component which when clicked must store the ID of a city in an array in localStorage. I am using a custom hook for this as mentioned below. The problem I am facing is whenever the component gets clicked it completely rewrites the value in the localStorage instead of pushing the new value.
import React, {useEffect, useState} from  'react';
import styled from 'styled-components';

const Container = styled.div`
   background-color: white;
   display: flex;
   position: relative;
   flex-direction: column;
   align-items: center;
   justify-content: center;
   width: 100%;
   cursor: pointer;
   padding: 2rem;
   margin-top: 2rem;
   transition: all 0.2s ease;
   border-radius: 5px;
   box-shadow: 0 .1rem 1rem 5px rgba(0,0,0,0.07);
   &:hover{
     box-shadow: 0 .1rem 1rem 5px rgba(0,0,0,0.16);
     transform: translateY(-3px);
   }
`;
  const SearchedCity = (props) => {
  const [storedId, setId] = useLocalStorage('ids', []);

  let handleId = () => {
     setId(prev => [...prev, props.cityId]);
  }

  return (
     <Container onClick={handleId}>
         {props.children}
     </Container>
  )
 }

 const useLocalStorage = (key, initialValue) => {
   const [storedId, setStoredValue] = useState(() => {
     try {
       const item = window.localStorage.getItem(key);
       return item ? JSON.parse(item) : initialValue;
     } catch (err) {
       console.error(err);
       return initialValue;
     }
   });

   const setValue = value => {
     try {
       const valueToStore =
       value instanceof Function ? value(storedId) : value;
       setStoredValue(valueToStore);
       window.localStorage.setItem(key, JSON.stringify(valueToStore));
     } catch (err) {
       console.error(err);
     }
   };

   return [storedId, setValue];
 };

 export default SearchedCity;

A: Before updating localStorage value you can do something like:

*

*Get localStorageValue. In your case it should contain stringified array.

*Parse it.

*Add your new value to the parsed array.

*Stringify an array and update your local storage.

const array = localStorage.get(yourKeyHere);
const parsedArray = array ? JSON.parse(array) : [];
const newArray = [...parsedArray, newItem];
localStorage.set(yourKeyHere, JSON.stringify(newArray));


text:
Q: how to backup and restore mysql database from remoteclient to server and vice versa using java? I have tried to backup and restore mysql database from localhost using like this command:
//for backup command :
String cmd ="C:\\DreamSoft\\DreamSoftSchoolSoftware\\src\\mysqlexe\\mysqldump.exe -uroot -proot  school -r "+path;

//for restore command:
String[] command = new String[]{"C:\\DreamSoft\\DreamSoftSchoolSoftware\\src\\mysqlexebut now

Now , I want to backup and restore totally from remote client to db server.
If my question don't have enough requirement please suggest me.
Thanks all


text:
Q: Executar select da classe DAO em java Pessoal estou com problemas para usar um select de uma classe dao em uma classe main.
Podem me ajudar.
Segue código.
package Model;

public class MTotalProduto {

    private String codigoBarra;
    private double totalProduto;
    private int produto_id;

    public MTotalProduto() {
    }

    public MTotalProduto(String codigoBarra, double totalProduto, int produto_id) {
        this.codigoBarra = codigoBarra;
        this.totalProduto = totalProduto;
        this.produto_id = produto_id;
    }

    public String getCodigoBarra() {
        return codigoBarra;
    }

    public void setCodigoBarra(String codigoBarra) {
        this.codigoBarra = codigoBarra;
    }

    public double getTotalProduto() {
        return totalProduto;
    }

    public void setTotalProduto(double totalProduto) {
        this.totalProduto = totalProduto;
    }

    public int getProduto_id() {
        return produto_id;
    }

    public void setProduto_id(int produto_id) {
        this.produto_id = produto_id;
    }

    @Override
    public String toString() {
        return "MTotalProduto{" + "codigoBarra=" + codigoBarra + ", totalProduto=" + totalProduto + ", produto_id=" + produto_id + '}';
    }

}

package DAO;

import Model.MTotalProduto;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DTotalProduto {

    private Connection con;

    public DTotalProduto(Connection con) {

        setCon(con);

    }

    public Connection getCon() {

        return con;

    }

    public void setCon(Connection con) {

        this.con = con;
    }

    public String salvar(MTotalProduto tot) {

        String sql = "insert into estoque.total_produto values(?,?,?)";

        try {

            PreparedStatement ps = getCon().prepareStatement(sql);
            ps.setString(1, tot.getCodigoBarra());
            ps.setDouble(2, tot.getTotalProduto());
            ps.setInt(3, tot.getProduto_id());

            if (ps.executeUpdate() > 0) {

                return "Total Salvo com sucesso!";

            } else {

                return "Erro ao Salvar Total de Produtos!";

            }

        } catch (SQLException e) {

            return e.getMessage();

        }

    }

    public String totProduto(MTotalProduto mt) {

        String sql = "SELECT total FROM estoque.total_produto "
                + "where produto_id=?";

        try {

            PreparedStatement ps = getCon().prepareStatement(sql);
            ps.setInt(1, mt.getProduto_id());
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {

                    MTotalProduto mtp = new MTotalProduto();
                    mtp.setTotalProduto(rs.getDouble("total"));
                    mtp.setProduto_id(rs.getInt("produto_id"));

            } else {

                return "Erro ao Carregar Total de Produtos!";

            }

        } catch (SQLException e) {

            return "Exeção ao carregar Total de Produtos!";

        }

        return "Total não carregado";

    }

}

package Principal;

import DAO.DConexao;
import DAO.DTotalProduto;
import Model.MTotalProduto;
import java.sql.Connection;

public class TotalProdutoMain {

    public static void main(String[] args) {

        Connection con = DConexao.abrirConexao();
        DTotalProduto dtp = new DTotalProduto(con);
        MTotalProduto tp = new MTotalProduto();

    }

}

A intenção é setar um produto_id e mostrar o valor total.
Agradeço pela ajuda.

A: Primeiramente, nomes de pacotes devem ter todas as letras em minúsculas e nomes de identificadores devem seguir o padrão camelCase. Veja mais aqui sobre as convenções. Além disso, os nomes das classes devem ser descritivos, e portanto é bom evitar abreviações obscuras, como no caso dos seus prefixos M e D. Chame suas classes de Conexao, de TotalProduto e de TotalProdutoDAO e use produtoId ao invés de produto_id.
Em seguida, classes imutáveis são bem mais fáceis de se utilizar, de se reutilizar, de se testar e são muito menos propensas a causar bugs inesperados. Assim sendo, sugiro que a classe TotalProduto seja imutável. Prefira fazer classes imutáveis quando possível e só introduza a mutabilidade quando houver uma razão boa e forte para tal. Sua classe TotalProduto fica assim:
package model;

public final class TotalProduto {

    private final String codigoBarra;
    private final double totalProduto;
    private final int produtoId;

    public TotalProduto(String codigoBarra, double totalProduto, int produtoId) {
        this.codigoBarra = codigoBarra;
        this.totalProduto = totalProduto;
        this.produtoId = produtoId;
    }

    public String getCodigoBarra() {
        return codigoBarra;
    }

    public double getTotalProduto() {
        return totalProduto;
    }

    public int getProdutoId() {
        return produtoId;
    }

    @Override
    public String toString() {
        return "TotalProduto{" +
                "codigoBarra=" + codigoBarra +
                ", totalProduto=" + totalProduto +
                ", produtoId=" + produtoId + '}';
    }
}

O retorno de um método deve servir para informar o resultado esperado. No seu método totProduto (que deveria se chamar totalProduto), o retorno deveria informar o total do produto. Entretanto, nos seus métodos, você usurpou o return para mostrar mensagens de erro ou de sucesso.
Imagine, por exemplo que eu quisesse fazer uma função que soma dois números:
 public String somar(int a, int b) {
     int r = a + b;
     return "Somado com sucesso.";
 }

Agora, imagine que eu vá usar esse método para fazer somar(16, 28). A resposta que eu gostaria de ter é 44, mas ao invés disso, eu tenho como resultado uma string praticamente inútil. Para resolver esse tipo de coisa, basta eu abolir essa prática de retornar strings com códigos ou mensagens de status:
 public int somar(int a, int b) {
     return a + b;
 }

Quanto aos casos onde ocorre um exceção, o que você deve fazer é simplesmente lançar essas exceções. As exceções foram inventadas exatamente para sinalizar condições de erros. Assim sendo, ao retornar strings com mensagens de erro, você está subvertendo o mecanismo de tratamento de exceções que já existe e que foi inventado justamente para livrar o programador de ter que usurpar o retorno das funções/métodos com códigos e/ou mensagens de erro.
Seu código deveria utilizar o try-with-resources. Sugiro a você ler todo o conteúdo desta pergunta para entender o porquê. Veja também que essa pergunta mostra muito de como você deveria lidar para construir o seu DAO.
Ah, e lembre-se de sempre utilizar o Connection, o PreparedStatement e o ResultSet com o try-with-resources.
Seu código do TotalProdutoDAO deve ficar assim:
package dao;

import model.TotalProduto;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TotalProdutoDAO {

    private static final String INSERT_SQL =
            "INSERT INTO estoque.total_produto VALUES (?, ?, ?)";

    private static final String SELECT_SQL =
            "SELECT total FROM estoque.total_produto WHERE produto_id = ?";

    private final Connection con;

    public TotalProdutoDAO(Connection con) {
        this.con = con;
    }

    public void salvar(TotalProduto tot) throws SQLException {
        try (PreparedStatement ps = con.prepareStatement(INSERT_SQL)) {
            ps.setString(1, tot.getCodigoBarra());
            ps.setDouble(2, tot.getTotalProduto());
            ps.setInt(3, tot.getProdutoId());

            if (ps.executeUpdate() == 0) {
                throw new SQLException("Nenhum resultado foi produzido.");
            }
        }
    }

    public double totalProduto(int idProduto) throws SQLException {
        try (PreparedStatement ps = con.prepareStatement(SELECT_SQL)) {
            ps.setInt(1, idProduto);
            try (ResultSet rs = ps.executeQuery()) {
                if (!rs.next()) {
                    throw new SQLException("Nenhum resultado foi produzido.");
                }
                return rs.getDouble("total");
            }
        }
    }
}

Observe que o método totalProduto não trabalha com o objeto TotalProduto porque ele só lida com os campos idProduto e total, deixando o codigoBarra de lado. Se você vai usar uma classe que modela uma tabela do banco de dados, é boa ideia ou utilizar todos os seus campos ou simplesmente não utilizá-la. Qualquer meio-termo provavelmente é uma má prática de programação. Aqui no caso, esse método só traz um double como resultado a partir de um int.
Se a sua ideia era trazer instâncias de MTotalProduto, então faça esse método assim (modificando também a instrução SQL):
    private static final String SELECT_SQL =
            "SELECT total, codigo_barra FROM estoque.total_produto WHERE produto_id = ?";

    public TotalProduto buscar(int idProduto) throws SQLException {
        try (PreparedStatement ps = con.prepareStatement(SELECT_SQL)) {
            ps.setInt(1, idProduto);
            try (ResultSet rs = ps.executeQuery()) {
                if (!rs.next()) {
                    throw new SQLException("Nenhum resultado foi produzido.");
                }
                double total = rs.getDouble("total");
                String codigoBarra = rs.getDouble("codigo_barra");
                return new TotalProduto(codigoBarra, total, idProduto);
            }
        }
    }

Sua classe principal está muito pouco desenvolvida e não há contexto suficiente na sua pergunta para saber o que ela viraria. No entanto, aqui vai um exemplo de alguma coisa:
package principal;

import dao.Conexao;
import dao.TotalProdutoDAO;
import model.TotalProduto;
import java.sql.Connection;
import java.sql.SQLException;

public class TotalProdutoMain {

    public static void main(String[] args) throws SQLException {
        // Lê o id do produto desejado.
        int produtoId = Integer.parseInt(args[0]);

        // Cria e usa o DAO.
        double total;
        try (Connection con = Conexao.abrirConexao()) {
            TotalProdutoDao dao = new TotalProdutoDAO(con);
            total = dao.totalProduto(produtoId);
        }

        // Mostra o resultado.
        System.out.println(total);
    }
}

Observe que tive que colocar o gerenciamento da conexão no main. Isso não é bom, mas sem saber mais sobre o contexto onde o TotalProdutoDAO será usado e nem saber o que existe no código de sua classe DConexao, é o que dá para fazer por enquanto. Também não há contexto o suficiente para saber qual seria a melhor forma de tratar a SQLException, mas seja lá qual for, definitivamente não era do jeito que você estava fazendo.

A: Consegui resolver o problema. Segue o código.
package Model;

public class MTotalProduto {

    private String codigoBarra;
    private double totalProduto;
    private int produtoId;

    public MTotalProduto() {
    }

    public MTotalProduto(String codigoBarra, double totalProduto, int produtoId) {
        this.codigoBarra = codigoBarra;
        this.totalProduto = totalProduto;
        this.produtoId = produtoId;
    }

    public String getCodigoBarra() {
        return codigoBarra;
    }

    public void setCodigoBarra(String codigoBarra) {
        this.codigoBarra = codigoBarra;
    }

    public double getTotalProduto() {
        return totalProduto;
    }

    public void setTotalProduto(double totalProduto) {
        this.totalProduto = totalProduto;
    }

    public int getProdutoId() {
        return produtoId;
    }

    public void setProdutoId(int produtoId) {
        this.produtoId = produtoId;
    }

    @Override
    public String toString() {
        return "MTotalProduto{" + "codigoBarra=" + codigoBarra + ", totalProduto=" + totalProduto + ", produtoId=" + produtoId + '}';
    }

}

package DAO;

import Model.MTotalProduto;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DTotalProduto {

    private Connection con;

    public DTotalProduto(Connection con) {

        setCon(con);

    }

    public Connection getCon() {

        return con;

    }

    public void setCon(Connection con) {

        this.con = con;
    }

    public String salvar(MTotalProduto tot) {

        String sql = "insert into estoque.total_produto values(?,?,?)";

        try {

            PreparedStatement ps = getCon().prepareStatement(sql);
            ps.setString(1, tot.getCodigoBarra());
            ps.setDouble(2, tot.getTotalProduto());
            ps.setInt(3, tot.getProdutoId());

            if (ps.executeUpdate() > 0) {

                return "Total Salvo com sucesso!";

            } else {

                return "Erro ao Salvar Total de Produtos!";

            }

        } catch (SQLException e) {

            return e.getMessage();

        }

    }

    public void totalProduto(MTotalProduto tp) {

        ResultSet rs = null;

        try {

            PreparedStatement ps = getCon().prepareStatement("SELECT total FROM estoque.total_produto where produto_id = ?");

            ps.setInt(1, tp.getProdutoId());
            rs = ps.executeQuery();

            while (rs.next()) {

                tp.setTotalProduto(rs.getDouble("total"));

            }

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

package Principal;

import DAO.DConexao;
import DAO.DTotalProduto;
import Model.MTotalProduto;
import java.sql.Connection;

public class TotalProdutoMain {

    public static void main(String[] args) {

        Connection con = DConexao.abrirConexao();
        MTotalProduto tp = new MTotalProduto();
        DTotalProduto dtp = new DTotalProduto(con);

       tp.setProdutoId(1);
       dtp.totalProduto(tp);
       tp.setTotalProduto(tp.getTotalProduto() + 1);

        System.out.println(tp);

    }

}


text:
Q: How to arrange field name and the fielt itself properly? Code:
 #inputfield {
 width:300px;
 border: 2px solid #3f3f3f;
 height:30px;
 font-size:20px;
 padding-left:5px;
 color: #6f6f6f;
 }
 #inputname {
 margin-right:10px;
 font-size:20px;
 color: #3f3f3f;
 }

 Name:<input name="name" id="inputfield" type="text">
 Other Name:<input name="other" id="inputfield" type="text">
 Other Other Name:<input name="other_2"
 id="inputfield" type="text">

The names and the fields look out of place.  I am trying to make the form organized like the way it looks on this page:
  https://secure.hulu.com/signup

A: Things to change:

*

*Don't use id. Use class and .inputfield

*Make sure to set the display to inline-block so that the browser will honor the width

*You don't want  tags. You want  tags.

*Wrap each line of your form in its own
 and use that to set the line height and spacing.


text:
Q: Linking boost library with Boost_USE_STATIC_LIB OFF on Windows My CMakeFiles.txt looks like this:
cmake_minimum_required ( VERSION 2.6 )

# Set warnings on and enable debugging
SET( CMAKE_C_FLAGS "-Wall -q" )

include(FindBoost)

set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)

find_package( Boost 1.57.0 COMPONENTS system filesystem REQUIRED )

if( Boost_FOUND )
    message( STATUS "Boost found!" )
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(foo main.cpp)

    # Needed for asio
    if(WIN32)
      target_link_libraries(foo wsock32 ws2_32)
    endif()

    target_link_libraries(foo ${Boost_LIBRARIES})
endif()

I render the project for Visual Studio 2013 64-bit:
cmake -G "Visual Studio 12 Win64" -DBOOST_LIBRARYDIR=D:\Development\Tools\boost_1_57_0\stage\x64\lib ..\KServer

The output is:
-- The C compiler identification is MSVC 18.0.31101.0
-- The CXX compiler identification is MSVC 18.0.31101.0
-- Check for working C compiler using: Visual Studio 12 2013 Win64
-- Check for working C compiler using: Visual Studio 12 2013 Win64 -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler using: Visual Studio 12 2013 Win64
-- Check for working CXX compiler using: Visual Studio 12 2013 Win64 -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Boost version: 1.57.0
-- Boost version: 1.57.0
-- Found the following Boost libraries:
--   system
--   filesystem
-- Boost found!
-- Configuring done
-- Generating done
-- Build files have been written to: D:/Development/Private/C++/KServerProject

This is all good and well.
Problem starts here:
When I change my cmake file to use:
set(Boost_USE_STATIC_LIBS OFF)

I then get the following error in Visual Studio when building:
error LNK1104: cannot open file 'libboost_filesystem-vc120-mt-gd-1_57.lib'  D:\Development\Private\C++\KServerProject\src\LINK  foo

Checking the Property Pages in the studio the library is added as a dependency:

When manually adding the folder D:\Development\Tools\boost_1_57_0\stage\x64\lib to Additional Library Directories it builds fine.
How can I get it to create project using dynamic libs?

A: I believe you need to add
add_definitions( -DBOOST_ALL_NO_LIB )

See http://www.boost.org/doc/libs/1_57_0/libs/config/doc/html/index.html. I have it set in my CMakeLists.txt and it works for my visual studio builds with boost. As a test, I removed it and got the same error you did.
For what it is worth, here is how I use boost with cmake.
# boost
set(Boost_NO_SYSTEM_PATHS true)
set (Boost_USE_STATIC_LIBS OFF CACHE BOOL "use static libraries from Boost")
set (Boost_USE_MULTITHREADED ON)
find_package(Boost REQUIRED
  COMPONENTS
  system program_options thread filesystem
  date_time chrono timer regex serialization
  )
include_directories(${Boost_INCLUDE_DIRS})
link_libraries(${Boost_LIBRARIES})

if (WIN32)
  # disable autolinking in boost
  add_definitions( -DBOOST_ALL_NO_LIB )

  # force all boost libraries to dynamic link (we already disabled
  # autolinking, so I don't know why we need this, but we do!)
  add_definitions( -DBOOST_ALL_DYN_LINK )
endif()


text:
Q: Is it possible to open a file from a network path in actionscript? I need to open media files from a network path like this "\\drive\folder\file", is it possible, if yes how? else is there any other alternative?
Thanks

A: As long as the path is not a path belonging to the user's computer or their network you shouldn't have a problem. If the path is on the server or a drive networked to the server, then passing it directly as a path to flash isn't going to work because the path is within the server domain and the flash instance is operating within the users domain. You can always convert local paths to relative paths in a server side script or, grab the binary contents of the file and serve then up to flash through a service (if the original target file is not directly accessible to the end-user via a network request).


text:
Q: Blog search by tag will never complete? I went to the blog and clicked on one of the tags.  "Legal" to be precise.  It redirected me to this url:

https://blog.stackoverflow.com/categoryhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttp://stackoverflow.comhttps://stackoverflow.com/legal/

That's a mouthful.  Anyway, Firefox had this to say about it:

The page isn't redirecting
properly
Firefox has detected that the server
is redirecting the request for this
address in a way that will never
complete.
*This problem can sometimes be caused by disabling or refusing to accept
cookies.

I'm pretty sure I have cookies enabled....

A: This is now fixed, it was a problem with the redirect add-in.


text:
Q: TypeScript Partial of Union complains about assigning a unioned value I am trying to create TypeScript interfaces for a query object.
interface Comparison {
    op: '=' | '>' | '<';
    field: string;
    value: any;
}

interface Conjunction {
    op: 'and' | 'or';
    queries: Array<Comparison>;
}

type Query = Comparison | Conjunction;

So the query can either be simple (Comparison) like
{
    "op": "=",
    "field": "score",
    "value": 5
}

or more complex (Conjunction) like
{
    "op": "and",
    "queries": [
        {
            "op": ">",
            "field": "score",
            "value": 1
        },
        {
            "op": "<",
            "field": "score",
            "value": 10
        }
    ]
}

I'm ultimately mapping some input filter object into my query object.
// One possible input for a simple comparison filter
// const inputFilter = {
//     field: 'someField',
//     type: 'eq',
//     value: 'someValue'
// };

// An input for a more complex filter
const inputFilter = {
    field: 'someField',
    type: 'range',
    value: 5,
    valueEnd: 10
};

const query: Partial<Query> = {
    field: inputFilter.field
};

switch (inputFilter.type) {
    case 'eq':
        query.op = '=';
        query.value = inputFilter.value;
        break;
    case 'range':
        query.op = 'and'; // ERROR: Type '"and"' is not assignable to type '"=" | ">" | "<" | undefined'
        query.queries = [
            { field: inputFilter.field, op: '>', value: inputFilter.value },
            { field: inputFilter.field, op: '<', value: inputFilter.valueEnd }
        ]; // ERROR: Property 'queries' does not exist on type 'Partial<Comparison>'
        break;
    // ...other cases / default...
}

I get two errors. The first is when I try to set query.op to 'and'

Type '"and"' is not assignable to type '"=" | ">" | "<" | undefined'

The second is when I type to set query.queries

Property 'queries' does not exist on type 'Partial<Comparison>'

Here is a TypeScript Playground to see it in action.
Am I misunderstanding what Partial<Query> is doing? I was hoping it meant that I can have a partial comparison or partial conjunction object.
For the record, using Partial<Comparison> | Partial<Conjunction> doesn't work either.

A: Conjunction objects don't have a field attribute
interface Conjunction {
    op: 'and' | 'or';
    queries: Comparison[];
}

const query: Partial<Query> = {
    field: inputFilter.field
};

which means your query will always be of type Comparison.


text:
Q: Getting the mean of a variable depending on other column in a pandas dataframe Basically what its on the title, I have a csv that I converted into a pandas dataframe that its something like this:
"ID","Name","Sex","Age","Height","Weight","Team","NOC","Games","Year","Season","City","Sport","Event","Medal"
"1","A Dijiang","M",24,180,80,"China","CHN","1992 Summer",1992,"Summer","Barcelona","Basketball","Basketball Men's Basketball",NA
"2","A Lamusi","M",23,170,60,"China","CHN","2012 Summer",2012,"Summer","London","Judo","Judo Men's Extra-Lightweight",NA
"3","Gunnar Nielsen Aaby","M",24,NA,NA,"Denmark","DEN","1920 Summer",1920,"Summer","Antwerpen","Football","Football Men's Football",NA
"4","Edgar Lindenau Aabye","M",34,NA,NA,"Denmark/Sweden","DEN","1900 Summer",1900,"Summer","Paris","Tug-Of-War","Tug-Of-War Men's Tug-Of-War","Gold"
"5","Christine Jacoba Aaftink","F",21,185,82,"Netherlands","NED","1988 Winter",1988,"Winter","Calgary","Speed Skating","Speed Skating Women's 500 metres",NA

I would like to obtain the mean of 'Height' based on the Years like having the mean of the year 1992 and so on

A: This is what you want!!
df.groupby('Year')['Height'].mean()

How does it work? Initially, we group by a particular column (it's also possible to group by a set of columns). Then, we need to tell the column that we need to be group, in our case "height" followed by the criteria, here "mean".
Another syntax is as follows:
import numpy as np #Since there's no mean function in python
df.groupby('Year')['Height'].agg(np.mean)

A: try this:
df = pd.read_csv("filename.csv")
mean_height = df[df["Year"]==1992]["height"].mean()


text:
Q: SCCM collection evaluates major version numbers in unexpected way Why do SCCM collections based upon the logic Installed Applications (64).Version is less than "100.0" not evaluate to true for applications of version 99.* and below?
The full WQL query statement is as follows, (linebreaks for legibility)
select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client
from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS_64 on SMS_G_System_ADD_REMOVE_PROGRAMS_64.ResourceID = SMS_R_System.ResourceId
where SMS_G_System_ADD_REMOVE_PROGRAMS_64.DisplayName
like "Mozilla Firefox%" and SMS_G_System_ADD_REMOVE_PROGRAMS_64.Version < "100.0"

Mozilla Firefox recently went from version 99.* to version 100.0, and this has caused  collections to stop evaluating lower versions as "less than" 100.0; there are  stopgaps in place to get around this, but would prefer to better understand why it is occurring and how to remediate it properly.


text:
Q: What is the correct term/expression for libraries' acquisition of books etc, as determined by the users? When libraries' decide what books etc they are to add to their collections, they look at, among other things, what people want to borrow, right? Now I'm wondering what the correct nominalisation for this is in English – I've thought about "user-determined acquisition", "user-controlled acquisition", and "user-dictated acquisition", but none of them generate any useful hits on Google. So, is there anyone who knows the established term/phrase here?
Thank you!


text:
Q: How to configure sslContext with p12 store (and password) for client authentication with https endpoint in Spring/Kotlin I want to call a https protected endpoint using a certificate and private key. I received a .p12 keystore which is protected with a password.
For testing purposes I extracted the .cer file and private key using openssl.
I could verify locally that communication works by setting the ssl context like this:
fun test(): WebClient.RequestHeadersSpec<*> {

    val sslContext = SslContextBuilder
            .forClient()
            .keyManager(ClassPathResource("cert").inputStream, ClassPathResource("key").inputStream)
            .build()

    val httpClient: HttpClient = HttpClient.create().secure { sslSpec -> sslSpec.sslContext(sslContext) }

    val webClient = WebClient
            .builder()
            .baseUrl("baseUrl")
            .clientConnector(ReactorClientHttpConnector(httpClient))
            .build()

    return webClient
            .post()
            .uri("uri")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue("test")
}

However, I do not want to version the cert and private key in my repository. How would I set the sslContext with the .p12 keystore and the password? I did not find any examples for this scenario.

A: load file from disc
this is java but it should be easy to adapt to kotlin
KeyStore keyStore = KeyStore.getInstance("pkcs12");
keyStore.load(new FileInputStream(keyStoreLocation), keyStorePassword.toCharArray());

SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
        new SSLContextBuilder()
                .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
                .build(),
        NoopHostnameVerifier.INSTANCE);

HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

where file location and password can provided from configuration
@Value("${keyStore.location}")
private String keyStoreLocation;

@Value("${keyStore.password}")
private String keyStorePassword;


text:
Q: tkinter image button not working inside a function Here is the code:
img_b64 = """R0lGODlhGAAYAPEAADIyMjMzMzQ0NAAAACH5BAEAAAMALAAAAAAYABgAAAJOnI8Ciu0I4gKvtmXzidoKBXbQBE5iVJZYJpGkQlluisYVnYbVgk/+XcOBBMAebWecFWfMR1Lo+DCNjuD0JcpqZUPmFSbjrbYDGJF8YGQKADs="""
img = PhotoImage(data = img_b64)
close_button = Button(root, image=img, command=root.quit)
close_button.pack(side=LEFT)
root.mainloop()

# def poptk(root):
#     img_b64 = """R0lGODlhGAAYAPEAADIyMjMzMzQ0NAAAACH5BAEAAAMALAAAAAAYABgAAAJOnI8Ciu0I4gKvtmXzidoKBXbQBE5iVJZYJpGkQlluisYVnYbVgk/+XcOBBMAebWecFWfMR1Lo+DCNjuD0JcpqZUPmFSbjrbYDGJF8YGQKADs="""
#     img = PhotoImage(data = img_b64)
#     close_button = Button(root, image=img, command=root.quit)
#     close_button.pack(side=LEFT)
# poptk(root)
# root.mainloop()

The first part is the working code, but once I refactor it into a function, the image then can't be displayed, and clicking has no effect.
Screenshots:


text:
Q: How do I change the error traceback syntax highlighting colours in Jupyter Notebook in VS Code? I am familiar with how to change the workbench, editor and syntax colours in VS Code.  However, I am not sure if it is possible to specifically amend the traceback error colours directly.  If it is, what settings need to be amended?
Here is an example error traceback output that I would like to change the colour settings for:

Speifically, changing the "ZeroDivisionError", "<module()>" and "<ipython-input-7-0f9f90da76dc>" colours just within the traceback output is what I am looking to achieve.  Thanks!


text:
Q: Calc 2: convergent of divergent sequences I would like to know if this sequence, $\sin\left(\frac{n \pi}{2}\right)$ ,is convergent or divergent?
I have done this problem and I know that it is divergent through oscillation (I'm pretty sure). Is there a mathematical way to prove this? If so can you please show me. Thank you

A: If a sequence is convergent, then its limit is unique, and every subsequence converges to that limit.
Can you find two subsequences of your sequence that have a different limit?

A: Let $k$ be an integer, $|\sin((2k)\pi/2) - \sin((2k + 1)\pi/2)| = 1$. Thus when $\epsilon = 1$, for all $N$ we can find elements in the sequence which differ by $\epsilon$. Let $k = N$. This contradicts the definition of convergence.

A: In the field of real analysis, you can show that every convergent sequence $\left\{a_n\right\}_n$ is what we call a Cauchy sequence: that is, for every $\epsilon > 0$, we can find an integer $N$ so that for all pairs of integers $m,n > N$,
$$|a_m - a_n| < \epsilon.$$
(In fact, every Cauchy sequence also converges, but we won't need this information to show that your sequence diverges.)
To see this from a more intuitive angle, imagine your favorite convergent sequence.  Let's call it $\left\{a_n\right\}_n$, and let's say it converges to some number we'll call $A$.  Then, when $n$ is really big, $a_n \approx A$.  So, if both $n$ and $m$ are both really big, $a_n - a_m \approx A - A = 0$.
Now, let's return to your sequence $\left\{a_n\right\}_n = \left\{\sin\left(\frac{n\pi}{2}\right)\right\}_n = \left\{1, 0, -1, 0, 1, 0, -1, \cdots\right\}_n$.  Then, for any $n$
$$\left|a_n - a_{n+1}\right| = 1.$$
So the terms of your sequence are not getting closer together (it is not a Cauchy sequence), and thus it must diverge.


text:
Q: LLBLGen Pro v2.6 designer issue How do you delete more than one entity at the same time in the designer Entities list. it seems that the designer interface only allows the selection of 1 entity at a time....
This is frustrating, is this possible? Or even deleting all entities?
Thanks
Regards
Luis

A: Per the support team:

Sorry, once they're added to the project, the only way to remove them is one at a time.
  Matt


text:
Q: How to debug VB 6 binaries in Visual Studio 2015 I used to debug VB 6 binaries using VS 2005 few years back. Now I am trying to do the same in VS 2015 but I am not able to. Could anyone please tell me step by step how can I debug VB 6 binaries in VS 2015?

A: In your VB6 project's Project->Properties->Compile, check "Compile to Native Code," "No Optimization" and "Create Symbolic Debug Info."

In Visual Studio 2015's Debug->Options, check "Use Native Compatibility Mode":

At runtime, in VS2015, attach to the process containing your VB6 executable. At this point, you should be able to set breakpoints and step through the code.