text:
Q: Code coverage for arrow functions inside an object in Karma I am writing a unit test for one of my applications in which the specifications are passed. But after seeing the code coverage, some parts do not seem to be covered as shown below:
this.columnDefs = [
      {
        translateKey: 'DEVICES.LIST.SNO',
        width: 100,
        resizable: false,
        sortable: false,
        suppressSizeToFit: true,
        floatingFilter: false,
        valueGetter: (args) => this.getId(args),
        checkboxSelection: (params) => {
          return params.columnApi.getRowGroupColumns().length === 0;
        },
        headerCheckboxSelection: (params) => {
          return params.columnApi.getRowGroupColumns().length === 0;
        },
      },
      ...gridColumns,
    ];

In which the valueGetter, CheckboxSelection are not covered

Component File:
export class ListComponent implements OnInit, OnDestroy {
  columnDefs: DeviceColumns[];
  defaultColumnDefs: any;
  gridApi: any;
  columnApi: any;

  constructor() {}

  ngOnInit() {
    this.initializeColumns();
  }

  initializeColumns() {
    this.columnDefs = [
      {
        translateKey: 'DEVICES.LIST.SNO',
        width: 100,
        resizable: false,
        sortable: false,
        suppressSizeToFit: true,
        floatingFilter: false,
        valueGetter: (args) => this.getId(args),
        checkboxSelection: (params) => {
          return params.columnApi.getRowGroupColumns().length === 0;
        },
        headerCheckboxSelection: (params) => {
          return params.columnApi.getRowGroupColumns().length === 0;
        },
      },
    ];
    this.columnDefs.forEach((columnDef) => {
      columnDef.floatingFilter = this.hasFloatingFilter;
    });
    this.columnDefs = map(this.columnDefs, (columnDef) => {
      return extend({}, columnDef, { headerValueGetter: this.localizeHeader.bind(this) });
    });
  }

  getId(args: any): any {
    return (
      this.pagination.per_page * this.pagination.prev_page + parseInt(args.node.rowIndex, 10) + 1
    );
  }

  OnGridReady(params) {
    this.gridApi = params.api;
    this.columnApi = params.columnApi;
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }
}

I need help for performing code coverage for these arrow functions.

A: You can get the valueGetter, checkboxSelection and headerCheckboxSelection from columnDefs property of the component. Then, test them as usual.
E.g. using angular v11+
list.component.ts:
import { OnInit, Component } from '@angular/core';

type DeviceColumns = any;

@Component({
  selector: 'app-list',
  template: 'list component',
})
export class ListComponent implements OnInit {
  columnDefs: DeviceColumns[];
  pagination = {
    per_page: 10,
    prev_page: 1,
  };
  defaultColumnDefs: any;
  gridApi: any;
  columnApi: any;

  constructor() {}

  ngOnInit() {
    this.initializeColumns();
  }

  initializeColumns() {
    this.columnDefs = [
      {
        translateKey: 'DEVICES.LIST.SNO',
        width: 100,
        resizable: false,
        sortable: false,
        suppressSizeToFit: true,
        floatingFilter: false,
        valueGetter: (args) => this.getId(args),
        checkboxSelection: (params) => {
          return params.columnApi.getRowGroupColumns().length === 0;
        },
        headerCheckboxSelection: (params) => {
          return params.columnApi.getRowGroupColumns().length === 0;
        },
      },
    ];
  }
  getId(args: any): any {
    console.log(this, args);
    return (
      this.pagination.per_page * this.pagination.prev_page +
      parseInt(args.node.rowIndex, 10) +
      1
    );
  }
}

list.component.spec.ts:
import { ListComponent } from './list.component';
import { TestBed, waitForAsync, ComponentFixture } from '@angular/core/testing';

fdescribe('65438592', () => {
  let fixture: ComponentFixture<ListComponent>;
  let component: ListComponent;
  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [ListComponent],
      })
        .compileComponents()
        .then(() => {
          fixture = TestBed.createComponent(ListComponent);
          component = fixture.componentInstance;
        });
    })
  );

  it('should checkbox selection', () => {
    fixture.detectChanges();
    const { checkboxSelection } = component.columnDefs[0];
    const columnApiSpy = jasmine.createSpyObj('columnApi', [
      'getRowGroupColumns',
    ]);
    columnApiSpy.getRowGroupColumns.and.returnValue([]);
    const actual = checkboxSelection({ columnApi: columnApiSpy });
    expect(actual).toBeTruthy();
  });

  it('should handle checkbox selection', () => {
    fixture.detectChanges();
    const { headerCheckboxSelection } = component.columnDefs[0];
    const columnApiSpy = jasmine.createSpyObj('columnApi', [
      'getRowGroupColumns',
    ]);
    columnApiSpy.getRowGroupColumns.and.returnValue([]);
    const actual = headerCheckboxSelection({ columnApi: columnApiSpy });
    expect(actual).toBeTruthy();
  });

  it('should get value', () => {
    fixture.detectChanges();
    const { valueGetter } = component.columnDefs[0];
    const getIdSpy = spyOn(component, 'getId').and.returnValue(10);
    const actual = valueGetter({ node: { rowIndex: '0' } });
    expect(actual).toEqual(10);
    expect(getIdSpy).toHaveBeenCalled();
  });
});

unit test result:


text:
Q: How render a Flask WTF HTML 5 widget? I'm trying to use the html 5 widgets of Flask to build a RangeInput (search for "range" to find it).
I think I'm missing something in the HTML template because it renders like that:

As you can see, it's not what I wanted: I was expecting something like that:

So I think the error isn't that tricky but I cannot find it. Here are my different files:
__author__ = 'laurentmeyer'

# That's my main class, don't be afraid, all is local, you cannot hack anything

from MySQL import MySQL
from flask import Flask, render_template
from Form import Form;

mysql = MySQL();
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'Laurent'
app.config['MYSQL_DATABASE_PASSWORD'] = 'laurent'
app.config['MYSQL_DATABASE_DB'] = 'Houses'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

@app.route("/")
def home():
    cursor = mysql.connect().cursor()
    cursor.execute("SELECT * from Offers;")
    data = cursor.fetchall()
    form = Form(csrf_enabled=False);
    if data is None:
        return "No data"
    else:
            return render_template('DB template.html',form = form, offers = data)

if __name__ == "__main__":
    app.run()

My HTML template :
<!DOCTYPE html>

    <title>Tableau des maisons</title>

<form>
Test: {{ form.ImportanceOfPrice }}
</form>

Finally, here is my Form.py (very simple):
__author__ = 'laurentmeyer'

from flask_wtf import Form
from flask_wtf.html5 import RangeInput

class Test(Form):
    ImportanceOfPrice = RangeInput(0.1)

A: the following code should be useful:
from flask import Flask, render_template
from wtforms import Form
from wtforms.fields.html5 import DecimalRangeField

app = Flask(__name__)
app.config['DEBUG'] = True

class TestForm(Form):
    price_importance = DecimalRangeField('Price Importance')

@app.route("/")
def home():
    form = TestForm(csrf_enabled=False)
    return render_template('tpl.html', form=form)

if __name__ == "__main__":
    app.run()

Template tpl.html, which, by default, must be placed into a folder 'templates':
<!DOCTYPE html>

<form>

{{ form.price_importance.label }}: {{ form.price_importance }}

</form>

Your code contains some errors:

*

*Python does not require semi-colons to terminate statements.

*You don't import the right form class (you should import the Test form class)

*In a form class, you should usually declare fields (which are rendered via widgets)

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to let Java HttpServer handle Post Request for File Upload First of all, my question is about HttpServer in Java to handle the POST request from a client, not about a Java client who can upload file to a web server.
OK. I am using a lightweight HttpServer in Java to handle "GET" || "POST" requests. The source code of the HttpServer is copied from http://www.prasannatech.net/2008/11/http-web-server-java-post-file-upload.html.
/*
 * HTTPPOSTServer.java
 * Author: S.Prasanna
 * @version 1.00
 */

import java.io.*;
import java.net.*;
import java.util.*;

public class HTTPPOSTServer extends Thread {

    static final String HTML_START =
        "" +
        "<title>HTTP POST Server in java</title>" +
        "";

    static final String HTML_END =
        "" +
        "";

    Socket connectedClient = null;
    BufferedReader inFromClient = null;
    DataOutputStream outToClient = null;

    public HTTPPOSTServer(Socket client) {
        connectedClient = client;
    }

    public void run() {

        String currentLine = null, postBoundary = null, contentength = null, filename = null, contentLength = null;
        PrintWriter fout = null;

        try {

            System.out.println( "The Client "+
                    connectedClient.getInetAddress() + ":" + connectedClient.getPort() + " is connected");

            inFromClient = new BufferedReader(new InputStreamReader (connectedClient.getInputStream()));
            outToClient = new DataOutputStream(connectedClient.getOutputStream());

            currentLine = inFromClient.readLine();
            String headerLine = currentLine;
            StringTokenizer tokenizer = new StringTokenizer(headerLine);
            String httpMethod = tokenizer.nextToken();
            String httpQueryString = tokenizer.nextToken();

            System.out.println(currentLine);

            if (httpMethod.equals("GET")) {
                System.out.println("GET request");
                if (httpQueryString.equals("/")) {
                    // The default home page
                    String responseString = HTTPPOSTServer.HTML_START +
                        "<form action=\"http://127.0.0.1:5000\" enctype=\"multipart/form-data\"" +
                        "method=\"post\">" +
                        "Enter the name of the File <input name=\"file\" type=\"file\">
" +
                        "<input value=\"Upload\" type=\"submit\"></form>" +
                        "Upload only text files." +
                        HTTPPOSTServer.HTML_END;
                    sendResponse(200, responseString , false);
                } else {
                    sendResponse(404, "The Requested resource not found ...." +
                            "Usage: http://127.0.0.1:5000", false);
                }
            }
            else { //POST request
                System.out.println("POST request");
                do {
                    currentLine = inFromClient.readLine();

                    if (currentLine.indexOf("Content-Type: multipart/form-data") != -1) {
                        String boundary = currentLine.split("boundary=")[1];
                        // The POST boundary

                        while (true) {
                            currentLine = inFromClient.readLine();
                            if (currentLine.indexOf("Content-Length:") != -1) {
                                contentLength = currentLine.split(" ")[1];
                                System.out.println("Content Length = " + contentLength);
                                break;
                            }
                        }

                        //Content length should be < 2MB
                        if (Long.valueOf(contentLength) > 2000000L) {
                            sendResponse(200, "File size should be < 2MB", false);
                        }

                        while (true) {
                            currentLine = inFromClient.readLine();
                            if (currentLine.indexOf("--" + boundary) != -1) {
                                filename = inFromClient.readLine().split("filename=")[1].replaceAll("\"", "");
                                String [] filelist = filename.split("\\" + System.getProperty("file.separator"));
                                filename = filelist[filelist.length - 1];
                                System.out.println("File to be uploaded = " + filename);
                                break;
                            }
                        }

                        String fileContentType = inFromClient.readLine().split(" ")[1];
                        System.out.println("File content type = " + fileContentType);

                        inFromClient.readLine(); //assert(inFromClient.readLine().equals("")) : "Expected line in POST request is "" ";

                        fout = new PrintWriter(filename);
                        String prevLine = inFromClient.readLine();
                        currentLine = inFromClient.readLine();

                        //Here we upload the actual file contents
                        while (true) {
                            if (currentLine.equals("--" + boundary + "--")) {
                                fout.print(prevLine);
                                break;
                            }
                            else {
                                fout.println(prevLine);
                            }
                            prevLine = currentLine;
                            currentLine = inFromClient.readLine();
                        }

                        sendResponse(200, "File " + filename + " Uploaded..", false);
                        fout.close();
                    } //if
                }while (inFromClient.ready()); //End of do-while
            }//else
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendResponse (int statusCode, String responseString, boolean isFile) throws Exception {

        String statusLine = null;
        String serverdetails = "Server: Java HTTPServer";
        String contentLengthLine = null;
        String fileName = null;
        String contentTypeLine = "Content-Type: text/html" + "\r\n";
        FileInputStream fin = null;

        if (statusCode == 200)
            statusLine = "HTTP/1.1 200 OK" + "\r\n";
        else
            statusLine = "HTTP/1.1 404 Not Found" + "\r\n";

        if (isFile) {
            fileName = responseString;
            fin = new FileInputStream(fileName);
            contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "\r\n";
            if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
                contentTypeLine = "Content-Type: \r\n";
        }
        else {
            responseString = HTTPPOSTServer.HTML_START + responseString + HTTPPOSTServer.HTML_END;
            contentLengthLine = "Content-Length: " + responseString.length() + "\r\n";
        }

        outToClient.writeBytes(statusLine);
        outToClient.writeBytes(serverdetails);
        outToClient.writeBytes(contentTypeLine);
        outToClient.writeBytes(contentLengthLine);
        outToClient.writeBytes("Connection: close\r\n");
        outToClient.writeBytes("\r\n");

        if (isFile) sendFile(fin, outToClient);
        else outToClient.writeBytes(responseString);

        outToClient.close();
    }

    public void sendFile (FileInputStream fin, DataOutputStream out) throws Exception {
        byte[] buffer = new byte[1024] ;
        int bytesRead;

        while ((bytesRead = fin.read(buffer)) != -1 ) {
            out.write(buffer, 0, bytesRead);
        }
        fin.close();
    }

    public static void main (String args[]) throws Exception {

        ServerSocket Server = new ServerSocket (5000);
        System.out.println ("HTTP Server Waiting for client on port 5000");

        while(true) {
            Socket connected = Server.accept();
            (new HTTPPOSTServer(connected)).start();
        }
    }
}

I read through the code, I think the code should be all right.
But when I try to upload a file, it will print out POST request, and then hang there and never receive any bytes.
If you are willing to, you can run the above source code directly. After launch it, you can type 127.0.0.1:5000 in a browser, and it will show a file upload, then if I try upload a file, it will hang there after printing PoST request.
If you are bored to read the code, may I ask the following simpler question?
So, what exactly Chrome or any other web browser do about form -> input type='file'?
If I am using a ServerSocket to handle the HTTP request, I just get the InputStream of the request, and then all the content (including HTTP headers & the uploading file's content) will go through that InputStream, right?
The above code can analyse the headers, but then it seems nothing is sent from the browser any more.
Can anyone pls help?
Thanks

A: It hangs because client (Chrome, in my case) does not provide Content-Length.
RFC 1867 is pretty vague about it. It kind of suggests it but does not force it and does not have an example. Apparently clients would not always send it. The code should safeguard against missing length. Instead it goes through the loop until it reaches the end of file. Then it hangs.
Using debugger is very helpful at times.

A: Thats a lotta code :)
Let start by moving the break; calls out of the if statements inside the POST section, starting with line 83.  We need to figure out what is hanging and those while statements could easily be the issue.
This will help us figure out where the issue is.
If you just want it to work, and don't really care what the bug is, this is sort of re-inventing the wheel, there are a ton of libraries out there to make this a one or two line operation.
Here's a good one :  http://www.servlets.com/cos/ - look at the MultiPartRequest class  (source is available in download)

A: This is an old question, but in case others stumble upon it looking for an answer to the title question rather than the specific bug mentioned in the details (I have a feeling that's most viewers)... I would recommend you save yourself the pain and not use the above code snippet.
It is not an HTTP server and it will fail on any but the simplest use case (and apparently even then), nor does is follow basic good coding practices. Even if it weren't for that, it explicitly states it supports text files only (and indeed reads the whole file into a String), and even then doesn't properly handle charset encodings.
That being said, you're probably here looking for one of two answers - how you can accept file uploads in your application, or how an HTTP server itself implements this.
If you are interested in how to do this for fun or educational purposes, I do highly recommend reading the RFCs (RFC 7230 for core HTTP/1.1, RFC 2046 section 5.1 for multipart parsing) and trying to write a simple HTTP-like server like this one. It's a good way to learn, especially if you have an experienced developer to review your code and give you tips and help you find edge cases. As an exercise, you can even start with the code above and try to fix its shortcomings and make it a bit more usable, though still, don't confuse that with a real HTTP server for use in production.
If you don't care for all this and just want to get things done in a real application, I recommend just using a proper HTTP server. There are plenty of them around that will let you do what the above snippet tries to, with much less code and bugs.
Disclaimer: I'm the author of JLHTTP - The Java Lightweight HTTP Server which is a tiny one-file server (or ~50K/35K jar) with no dependencies that strives to be RFC-compliant and supports file uploads among other things. Feel free to use it, or just browse the code and documentation for a relatively simple example of how an HTTP server and multipart parsing (file uploads) might work, both as implemented by the server itself and how you can use this in your application. Or check out any of the many other HTTP servers out there that can do the same.


text:
Q: Automatically apply values from a JSON object to input tags I have a JSON object returned from the database.  The values in the JSON object came from an HTML page full of input tags.
var userTemplate = { };
$("#tabBasic").find($("input")).each(function() {
    userTemplate[this.name] = this.value;
});

Now I'd like to re-apply the values from the JSON to the input tags on the page.
Is there a way to do this automatically using jQuery?

A: You've just got the assignment reversed.
$("#tabBasic").find("input").each(function() {
    this.value = userTemplate[this.name];
});

I assume that each input has a unique name attribute.

You could also pass a function to the val()[docs] method. The return value is assigned as the new value.
$("#tabBasic").find("input").val(function() {
    return userTemplate[this.name];
});


text:
Q: GcmBroadcastReceiver onReceive method not fired on Android 4.0.3 I am writing an Android 4.0.3 program with GCM support.
The app registers fine and sending a message from the server also seems to work (getting "success" from Google with a message id), however the onReceive method on my BroadcastReceiver doesn't get fired for some reason.
Here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jlieberman.nightwatch"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.jlieberman.nightwatch.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.jlieberman.nightwatch.NightWatch"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <category android:name="com.jlieberman.nightwatch" />
            </intent-filter>
        </receiver>

        <service android:name=".GcmIntentService" />
    </application>

</manifest>

And here is the BroadcastReceiver:
package com.jlieberman.nightwatch;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }

}

Any idea what is causing the problem?
Thanks!

A: You have <uses-permission android:name="com.jlieberman.nightwatch.permission.C2D_MESSAGE" /> in your manifest, but I don't see where you define this permission.
You should add :
<permission android:name="com.jlieberman.nightwatch.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

A: Good please try this
   import com.google.android.gms.gcm.GoogleCloudMessaging;
    import android.app.Activity;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.support.v4.app.NotificationCompat;
    import android.util.Log;

    public class MyBroadcastReceiver extends BroadcastReceiver {
        static final String TAG = "pushnotification";
        public static final int NOTIFICATION_ID = 1;
        private NotificationManager mNotificationManager;
        NotificationCompat.Builder builder;
        Context ctx;
        @Override
        public void onReceive(Context context, Intent intent) {
            GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
            ctx = context;
            WakeLocker.acquire(ctx);
            String messageType = gcm.getMessageType(intent);
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification("Send error: " + intent.getExtras().toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification("Deleted messages on server: " +
                        intent.getExtras().toString());
            } else {
                sendNotification("Received: " + intent.getExtras().toString());
            }
            setResultCode(Activity.RESULT_OK);
            WakeLocker.release();
        }
}

And for the wakelocker i wrote a class, here it is,
WakeLocker.java

import android.content.Context;
import android.os.PowerManager;

public abstract class WakeLocker {
    private static PowerManager.WakeLock wakeLock;

    public static void acquire(Context context) {
        if (wakeLock != null) wakeLock.release();

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
                PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.ON_AFTER_RELEASE, "WakeLock");
        wakeLock.acquire();
    }

    public static void release() {
        if (wakeLock != null) wakeLock.release(); wakeLock = null;
    }
}

Try this and if it doesn't work ill be here to help!!!!

A: I had the same problem recently, and discovered that it is a package name error in the permissions. need to follow this guide exactly, with the name of your main package, that the example of google lends itself to Confucianism.
Add the following to your application's manifest:
The com.google.android.c2dm.permission.RECEIVE
The android.permission.INTERNET
The android.permission.GET_ACCOUNTS
The android.permission.WAKE_LOCK
An applicationPackage + ".permission.C2D_MESSAGE"

And In the filter name:
A receiver for com.google.android.c2dm.intent.RECEIVE


text:
Q: Nhibernate: How to find responsible Field for SqlDateTime overflow exception I know the reason for the exception (SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.) is a non nullable DateTime field in a Entity and so Nhibernate wants to save a smaller DateTime value than MSSQL accepts.
The Problem ist that there are far to many entities in the project to find the right DateTime field.
The exception occurs after an SaveOrUpdate() but is not triggered by the entity i want to save but any other entity which was loaded in the current session and now is affected by the flush().
How can i find out which field really is responsible for the exception?

A: If you cast the exception to a SqlTypeException, that will expose the Data collection.  Normally there is a single Key and a single Value in the collection.  The value is the SQL that was attempted to be executed.  By examining the DML you can then see what table was being acted upon.  Hopefully that table is narrow enough to make determining the offending column trivial.
Here's some simple code I use to spit out the Key and Value of the exception.
            catch (SqlTypeException e)
            {
                foreach(var key in e.Data.Keys)
                {
                    System.Console.Write("Key is " + key.ToString());
                }
                foreach(var value in e.Data.Values)
                {
                    Console.WriteLine("Value is "+value.ToString());
                }
            }

A: Have you tried forcing NHib to output the generated sql and reviewing that for the rogue DateTime? It'd be easier if you were using something like NHProfiler (I don't work for them, just a satisfied customer), but really all that's doing for you is showing/isolating the sql anyway, which you can do from the output window with a little extra effort. The trick will be if it's a really deep save, then there could potentially be a lot of sql to read through, but chances are you'll be able to spot it pretty quickly.

A: You can create a class that implements both IPreUpdateEventListener and IPreInsertEventListener as follows:
  public class InsertUpdateListener : IPreInsertEventListener, IPreUpdateEventListener {
     public bool OnPreInsert(PreInsertEvent @event) {
        CheckDateTimeWithinSqlRange(@event.Persister, @event.State);
        return false;
     }

     public bool OnPreUpdate(PreUpdateEvent @event) {
        CheckDateTimeWithinSqlRange(@event.Persister, @event.State);
        return false;
     }

     private static void CheckDateTimeWithinSqlRange(IEntityPersister persister, IReadOnlyList<object> state) {
        var rgnMin = System.Data.SqlTypes.SqlDateTime.MinValue.Value;
        // There is a small but relevant difference between DateTime.MaxValue and SqlDateTime.MaxValue.
        // DateTime.MaxValue is bigger than SqlDateTime.MaxValue but still within the valid range of
        // values for SQL Server. Therefore we test against DateTime.MaxValue and not against
        // SqlDateTime.MaxValue. [Manfred, 04jul2017]
        //var rgnMax = System.Data.SqlTypes.SqlDateTime.MaxValue.Value;
        var rgnMax = DateTime.MaxValue;
        for (var i = 0; i < state.Count; i++) {
           if (state[i] != null
               && state[i] is DateTime) {
              var value = (DateTime)state[i];
              if (value < rgnMin /*|| value > rgnMax*/) { // we don't check max as SQL Server is happy with DateTime.MaxValue [Manfred, 04jul2017]
                 throw new ArgumentOutOfRangeException(persister.PropertyNames[i], value,
                    $"Property '{persister.PropertyNames[i]}' for class '{persister.EntityName}' must be between {rgnMin:s} and {rgnMax:s} but was {value:s}");
              }
           }
        }
     }
  }

You also need to then register this event handler when you configure the session factory. Add an instance to Configuration.EventListeners.PreUpdateEventListeners and to Configuration.EventListeners.PreInsertEventListeners and then use the Configuration object when creating NHibernate's session factory.
What this does is this: Every time NHibernate inserts or updates an entity it will call OnPreInsert() or OnPreUpdate() respectively. Each of these methods in turn calls CheckDateTimeWithinSqlRange().
CheckDateTimeWithinSqlRange() iterates over all property values of the entity, ie the object, that is being saved. If the property value is not null it then checks if it is of type DateTime. If that is the case it checks that it is not less than SqlDateTime.MinValue.Value (note the additional .Value to avoid exceptions). There is no need to check against SqlDateTime.MaxValue.Value if you are using SQL Server 2012 or later. They will happily accept even DateTime.MaxValue which is a few time ticks greater than SqlDateTime.MaxValue.Value.
If the value is outside of the allowed range this code will then throw an ArgumentOutOfRangeException with an appropriate message that includes the names of the class (entity) and property causing the problem as well as the actual value that was passed in. The message is similar to the equivalent SqlServerException for the SqlDateTime overflow exception but will make it easier to pinpoint the problem.
A couple of things to consider. Obviously this does not come for free. You will incur a runtime overhead as this logic consumes CPU. Depending on your scenario this may not be a problem. If it is, you can also consider optimizing the code given in this example to make it faster. One option could perhaps be to use caching to avoid the loop for the same class. Another option could be to use it only in test and development environments. For production you could then rely that the rest of the system operates correctly and the values will always be within valid range.
Also, be aware that this code introduces a dependency on SQL Server. NHibernate is typically used to avoid dependencies like this. Other database servers that are supported by NHibernate may have a different range of allowed values for datetime. Again, there are options for resolving this as well, e.g. by using different boundaries depending on SQL dialect.
Happy coding!


text:
Q: Keyword density and instance php script I am usng the following script but its not working, It keeps saying there is only once instance of the keyword
Maybe it  has something to do with the special character? Not sure how to fix it though
   $word_count = explode(' ', "estudiar inglés estudiar inglés asdasd asd asd sadasd estudiar ingles adas dasd estudiar inglés");
$word_count = count($word_count);
$keyword= "estudiar inglés";

echo $keyword;

$keyword_count = preg_match_all("#{$keyword}#si", $text, $matches);
$keyword_count = count($matches);

$density = $keyword_count / $word_count * 100;

$density = number_format($density, 2) . '%';

              echo $keyword_count;

A: This work:
$text       = "some text asoijw oijd cj isoj some text asiojoasj aisojsaij";

$word_count = explode(' ',$text);
$word_count = count($word_count);
$keyword    = "some text";

$keyword_count = preg_match_all("/$keyword/i", $text, $matches);
$keyword_count = count($matches[0]);

$density = $keyword_count / $word_count * 100;
$density = number_format($density, 2) . '%';

echo "Text: $text
"
    ."Keyword: $keyword

"
    ."Matched $keyword_count time(s)
"
    ."Density: $density";

$matches[0]: preg_match_all split matches into subarrays


text:
Q: Icon tag  in remote ajax call in rails i want to use the new Icon  tag from bootstrap css to make a remote call in rails 3.1.1
Here is my original code:
<%=link_to(image_tag("/assets/icons/sub_blue_down.png", :class => "points_arrow"),
vote_down_politician_path(pending_discussions, :politician_id  =>
pending_discussions.politician_id), :remote=> true, :method => :post) %>

I want to use this:

Instead of the image tag
Here is my attempt but doesn't work:
<%= link_to  ' ',
vote_up_politician_path(pending_discussions, :politician_id  =>
pending_discussions.politician_id), :remote=> true, :method => :post%>

A: You should be using this syntax instead:
<%= link_to vote_up_politician_path(pending_discussions, :politician_id  =>
pending_discussions.politician_id), :remote=> true, :method => :post do%>

<% end %>

More info: http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to

A: You should also be able to use content_tag for this. Although this example doesn't do a remote call, it does use link_to and the glyph icons:
<%= link_to(content_tag(:i, nil, class: "icon-remove-sign"),
  adcard_path(adcard), data: { confirm: "Are you sure?" },
  method: :delete, class: 'btn btn-mini') %>

In my case this was an address card with a delete button. Just another way, I think, and it might help someone else.
content_tag reference: http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag


text:
Q: How to get better typing for MongoDB BSON validator ? (instead of `[key: string]: any;`) When following the typing of validator I end up on [key: string]: any;.
await db().createCollection('model', {
  validator: {
    $jsonSchema: {
      // ...
    }
  }
});

// mongodb.d.ts
export declare interface CreateCollectionOptions extends CommandOperationOptions {
// ...
    /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher */
    validator?: Document;
// ...
}

// bson.ts
export interface Document {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [key: string]: any;
}

I thought about @types/bson, but it is deprecated. Because "bson provides its own type definitions".


text:
Q: Simple way to shorten time period of graph in ggplot Let's consider data :
library(ggplot2)
library(quantmod)
start <- as.Date("2013-01-01")
end <- as.Date("2016-10-01")
# Apple stock
getSymbols("AAPL", src = "yahoo", from = start, to = end)

And plot :
autoplot(Cl(AAPL))

My question is : is there any way how can I simlpy shorten time period of my plot ? Let's say for example I want to have my plot from '2013-01-01' up to '2014-01-01'. Of course I can do exactly same thing with changing my start and end variables (defined at the very beggining) and redownload data set. However I found this solution inefficient. Is there any simpler way how it can be performed ?

A: You can add an xlim =  argument to autoplot:
autoplot(Cl(AAPL),
         xlim = as.Date(c("2014-01-01","2016-04-01")))

You can also use the + operator if you prefer:
autoplot(Cl(AAPL)) +
  xlim(as.Date(c("2014-01-01","2016-04-01")))

See help(autoplot.zoo) for more.

A: There are two approaches. One is to specify limits to the plotting routine and the other is to subset the data itself.  Since the first one is already illustrated by another answer we will focus on the second:
# xts suppports .../... notation
apple <- Cl(AAPL)['2013-01-01/2014-01-01']

# this will extract all rows for 2013
apple <- Cl(AAPL)['2013']

# window function
apple <- window(Cl(AAPL), start = "2013-01-01", end = "2014-01-01")

Having defined apple we can autoplot it.


text:
Q: Running Nameserver behind NAT I have an internet connection with a static ip from my ISP. I do have mail servers and webservers hosted from it. What i would like to achieve is run couple of nameservers by getting another static ip from my ISP. I have forwarded TCP and UDP ports from my local IP address and the internet connection is being managed by pfsense. The DNS resolver and forwarder service has been disabled.
I tried to setup a nameserver by NAT and forwarded PORT 53 for udp & tcp traffic. But still when i try to query a record for a zone on my nameserver using dig externally or internally , i get an error "no servers could be reached". Is there any guide or information that would help me to setup the nameservers behind NAT or help me solve this issue?
My ISP has confirmed that they do not have blocks or filters in place. I have also confirmed that no ports are being blocked or filtered from my end too. The name of the nameserver is ns1.sitehosters.in.
ETHERNET CONFIG on NS1
auto eth1
iface eth1 inet static
address 192.168.1.12
netmask 255.255.255.0
gateway 192.168.1.1(PFSENSE)
dns-nameservers 8.8.8.8

/etc/bind/named/conf.options
options {
directory "/var/cache/bind";
dnssec-validation auto;
auth-nxdomain no;
listen-on-v6 { any; };
};

Named.conf.local file on ns1
nano /etc/bind/named.conf.local
zone "sitehosters.in" {
type master;
allow-transfer {none;};
file"/etc/bind/pri.sitehosters.in"
};

Netstat output from below:
tcp 0 0 192.168.1.36:domain . LISTEN 1156/named
tcp 0 0 localhost:domain . LISTEN 1156/named
tcp 0 0 localhost:953 . LISTEN 1156/named
udp 0 0 192.168.1.36:domain . 1156/named
udp 0 0 localhost:domain . 1156/named

DNSCHECK at PINGDOM
No name servers found at child.

No name servers could be found at the child.
This usually means that the child is not configured to answer queries about the zone.

Please find some screenshots of my router config which might help you to point me in the right direction. I use pfsense on a PC which is managing all the internet connection and firewall.
When using packet capture on my wan port in pfsense, i get
19:05:02.660753 IP xx.xx.xx.xx.13747 > 8.8.8.8.53: UDP, length 27
19:05:02.669900 IP 8.8.8.8.53 > xx.xx.xx.xx.13747: UDP, length 509
19:05:02.670409 IP xx.xx.xx.xx.63621 > 8.8.8.8.53: UDP, length 44
19:05:02.694125 IP xx.xx.xx.xx.34919 > 8.8.8.8.53: UDP, length 27
19:05:02.704487 IP 8.8.8.8.53 > xx.xx.xx.xx.34919: UDP, length 509
19:05:02.705580 IP xx.xx.xx.xx.11687 > 8.8.8.8.53: UDP, length 44
19:05:02.741893 IP 8.8.8.8.53 > xx.xx.xx.xx.11687: UDP, length 208
19:05:02.741919 IP 8.8.8.8.53 > xx.xx.xx.xx.63621: UDP, length 208

19:13:39.682095 IP 81.143.220.107.51368 > xx.xx.xx.xx.53: tcp 0
19:13:39.682355 IP xx.xx.xx.xx.53 > 81.143.220.107.51368: tcp 0
19:13:39.893583 IP 81.143.220.107.51368 > xx.xx.xx.xx: tcp 0
19:13:39.894893 IP 81.143.220.107.51368 > xx.xx.xx.xx.53: tcp 34
19:13:39.895023 IP xx.xx.xx.xx.53 > 81.143.220.107.51368: tcp 0
19:13:39.895353 IP xx.xx.xx.xx.53 > 81.143.220.107.51368: tcp 155
19:13:40.100199 IP 81.143.220.107.51368 > xx.xx.xx.xx.53: tcp 0
19:13:40.100220 IP 81.143.220.107.51368 > xx.xx.xx.xx.53: tcp 0

The report at intodns.com says
DNS servers responded   ERROR: One or more of your nameservers did not respond:
The ones that did not respond are: xx.xx.xx.xx

A: If you want to run a nameserver that is the authority for an Intenet zone then it will need to be properly addressed with an public IP.
If you must put a name server behind a NAT, then the NAT device must incorporate an appropriate Application Layer Gateway (ALG).  Although many NAT devices will incorporate an ALG suitable for NATing the client IP address I don't know if any of them are built to NAT SOA records etc.
If you only have /32 public addresses then you might be able to port-forward through your outer router and then push that through a second NAT device to restore the original destination IP address.  Off the top of my head this should work but I haven't thought it through at length.
I haven't looked at yopu configs in detail but notice that you've got 8.8.8.8 defined as name server.  Unless you want to restrict your name server to authoritative-only then you'd have that set to 127.0.0.1.
On reflection NATing twice shouldn't be necessary.  The DNS server may need to have an interface on it with the public IP address though, you can probably achieve that with a secondary IP on an interface.

A: I figured it out. The ISP had a filter on port 53 even though it was open. Got to change the ISP as they cant remove the block. Thanks all for the time spend solving the issue


text:
Q: Pass IDs of visible images I have got 21 images inside multiple divs. Below is an example of the images.

When the page loads 3 - 6 random images will be visible. Now I want to be able to know which images are visible by its id. So basically I want to pass the id of each visible image on to a function.
This is what I did. But its not doing as expected. Not all visible image id's are passed. How can I identify the visible images and be able to pass each of their IDs to the passFunction() ?
$('#getIDs').click(function(){
   if( $('.fruit').css('visibility', 'visible') ){
       passFunction( $(this.id) );
   }
});

A: Try using this pseudo :visible on document load (am assuming the images are created randomly when the document loads) as follows:
$('.fruit:visible').each(function(){
       passFunction( $(this).attr("id") );
});

A: This is done easily with :visible and .each()
$('#getIDs').click(function(){
    $('.fruit:visible').each(function (){
       passFunction( $(this.id) );
   });
});

BUT
the :visible selector might not select all the "invisible" images. (example images that are visible but are off screen)

A: As leonid mentioned if your code is showing/hiding image elements you can use :visible selector with any of above code examples. You would also need to lookout how images are being shown/hidden. If it is controlled by opacity or visibility css styling it will come in visible images ids even if not shown on screen. If it has css styling as display:none it wont get caught in :visible selector that is what I noted in jquery visible selector example. You can refer to https://api.jquery.com/visible-selector/


text:
Q: multiline textbox validation ms access Hi I am pretty new to Ms Access and I could use some of your expertise to advise:
I would like to validate the text of a multiline textbox, so that the user can only enter 2 capital letters - 7 numbers - semi-colon - new line.  As an example, the textbox would look like this (but with each entry on a new line, since I have it so that enter makes a new line in the textbox
AB1234567; SE0001848; SE0019591; RE0010599; etc.

I think this is too complex for a validation rule.  I also think it's too complex for an input mask.  I started looking into RegEx to validate the text but I am hungup on how to have the code evaluate each new line in the multiline textbox so that the entire textbox is evaluated.  Do i need to do a loop of some sort?
Ultimately, I would like the user to get a message box when they enter their text incorrectly that blocks the entry from being added to the record and also explains to the user that they need to modify their entry so that it is valid.

A: I think your idea of RegEx is the easiest but you'll need to add a reference (see code).
This should do what you want (just replace Text14 with your text control)
Note - I removed the CANCEL=TRUE because that wipes out the users data. The best route woul dbe to make sure the text box is UNBOUND - then if valid you would update the actual field if the RegExp is validated for all lines
Private Sub Text14_BeforeUpdate(Cancel As Integer)

    ' Requires reference to "Microsoft VBScript Regular Expressions 5.5"
    ' Under Tools | References
    ' Add Reference to "Microsoft VBScript Regular Expressions 5.5"

    ' 2 Capital Letters followed by 7 digits and ";'
    Const VALID_LINE    As String = "[A-Z]{2}[\d]{7};"

    Dim regEx As New RegExp

    Dim strData     As String  ' Read in textbox
    Dim varLines    As Variant ' Use this to hold lines of text

    Dim intNumLines As Integer
    Dim intLine     As Integer
    Dim strLine     As String

    With regEx
        .Global = True
        .Multiline = False
        .IgnoreCase = False
        .Pattern = VALID_LINE
    End With

    ' Replace Text14 with your text box control name
    strData = Text14.Value ' Get Data from Text box

    ' Split data into lines using Carriage Return Line Feed delimiters
    varLines = Split(strData, vbCrLf)

    ' Go thru all lines to check for data issue
    intNumLines = UBound(varLines)
    For intLine = 0 To intNumLines
        strLine = varLines(intLine)
        If Not regEx.Test(strLine) Then
            MsgBox "Problem with Line #" & (intLine + 1)
            ' Cancel - if you want to wipe out data
            ' Cancel = True
            Exit Sub
        End If
    Next

    MsgBox "Data Looks Good: All " & intNumLines & " Lines"

End Sub


text:
Q: Drop some parts of video and re-make key frames (c++ + libav) I'm trying to drop some parts of video in my app using libav, for example in a video that has 00:08:00 length, I try to drop frames 100-250 and 400-500 (Just for example).
I wrote this code that copy AVPacket and drop some packets, But there is a problem! In our videos every keyframe followed by 29 non-key frames. So when my code goes to drop frames 100-250 the frame 100 may be is a non-key frame, in this case the parts that are going to join (In this example frame 250 to frame 400) the frame 400 is positioned after a keyframe that is not belogs to.
In this section video frames shown garbled,
Video cutting speed is so important in my code, so I can't decode/re-encode all of video frames.
The question is that, How can I decode encode begin of each parts (from begin frame to first key frame) and make another frames copy without decode?
Or, Is there any another FAST solution for splitting/merging (Dropping some parts of video)?

A: The question is that, How can I decode encode begin of each parts (from  begin frame to first key frame) and make another frames copy without decode?

You can't. It doesn't work that way.

A: Start to think about time, not in frames
you can get new videos fast in parts of base_video.mp4, for example,
ffmpeg -ss 00:00:00.000 -i base_video.mp4 -t 8.000 -c copy -strict -2 new_video_8seconds_fromstart.mp4

-ss 00:00:00.000 is the time to start the new video
-t is the duration in seconds and miliseconds, example, for 8 seconds of duration you have to use 8.000
-an if you dont want audio
-strict -2 if for copy some files codecs like DTS

but if you want with re-encoding remove -c copy but it never will be fast!
ffmpeg -ss 00:00:00.000 -i base_video.mp4 -t 8.000 new_video_8seconds_fromstart.mp4


text:
Q: iOS Health Kit Clinical Patient Data I have a third-party app that is attempting to gather clinical health records from the iOS Health App. I have successfully followed these steps to gain access to apple healths 7 record types. For the requirements of this task, I also need to gain access to "Patient Data". This data can be found within the Apple Health App under accounts:

In the "FHIR Patient Data" tab:

Does the apple health kit API allow for this type of data fetch?

A: The answer to your question is yes, the API supports retrieval of FHIR records. You will have to pull the data apart yourself after you get it. Here is some example code which will get the records;
func getClinicalDocuments()
{
    guard let cdaType = HKObjectType.documentType(forIdentifier: .CDA) else {
        print("unable to create CDA type.")
        return
    }
    allDocuments.removeAll(keepingCapacity: true)

    let cdaQuery = HKDocumentQuery(documentType: cdaType, predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: nil, includeDocumentData: true)
    { (query, results, done, error) in

        if results != nil
        {
             for d in results!
            {
                self.allDocuments.append(d as! HKCDADocumentSample)
            }
        }

    }
     healthStore.execute(cdaQuery)
}


text:
Q: remove password from vertification mail razor have taken over some code from a other person
the razor code sends an notification to the owner with information about the user.
however right now it alson sends the password which i would like to remove from the message
@inherits UmbracoViewPage<Umbraco.Forms.Core.Models.FormsHtmlModel>

@{
    //This is an example email template where you can use Razor Views to send HTML emails

    //You can use Umbraco.Content & Umbraco.Media etc to use Images & content from your site
    //directly in your email templates too

    //Strongly Typed
    //@Model.GetValue("aliasFormField")
    //@foreach (var color in Model.GetValues("checkboxField")){}

    //Images need to be absolute - so fetching domain to prefix with images
    var siteDomain = Request.Url.GetLeftPart(UriPartial.Authority);
    var assetUrl = siteDomain + "/App_plugins/UmbracoForms/Assets/Email-Example";

}
<!DOCTYPE html>

    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,900" rel="stylesheet">

Umbraco Forms

                            This is an example email template from Umbraco Forms Razor based email templates. You can build forms using any HTML markup you wish.

Form Results

                            @{
                                string[] ignoreFields = new string[]
                                {
                            "FieldType.Recaptcha2.cshtml",
                            "FieldType.Recaptcha3.cshtml",
                            "FieldType.Text.cshtml"
                                };
                            }

                            @foreach (var field in Model.Fields.Where(x => ignoreFields.Contains(x.FieldType) == false))
                            {

@field.Name

                                    @switch (field.FieldType)
                                    {
                                        case "FieldType.FileUpload.cshtml":
                                            var fileUploadValue = field.GetValue();
                                            if (fileUploadValue != null && !string.IsNullOrEmpty(fileUploadValue.ToString()))
                                            {
                                                @fileUploadValue
                                            }
                                            break;

                                        case "FieldType.DatePicker.cshtml":
                                            var datePickerValue = field.GetValue();
                                            if (datePickerValue != null && !string.IsNullOrEmpty(datePickerValue.ToString()))
                                            {
                                                DateTime dt;
                                                var dateValid = DateTime.TryParse(datePickerValue != null ? datePickerValue.ToString() : string.Empty, out dt);
                                                var dateStr = dateValid ? dt.ToString("f") : "";
                                                @dateStr
                                            }
                                            break;

                                        default:
                                            var values = field.GetValues();
                                            if (values != null)
                                            {
                                                foreach (var value in values)
                                                {
                                                    @value

                                                }
                                            }
                                            break;
                                    }

                            }

Need more help?

Find our documentation here

i think i have located the problem to this part
@switch (field.FieldType)
                                    {
                                        case "FieldType.FileUpload.cshtml":
                                            var fileUploadValue = field.GetValue();
                                            if (fileUploadValue != null && !string.IsNullOrEmpty(fileUploadValue.ToString()))
                                            {
                                                @fileUploadValue
                                            }
                                            break;

                                        case "FieldType.DatePicker.cshtml":
                                            var datePickerValue = field.GetValue();
                                            if (datePickerValue != null && !string.IsNullOrEmpty(datePickerValue.ToString()))
                                            {
                                                DateTime dt;
                                                var dateValid = DateTime.TryParse(datePickerValue != null ? datePickerValue.ToString() : string.Empty, out dt);
                                                var dateStr = dateValid ? dt.ToString("f") : "";
                                                @dateStr
                                            }
                                            break;

                                        default:
                                            var values = field.GetValues();
                                            if (values != null)
                                            {
                                                foreach (var value in values)
                                                {
                                                    @value

                                                }
                                            }
                                            break;
                                    }

and i think i could maybe change the foreach loop, just want to be sure i only leave out the password


text:
Q: Swift: JSON unexpected error with nil second level element I have a problem trying to create a JSON object.
Everything is fine until I try to create a second level element with nil values:
var json = [String: AnyObject]()
json["id"] = 1234567

let secondLevel : [String: AnyObject] = ["i1": 12, "i2": "not nil"]
json["secondLevel"] = secondLevel

This is fine, but if I try:
let secondLevel : [String: AnyObject?] = ["i1": 12, "i2": nil]
json["secondLevel"] = secondLevel

I got the following error:

cannot assign a value of type '[String : AnyObject?]' to a value of
  type 'AnyObject?'

What does it means? Isn't a [String:AnyObject?] of AnyObject type?
What could I do to avoid this error?

A: You can use Any instead of AnyObject

Type Casting for Any and AnyObject
Swift provides two special type aliases for working with non-specific types:
AnyObject can represent an instance of any class type.
Any can represent an instance of any type at all, apart from function types.
NOTE:
Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code.

From The Swift Programming Language
var json = [String: Any]()
json["id"] = 123452

let secondLevel : [String: Any?] = ["i1": 12, "i2": nil]
json["secondLevel"] = secondLevel

print(json)

A: The key was not use Any instead of AnyObject, I couldn't change the type.
The solution is to use an object to manipulate nil value like:
let secondLevel : [String: AnyObject] = ["i1": 12, "i2": NSNull()]
json["secondLevel"] = secondLevel

A: You should probably check out the following links:

*

*https://stackoverflow.com/a/25475702/1235505

*https://stackoverflow.com/a/29722810/1235505
Here they mention why your code does not work. The first link demonstrates how you can properly create a dictionary object containing multiple nested dictionaries.
The second link will show you why your code does not work. It seems the dictionary object is a struct, not a class. A struct does not inherit from the AnyObject class. Hence you can not cast a dictionary to an AnyObject object. Perhaps you should use an NSDictionary object instead as suggested in the second link.
What I mean by using NSDictionary:
var secondLevel: NSDictionary = [
    "i1" : 12,
    "i2" : "not nil"
]

var json: [String: AnyObject] = []
json["id"] = 1234567
json["secondLevel"] = secondLevel


text:
Q: How do you split duplicate letters with "x" in Python? I am trying to create a function which is able to detect when two letters back to back are duplicates, for example the ls in "hello", and split the duplicate letters with the letter "x". Here is my code:
plaintext = input("Enter plaintext here: ")

plaintext = plaintext.lower() # makes plaintext lowercase
plaintext = plaintext.replace(" ", "") # removes all spaces

# this separates all duplicate letters

i = 0 # sets i to 0
for letter in plaintext:
    if plaintext[-1] == plaintext[-2]: # if the last letter is the same as the second to last
        plaintext = plaintext[:-1] + "x" + plaintext[-1:] # separate them with an x
    elif plaintext[i] == plaintext [i+1]: # if one letter is the same as the next letter
        # the line above makes an error
        plaintext = plaintext[:i+1] + "x" + plaintext[i+1:] #separate them with an x
        i += 1
    else:
        i += 1

This code works when I enter hello there as the input; I receive helxlothere. However, when I test another input, such as heythere, IndexError: string index out of range shows up for elif line (line 12). How can I make this code work for all inputs?

A: You can use regex to achieve this.
For both approaches, it will work for hello there hey there
The difference comes when more than two character repetition happens.
approach 1
import re
string='hello there'
# find Any repeated character and add x in between them
answer = re.sub(r'(.)\1{1}', r'\1x\1', string)
print(answer)

Here for hellllo there text, you will get output helxllxlo there
approach 2
alternatively, you can use this method.
s="hello there"

for match in re.finditer(r"(.)\1+", s):
    old=s[match.start():match.end()]
    s=s.replace(old,'x'.join(old))
print(s)

here for hellllo there text, you will get output helxlxlxlo there as output.
I think the second approach will be more appropriate.

A: The IndexError is caused by the fact that you are looking at plaintext[i+1]. As you can see in the word heythere, there are no letters which match back to back, and therefore the code continues until it hits the end, and so you get an IndexError because there is no element i+1.
You can fix this by using this code instead:
plaintext = input("Enter plaintext here: ")

    plaintext = plaintext.lower() # makes plaintext lowercase
    plaintext = plaintext.replace(" ", "") # removes all spaces

    # this separates all duplicate letters

    i = 0 # sets i to 0
    for letter in plaintext:
        if plaintext[-1] == plaintext[-2]: # if the last letter is the same as the second to last
            plaintext = plaintext[:-1] + "x" + plaintext[-1:] # separate them with an x
        try:
            elif plaintext[i] == plaintext [i+1]: # if one letter is the same as the next letter
                # the line above makes an error
                plaintext = plaintext[:i+1] + "x" + plaintext[i+1:] #separate them with an x
                i += 1
            else:
                i += 1
        except IndexError:
            pass

This code should stop your code from crashing in the elif statement, while also completing properly.
Hope this helps, have a nice day!

A: You are receiving the IndexError because during iterating, when the loop reaches the last letter,
elif plaintext[i] == plaintext [i+1]:
this line checks for the letter after the last letter, which does not exist, which causes the program to run into IndexError.
You have to check till the second last letter, for it to work properly.

A: A simple and easier way to arrive at the same output with a bit easier logic.
Logic
Create a new string and insert all letters which are in the old string, plaintext, to the new string, newPlainText, and check only for one condition that is whether the last letter is same as current or not and if yes then also insert letter 'x' into the newPlainText and that's it!
plaintext = input("Enter plaintext here: ")

plaintext = plaintext.lower() # makes plaintext lowercase
plaintext = plaintext.replace(" ", "") # removes all spaces

# this separates all duplicate letters

newPlainText = plaintext[0] # copy the first letter of plaintext to the new string which will handle the duplicates and insert `x` between them

i = 1 # sets i to 1

while i < len(plaintext):
    if plaintext[i] == plaintext[i-1]: # we check that if prev and current letters are same then also append x to the new string
        newPlainText += "x"

    newPlainText += plaintext[i]    # we insert the required current letter to the new string in each iteration
    i += 1

print(newPlainText)


text:
Q: Proving inequality $\frac{1}{2}e^x\left(2+e^x\right) > \left(1+e^x\right)\ln(1+e^x)$ Do you have any ideas on how to show the following inequality?
$$\frac{1}{2}e^x\left(2+e^x\right) > \left(1+e^x\right)\ln(1+e^x)$$
It's not about the convexity of any of those functions. Derivatives doesn't look interesting to me as well, but maybe I'm missing something.

A: By following @Daniel Fischer's suggestion, we only need to prove that:
$$\frac{t^2-1}{2t}>\log t\tag{1}$$
for any $t>1$. By replacing $t$ with $e^u$, we only need to prove that:
$$ u < \sinh u \tag{2}$$
for any $u>0$. But $(2)$ is trivial by convexity, since $\sinh 0=0$, $\sinh' 0 = \cosh 0 = 1$ and $\sinh'' u=\sinh u > 0$ for any $u>0$.


text:
Q: How (or in which file) does JShell store its configuration settings? The doc says:

Remember that the startup scripts are loaded into the current session
  only when the state is reset. The contents of the script is stored,
  not a reference to the script.

(https://docs.oracle.com/javase/9/jshell/scripts.htm#JSHEL-GUID-AC2A6582-6A9A-48B1-ABBF-4C9536CDFD07)
For example,
/set start -retain mystartscript.jsh

But where does it store the contents of mystartscript.jsh?

A: Using a relative filename like you do in your example:
/set start -retain mystartscript.jsh

JShell would look for mystartscript.jsh in [user.home]/mystartscript.jsh
You could also give it an absolute file path:
/set start -retain /my_custom_jshell_scripts/mystartscript.jsh

Robert Field—the JShell lead architect—explains in this tutorial how to (re)set/unset JShell's built-in DEFAULT startup scripts plus custom .jshstartup scripts.


text:
Q: What is the word "funny" modifying in this sentence?
I don't understand why Daniella is acting so funny.

Is funny modifiying Daniella (which would make it an adjective) or is it modifying acting (making it an adverb)?
Is there any way to tell from this sentence?

A: funny in this sentence is an adverb (meaning strangely) modifying the verb acting.


text:
Q: progress indicator for javafx app I'm using below code for showing progress indicator for loading tasks.I'm using MaskerPane from ControlsFX progress indicator.
But when i using the component , maskerpane only showing 1 time..Please suggest a better way for showing progress indicator.
@FXML
    private MaskerPane progressPane;
 @FXML
        private void addMemberSelect() {
            Task task = new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    progressPane.setVisible(true);
                    return null;
                }
                @Override
                protected void succeeded(){
                    super.succeeded();
                    content.setContent(null);
                    ScreensController colllectScreenController = new ScreensController();
                    colllectScreenController.loadScreen(Screens.ADD_MEMBER);
                    colllectScreenController.setScreen(Screens.ADD_MEMBER);
                    content.setContent(colllectScreenController);
                    progressPane.setVisible(false);
                }
            };
            new Thread(task).start();
        }

A: This example can help you.
public class MaskerPaneTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {

    MaskerPane progressPane = new MaskerPane();
    progressPane.setVisible(false);

    Button button = new Button("Show");
    button.setOnAction(event -> {

            Task task = new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    progressPane.setVisible(true);
                    Thread.sleep(2000);
                    return null;
                }
                @Override
                protected void succeeded(){
                    super.succeeded();
                    progressPane.setVisible(false);
                }
            };
            new Thread(task).start();
        });
    VBox box = new VBox(button, progressPane);
    box.setAlignment(Pos.CENTER);
    Scene scene = new Scene(box, 200, 200);
    primaryStage.setScene(scene);
    primaryStage.show();
}

}
Source: https://gist.github.com/TheItachiUchiha/13f8cc637872ebac4385f92cd16075a7
I tested it and it works well, so you can adapt it.


text:
Q: Push to Azure Container Registry is painfully slow at unpredictable times We're pushing docker images from Azure DevOps pipeline to the repo in ACR.
The build agent is running on a VM in Azure and it's not utilised by anything else.
Sometimes (often at night) the push commands takes 3s, sometimes (mostly during the day UTC) it can take up to 20min.
The tier of our ACR is Standard.
Do you encounter similar problems? Is there to do to avoid these "lags"?
Since we're pusinh many images per day, this can be really a nuisance.

A: There is an issue about this is on Github: https://github.com/Azure/acr/issues/214
For us it has been especially bad yesterday and today.
In the issue on Github they mentioned they are looking into it: https://github.com/Azure/acr/issues/214#issuecomment-509672337


text:
Q: Update Image Thumbnail from c# I am manipulating JPEG images programmatically from C# in a WinForms app in Win 10 and would like File Explorer to show the manipulated rather than the original image thumbnail. Closing Explorer,  deleting %LocalAppData%\Microsoft\Windows\Explorer\thumbcache_*.db and restarting does this but it is slow and intrusive. I would like to update an individual file's thumbnail programmatically. Windows does this when an image is rotated via the Explorer context menu, but the means for doing this from a program aren't clear.
The batch file which I currently use to  close Explorer, delete the thumbnail cache file and restart is
taskkill /f /im explorer.exe
timeout 2 /nobreak>nul
DEL /F /S /Q /A %LocalAppData%\Microsoft\Windows\Explorer\thumbcache_*.db
timeout 2 /nobreak>nul
start "" %windir%\explorer.exe
start "" %windir%\explorer.exe "Folder To Update"

A: The proper way to do something like this is to use the SHChangeNotify() function. If you're using C#, you can p/invoke it like so:
[DllImport( "Shell32.dll", CharSet = CharSet.Auto, SetLastError = true )]
static extern void SHChangeNotify(uint wEventId, uint uFlags, [MarshalAs(UnmanagedType.LPWStr)] string dwItem1, IntPtr dwItem2);

...and then use it to notify Explorer that an item has been modified (i.e. the image that you manipulated):
private const uint SHCNE_UPDATEITEM = 0x00002000;
private const uint SHCNF_PATHW = 0x0005;
private const uint SHCNF_FLUSH = 0x1000;

string pathName = "your image file.jpg"

SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATHW | SHCNF_FLUSH, pathName, IntPtr.Zero);

A: Increasing the file modified date by 1 sec and then changing it back triggers Windows into thinking the file has changed so that the thumbnail is updated. Code used is
DateTime modDate = System.IO.File.GetLastWriteTime(sFile);
System.IO.File.SetLastWriteTime(sFile, modDate.AddSeconds(1.0));
System.IO.File.SetLastWriteTime(sFile, modDate.AddSeconds(-1.0));


text:
Q: Split column by separator and delete values contained in other values I have a category column that is separated by ";". I.E Value:
value <- "A > B > C; A > B > D; A > B > C > C1"

It means:
The current product belongs to category "A > B > C", to category "A > B > D" and to category "A > B > C > C1"
If a category is already contained in another, this should be removed. So the goal is:
expectedResult <- "A > B > D; A > B > C > C1"

because "A > B > C > C1" is containing "A > B > C".
How can I solve this?
Note: I know that there are hundreds of questions that seem similar. But I just couldn't find a solution.

A: This ought to work:

value <- "A > B > C; A > B > D; A > B > C > C1"
els <- strsplit( value, "; " )[[1]]

my_reducer  <- function(a,b) {
    v <- str_detect( b, fixed(a) )
    a <- a[!v]
    append(a,b)
}

paste( Reduce( my_reducer, els ), collapse="; " )

Output:

> Reduce( my_reducer, els )
[1] "A > B > D; A > B > C > C1"

A: Perhaps you can try the code below
v <- unlist(strsplit(value, ";\\s+"))
idx <- colSums(`diag<-`(sapply(v, function(x) {
  p <- gsub(x, "", v, fix = TRUE)
  p != v & nchar(p) > 0
}), FALSE)) == 0
paste0(names(idx)[idx], collapse = "; ")

which gives
[1] "A > B > D; A > B > C > C1"


text:
Q: Sifting out Solutions to Differential Equations I am wondering, is there a general method one uses to seek methods of solutions without much strenuous work and calculations, and possibly a way to get non-trivial solutions for PDE's.
A simple counter example would be:

Suppose we are given: $\dfrac{\partial u}{\partial x}-2u = 0$

And are asked to find solutions that would satisfy this equation. Well a sort of trivial solution would be to say, suppose we let $u=e^{2x}$. This would imply from the equation that, $$2e^{2x}-2e^{2x}=0.$$
Now we all know that this would not be the case for much tougher equations to begin with, especially non-linear equations. What I want to find out is, is there a systematic manner of sifting out the other solutions that are more non-trivial without a great deal of work. Maybe like some common trick or something. It is sort of like for ODE's of certain type, we can expect an exponential form of a solution.

A: There is no general rule to find solutions for PDE's. However, there are special types of solutions that may help when looking for particular solutions. In many cases, these special solutions are the ones of physical interest, or describe the cualitative behviour of the general solution. A non comprehensive list of special type of solutions follows. I asume a PDE with independent variables $t\in\mathbb{R}$ (time) and $x=(x_1,\dots,x_n)\in\mathbb{R}^n$ (space).

*

*Stationary solutions: solutions that do not depend on time.

*Solutions in separeted variables: solutions of the form $T(t)\,X(x)$. They are the base of the Fourier method for solving initial and boundary problems for linear PDE's.

*Radial solutions: solutions with rotational symmetry of the form $u(r,t)$ where $r=|x|$.

*Self similar solutions: solutions invariant under the action of a group of transformations of the form $T_\lambda u(t,x)=\lambda^au(\lambda^b\,x,\lambda^c\,t)$ for some $a,b,c\in\mathbb{R}$.

*The previous two are particular examples of solutions invariant under the action of a Lie group. A reference is the book Applications of Lie Groups to Differential Equations by Peter J. Olver.

*Travelling waves: solutions of the form $u=\phi(x-c\,t)$. They are solutions with a fixed profile that travels at speed $c$.

*...


text:
Q: printing the largest value in array I was having a trouble regarding to printing out the largest number in array in c language and i don't know how to do it while using loop. Please help me thanks
here is my code
#include <stdio.h>
void main() {

    int Lnum, size;

    printf("Enter the size: ");
    scanf("%d", &size);

    int nums[size];

    for (int i = 0; i < size; i++) {
        scanf("%d", &nums[i]);
    }
    printf("\nReversed = ");
    for (int i = size - 1; i >= 0; i--) {
        printf("%d ", nums[i]);
    }

    for (int a = 0; a < size; a++) {
        for (int i = 0; i < size; i++) {
            if (nums[a] > nums[i]) {
                Lnum = nums[a];
            }
        }
    }
    printf("\nLargest element = %d", Lnum);
}

A: The algorithm for determining the largest element in an array goes as follows.

*

*Use the value of the first array element as a start value for the biggest number.

*Go over the rest of the array and check for each element if it is a bigger number.

*When a bigger number is found use the bigger number for further comparisons.

    #include<stdio.h>
void main(){

  int Lnum, size;

    printf("Enter the size: ");
    scanf("%d", &size);

    int nums[size];

    for(int i=0; i<size; i++){
      scanf("%d", &nums[i]);
    }
    printf("\nReversed = ");
    for(int i=size-1; i>=0; i--){
      printf("%d ", nums[i]);
    }

    Lnum = nums[0]; // Assume first element to be the largest element
    for(int a=1; a<size; a++){ // start loop with second element
      if(Lnum < nums[a]) { // check if current element is larger
        Lnum = nums[a]; // found larger element, it is now the largest element of all inspected element
      }
    }
    printf("\nLargest element = %d", Lnum);
}

Output:
Enter the size: 3
1 2 3

Reversed = 3 2 1
Largest element = 3

...Program finished with exit code 0


text:
Q: Need help for retrofit login example? http://172.16.7.203/sfAppServices/SF_UserLogin.svc/rest/login/
in this username and password is part of it i need to post the user entered username and password from edittext and getting json response like this
{"Result":"1","UserID":"0"}

how to get that json using retrofit . I have successfully made this with asynctask .  But feeling quite difficult to implement through retrofit.
my question is

*

*Which is the base url?

*in interface which should be exposed in post method.

*How can i get the json response from rest service through json .

Below is my main activity:
 package com.example.first.servicefirst;

 import android.app.Activity;
 import android.app.AlertDialog;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.ProgressBar;
 import android.widget.TextView;
 import android.widget.Toast;

 import retrofit.Callback;
 import retrofit.GsonConverterFactory;
 import retrofit.Response;
 import retrofit.Retrofit;

 public class MainActivity extends Activity {
EditText password,userName;
Button login,resister;
ProgressBar progressbar;
TextView tv;

 String url="http://172.16.7.203/sfAppServices/SF_UserLogin.svc/rest/login/";

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    password=(EditText) findViewById(R.id.password);

    userName=(EditText) findViewById(R.id.txtEmployeeCode);

    login=(Button) findViewById(R.id.btnsignin);
    userName.setBackgroundResource(R.drawable.colorfoucs);

    //progess_msz.setVisibility(View.GONE);
    ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nf=cn.getActiveNetworkInfo();
    if(nf != null && nf.isConnected()==true )
    {
        Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();

    } else {
      showAlertDialog(MainActivity.this,"No Network","Please Check Your Network Connectivity",true);
    }

    final   ConnectionDetector    cd = new ConnectionDetector(getApplicationContext());

    login.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            progressbar = (ProgressBar) findViewById(R.id.progressBar);
            progressbar.setVisibility(View.VISIBLE);

          login();

        }
    });

}

public void showAlertDialog(Context context, String title, String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting alert dialog icon

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });

    // Showing Alert Message
    alertDialog.show();
}
public void login(){
Retrofit retro = new
Retrofit.Builder().baseUrl("http://172.16.7.203").addConverterFactory(GsonConverterFactory.create()).build();
RetrofitRest retrofitRest = retro.create(RetrofitRest.class);
String s1 = userName.getText().toString();
String s2 = password.getText().toString();
if (s1.equals("")) {
    userName.setError("Enter User Name");
}
if (s2.equals("")) {
    password.setError("Enter Password");
}

retrofitRest.login(s1,s2, new Callback<ModelLogin>() {
    @Override
    public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
        Intent intent = new Intent(MainActivity.this, Main2Activity.class);
        startActivity(intent);
    }

    @Override
    public void onFailure(Throwable t) {

    }
});
 }
 }

Below is my interface:
 public interface RetrofitRest {
@FormUrlEncoded
@POST("/sfAppServices/SF_UserLogin.svc/rest/login/")
Callback<ModelLogin> login(@Query("empcode") String employeecode, @Query("password") String password,
Callback<ModelLogin> callback);
 }

My pojo:
 package com.example.first.servicefirst;

import com.google.gson.annotations.SerializedName;

public class ModelLogin {

private String empcode;
private ModelLogin(){}
@SerializedName("Result")
private String result;
public String getResult(){
    return result;
}
private String password;
public String getEmpcode() {
    return empcode;
}

public String getPassword() {
    return password;
}

public void setEmpcode(String empcode) {
    this.empcode = empcode;
}

public void setPassword(String password) {
    this.password = password;
}

}

A: Since your request parameters are path parameters you do not need a DTO for your request. Just create a DTO for your response like this.
public class LoginResponseDto {
    @SerializedName("Result")
    private String result;
    @SerializedName("UserID")
    private String userId;

    // Getters & Setters etc.
}

And lets parse your URL and create your service interface. I think your base url will be "http://172.16.7.203/sfAppServices/" and other are for service identification. It highly depends on other services you may want to use. If you are just using login service you can even make your base url like this "http://172.16.7.203/sfAppServices/SF_UserLogin.svc" but these decisions change your service annotations.
public interface LoginService{
    @POST("/SF_UserLogin.svc/rest/login/{employeeCode}/{password}") // Assume your base url is http://172.16.7.203/sfAppServices/
    public void login(@Path("employeeCode") String employeeCode, @Path("password") String password, Callback<LoginResponseDto> callback);
}

And at last your retrofit instance. You should not create your Retrofit instance over and over again. Instead create it in your application or use a singleton pattern and get LoginService when you need it.
Update
Since you are using Retrofit 2 you should use a service like this.
public interface LoginService{
    @POST("/SF_UserLogin.svc/rest/login/{employeeCode}/{password}") // Assume your base url is http://172.16.7.203/sfAppServices/
    public Call<LoginResponseDto> login(@Path("employeeCode") String employeeCode, @Path("password") String password);
}

A: Write below code in your Activity
private void callLoginApi()
{

    ApiListeners apiListener;

    Retrofit retrofit = Retrofit.Builder().baseUrl("http://172.16.7.203/sfAppServices/SF_UserLogin.svc/rest/").build();

    apiListener = retrofit.create(ApiListeners.class);

    apiListener.loginUser("test@test.com", "123456",new Callback<String>()
        {
            @Override
            public void success(String response, retrofit.client.Response arg1)
            {
                CommonUtills.dismissProgressDialog();
                if(response != null && !response.isEmpty())
                {
                    // Do what you want after getting success
                }
            }

            @Override
            public void failure(RetrofitError error)
            {
                // Do what you want after getting failure
            }
        });
}

Callback you can change this according to your need
You need to create one interface in which you need to create login API call method
@FormUrlEncoded
@POST("/login")
public void loginUser(@Field("email") String email,@Field("password") String password,retrofit.Callback<String> response);


text:
Q: Firefox focus() sets the focus and blurs immediately I have a <span class="numbers"> and this code for on Click, it creates a new <input class="number_input"> field and sets the focus on it:
            $('body').on('click','.numbers', function () {
                oldNumbersValue = $(this).html();
                var input = $('<input />', {'style':'font-size:30pt','type': 'number','class':'number_input', 'name': 'aname', 'value': oldNumbersValue});
                $(this).parent().append(input);
                input.focus();
            });

When the field loses the focus, it will be removed:
 $('body').on('blur', '.number_input',function () {
// do something
 $(this).remove();
});

This works in Chrome but not in Firefox! In Firefox it creates the field, sets the focus on it and loses it immediately!
Any solutions?
edit:
working in chorme/not working in ff fiddle:
https://jsfiddle.net/v8hmpgv2/

A: The problem here is that (for a reason I'm not 100% sure of), Firefox is triggering the blur event on .number_input after the element has been appended to the document, but before your focus() actually calls.
You can see this happening in Firefox with this JSFiddle demo - note the order of the messages indicating when focus is set and lost on .number_input.
One way you could modify the code is to not use event delegation, and rather attach the blur handler directly to .number_input:
$('body').on('click', '.numbers', function (e) {
    oldNumbersValue = $(this).text();
    var input = $('<input />', {
        'style': 'font-size:30pt',
        'type': 'number',
        'class': 'number_input',
        'name': 'aname',
        'value': oldNumbersValue
    });
    $(this).parent().append(input);

    input.focus();
    input.blur(function(){
        $(this).remove();
    });
});

Here's a working JSFiddle to demonstrate. (Don't worry about any potential memory leakage due to constantly adding new event handlers - the jQuery docs indicate that .remove() should erase those each time.)
Hope this helps! Let me know if you have any questions.


text:
Q: Add fields and query manually to existing single group layout I already have a group called G_1 in my report and the entire fieldset required for the report are present in G_1.
Now, I have a new requirement which needs data from different tables and hence I created a new query using "Data wizard" and a group called G_2 was created as well.
I don't want to affect the layout of the existing report(every field is in a single repeat frame) and wanted to add my new fields as well
I added fields and mapped the data, but then I got error saying "field references column below its group frequency"
So I have to bring the column under the existing group G_1 without using report wizard.
Any leads would be of big help!

A: If I understood what you are saying, that won't work.
If you created a new query, it has its group (G_2) and fields selected within that query have to belong to G_2 group. In Paper Layout, by default, every query has the outer frame (M_2), it contains a repeating frame (R_2) and fields have to be part of those frames.
If you set flex off and confine off (so that you could drag fields here and there, even out of its boundaries (frames) and actually do that - drag a field to, say, R_1 frame (which is part of M_1 which belongs to query 1), you'll get that error.
So, what to do?
If possible, the simplest option would be to adjust query Q_1 and add those new fields in there. If not, you'll have those two queries.
One option is to put query 2 objects (frames, fields) below the ones that belong to query 1 (so that they are unrelated). Another is to stretch query 1 frames "down" and make space for query 2 objects. Then you'd draw a M_2 frame (paint it white so that you can easily see what's going on). Within M_2, draw a repeating frame R_2 and paint it yellow. It has to be contained in M_2. Now, create the first field within the R_2 repeating frame. Check the Object Navigator - everything has to be in its place. If it is not, you'll have to move objects backwards (or forward).
Run the report - if it works OK, fine - go on to the next field, and so forth. Test frequently. Once you're done, make it prettier - move everything to its right place, remove painting and - that's it.

On the other hand: as there's only one frame you currently have (I don't know how many fields there are and how complex the layout is), if you are an unexperienced Reports user, your best option is to delete current layout and let the Wizard do the job. It'll certainly ruin everything you've done so far, but it has its advantages - all objects will be on their proper places. Might be time consuming, but adjusting fields and headings and stuff could be simpler and easier.
Unfortunately, there's no easy way to do it. Takes time to gain experience, but - if you have it - go for it. How will you learn how to do it if you actually don't do it?
Best of luck!


text:
Q: GLIBCXX not found in local built libstdc++.so.6 GCC10.2.0 on REHL7.4 and CentOS8 I have two servers one of which is running RHEL 7.4 and the other one is CentOS 8
the RHEL comes with gcc 4.8.5 and libc.so.6 at 2.17
the CentOS comes with gcc 8.3.1 and libc 2.28
I built a GCC 10.2 on both server and install to customized path something like /dist/gcc/10.2.0
to built the GCC 10.2, I also built gmp 6.2.0, mpc 1.1.0 and mpfr 4.0.2, those three libs are also install under my customized path like /dist/gmp/6.2.0..
things has been smooth on both servers for a long time, I built all kinds of customized library on both REHL and CentOS with my brand new GCC10.2.
However last week I started to build a simple C++ application which links a 3rd party lib( shared object) built with old gcc(4.7 4.8 likely), I know there could be ABI issues so I took that seriously and tried building on both servers.
The result is surprising, without D_GLIBCXX_USE_CXX11_ABI=0, CentOS environment builds smoothly
but the REHL one complains with something like /......./linux64-demo/../../libs/LINUX64/libsomething.so: undefined reference to `std::ostream::operator<<(double)@GLIBCXX_3.4' which I believe has something to do with ABI, or linking wrong lib, I tried both with and without flag D_GLIBCXX_USE_CXX11_ABI, the result is same.
So I did
strings /dist/gcc/10.2.0/lib64/libstdc++.so.6 | grep GLIBC
'''
GLIBCXX_3.4
GLIBCXX_3.4.1
GLIBCXX_3.4.2
GLIBCXX_3.4.3
GLIBCXX_3.4.4
GLIBCXX_3.4.5
GLIBCXX_3.4.6
GLIBCXX_3.4.7
GLIBCXX_3.4.8
GLIBCXX_3.4.9
GLIBCXX_3.4.10
GLIBCXX_3.4.11
GLIBCXX_3.4.12
GLIBCXX_3.4.13
GLIBCXX_3.4.14
GLIBCXX_3.4.15
GLIBCXX_3.4.16
GLIBCXX_3.4.17
GLIBCXX_3.4.18
GLIBCXX_3.4.19
GLIBC_2.3
GLIBC_2.2.5
GLIBC_2.14
GLIBC_2.4
GLIBC_2.3.2
GLIBCXX_DEBUG_MESSAGE_LENGTH

'''
and I did the same on the REHL server
'''
GLIBC_2.2.5
GLIBC_2.3
GLIBC_2.14
GLIBC_2.6
GLIBC_2.4
GLIBC_2.16
GLIBC_2.17
GLIBC_2.3.2
GLIBCXX_FORCE_NEW
GLIBCXX_DEBUG_MESSAGE_LENGTH
__strtof_l@@GLIBC_2.2.5
symlink@@GLIBC_2.2.5
chdir@@GLIBC_2.2.5
fileno@@GLIBC_2.2.5
pthread_cond_destroy@@GLIBC_2.3.2
__strcoll_l@@GLIBC_2.2.5
__nl_langinfo_l@@GLIBC_2.2.5
dgettext@@GLIBC_2.2.5
fseeko64@@GLIBC_2.2.5
wmemcpy@@GLIBC_2.2.5
memset@@GLIBC_2.2.5
mbrtowc@@GLIBC_2.2.5
wcslen@@GLIBC_2.2.5
close@@GLIBC_2.2.5
__duplocale@@GLIBC_2.2.5
ioctl@@GLIBC_2.2.5
abort@@GLIBC_2.2.5
......

'''
it looks like the libstdc++.so.6 I built on REHL does not contain GLIBCXX3.4
even thou both hosts were building the exact same GCC10.2.0 with same dependencies.
Does it have anything to do with the glibc that comes with the OS? Do I need to build a newer glibc on REHL and then rebuild GCC linking with the new glibc to solve this?

A: after a whole weekend trail and error, I found that the reason behind all these is
because of the aging binutils that comes with the OS
I was inspired by this post
https://unix.stackexchange.com/questions/596280/no-version-symbols-in-freshly-compiled-libstdc
simply build a newer version binutils and use that to build the gcc 10.2 solves all these problems.

A: This worked for me on CentOS Stream 8. (originally not from me)

*

*wget https://repo.anaconda.com/archive/Anaconda3-2019.07-Linux-x86_64.sh

*sh Anaconda3-2019.07-Linux-x86_64.sh

*cp anaconda3/lib/libstdc++.so.6.0.26 /usr/lib64

*rm /usr/lib64/libstdc++.so.6

*ln -s /usr/lib64/libstdc++.so.6.0.26 /usr/lib64/libstdc++.so.6
To Check:

*

*strings /usr/lib64/libstdc++.so.6 | grep GLIBCXX


text:
Q: Create separate template for shared custom taxonomy with shared terms I have created custom taxonomy called "product_category", it has been shared with post type "books" and "movies" .
So I need to create a different template for both post types.
Both the templates' design will be different, so its important that both the post_type shared taxonomy (even their terms will be shared in both the post_type.) should have different template .
Path should be like :-

site/books/product_category/horror/
site/movies/product_category/horror/

A: See, It's quite difficult to have path like

site/books/product_category/horror/
site/movies/product_category/horror/

As wordpress functionality will conflict between custom_post_type & their taxonomy if try to keep url like you mentioned. I suggest you consider the I mentioned below as a solution of your problem.

site/product_category/horror/?post_type=books
site/product_category/horror/?post_type=movies

Now to keep template as per shared terms, Create two templates in your theme directory.

*

*common-term-books.php

*common-term-movies.php

And, use this code to redirect to template on the basis of custom post type:
add_filter( 'template_include', 'wpse_152146_template_override', 99 );
function wpse_152146_template_override(){
    if (is_tax()) {
        if ( 'books' == $_GET['post_type']) {

            $new_template = locate_template( array( 'common-term-books.php' ) );
            if ( '' != $new_template ) {
                return $new_template ;
            }

        }
        elseif ( 'movies' == $_GET['post_type']) {

            $new_template = locate_template( array( 'common-term-movies.php' ) );
            if ( '' != $new_template ) {
                return $new_template ;
            }

        }
        else
            return $template;
    }
    else
        return $template;
}

Additionally, You can also use custom_term_link function i created to get url on the basis of post_type
function get_custom_term_link( $term, $taxonomy, $post_type ){
    $link = get_term_link( $term, $taxonomy );
    return $link.'?post_type='.$post_type;
}

get_custom_term_link( 'horror', 'product_category', 'books');

Don't forget to create template file common-term-books.php & common-term-movies.php. Otherwise, it'll just show blank white screen.


text:
Q: UITextView or something else? need help in understanding i'm writing a small app to train myself and i need a little help.
can anyone give me an advice how to make this construction like on the picture bellow?
i'm interested about "Description" section. i want to make the similar thing in my app. some text in preview..button "more" and when i click it the whole text will appear on the screen. also i want to have the same button "hide" that returned me to the preview.
i need UITextView or smth else?

A: rmaddy is right, UILabel is the way to go.
You need to hide the More button, and show a  Hide (or Less?) button and the label when the user taps. You also need to change the row's height to accomodate for the new content.
To find the appropriate height for the table's row, use either [UILabel sizeToFit] or [UILabel sizeThatFits].
To animate the height change of the row, have a look at Can you animate a height change on a UITableViewCell when selected?


text:
Q: Can't import from python module md5hash I'm getting an error that python "cannot import name 'scan' from 'md5hash' and then references the path (C:\Users\Misha\AppData\Roaming\Python\Python37\site-packages\md5hash__init__.py)
This seems to happen for all modules, not just md5hash.  Originally I had read that this was a bug with PyCharm IDE, so I ditched that, but I'm seeing the same problem in IDLE.  I have tried reinstalling the module and checking to see if something is inside init.py, but it is a blank file, as expected.  Still not sure what's going on here.
from md5hash import scan
path = input("Enter the absolute path to your files: ")
print(scan(path))

EDIT:  Think I may have discovered the source of the problem: http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html#the-init-py-trap... Will report back if / when I've fixed it.
EDIT2: Well I reinstalled pycharm, python, and pip.  I read that reinstalling the md5hash module directly from within PyCharm will help, but I'm still getting a similar error and my code will not run:  "Cannot find reference 'scan' in 'init.py'."  I read that simply disabling the IDE warning for uncaught references will resolve this, but so far no luck.
EDIT3: added an all statement to the beginning of the init file and restarted pycharm.
__all__ = ['size', 'calculate', 'scan', 'md5', 'Profiler']

Still not working.  And the problem appears to be with all modules.  It's doing it with numpy, as well.


text:
Q: Run Putty command from python I currently have a .sh file from which I run a command called metl.
metl is a python package which helps with the extraction, transformation and loading of data from almost any source.
The normal procedure I need in the putty console and works fine is the following:
metl -m migration.pickle1
     -t migration.pickle2
     -s filename.csv
     config_file.yml

The procedure that I run from my .sh file, and also works properly is the following:
metl -m migrationfiles/"${migbefore}" \
    -t migrationfiles/"${migafter}" \
    -s "${y}" \
    config_file.yml

Sorry I was not clear enough before, in general I want to run a Python script from the PuTTY console, and from inside this Python script I need to run a PuTTY command, which is the one I mentioned before (metl -m migration.pickle1....)
So what I am trying to run is this:
import os

os.system("metl -m " + path + ""\"" + migbefore + "-t " + path + ""\"" + migafter + "-s " + csvfile + " " + directory + ""\"" + config_file.yml)

A: I would suggest to use:
import subprocess
proc_args = ['metl', '-m', 'arg2', ....]
process = subprocess.Popen(proc_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)