text:
Q: How do I constantly check if my if statement returns true or false I am trying to constantly check for any update on the page. I want to influence the second object on the page by checking if the user clicks a button that makes first object display as a block
So user click button > first object displays block > the second object should move.
how do I constantly check for any changes in Javascript?
I currently have this
const button = document.querySelector("button")
const firstObject = document.querySelector(".first-object")

button.addEventListener("click", function(){
   if(firstObject.style.display === "none"){
      firstObject.style.display = "block"
    } else {
      firstObject.style.display = "none"
    }
})

So this sets the ".first-object" div to block or hides it , Now I want my second div to get a margin-top of 50px when the ".first-object" is set to block
and so I added this
    const secondObject= document.querySelector(".second-object")

    if (firstObject.style.display == "block"){
        secondObject.style.marginTop = "50px";
    } else {
        secondObject.style.marginTop = "0";
    }

But this part doesnt constantly check if the other value returns true. How do I achieve this?
Sorry for my noobish question and thanks in advance!

Here is a jsfiddle link for the part I am trying to achieve.
https://jsfiddle.net/wvy7rhuc/
PS: fixed the type error on from
if (firstObject.style.display = "block")
to
if (firstObject.style.display === "block")

A: You have a simple typo –
if (object.style.display = "block"){

is an assignment and will be truthy and
if (object.style.display == "block"){

is the comparison you're looking for.

A: The above answer by @AKX is correct and I want to give you some extra explanation.
In JavaScript,
 = is used for assigning values to a variable.
 == is used for comparison between two variables irrespective of the datatype of variable.
 === is used for comparison between two variables but this will check strict type, which means it will check datatype of two values.

Let's see the above in examples.
 var number = 100;  // Here 100 is assigned using to variable using =

 **Example of ==**

 if (number == 100)  // Here comparison between two values using ==. It will compare irrespective of datatype of variable
     alert("Both are equal");
 else
     alert("Both are not equal");

 **Example of ===**

 if (number === 100)  // Here comparison is happening between two values using ===. It will compare strictly means it will check datatype as well.
     alert("Both are equal");
 else
     alert("Both are not equal");

A: I believe that you should place the second (if) statement inside the event listener which will allow the (if) statement to constantly check both (if) statements.
Here is my suggestion JS code.
    const button = document.querySelector("button")
    const firstObject = document.querySelector(".first-object")
    const secondObject = document.querySelector(".second-object")

    button.addEventListener("click", function(){
       if(firstObject.style.display === "block"){
          firstObject.style.display = "none"
        } else {
          firstObject.style.display = "block"
        }

        if (firstObject.style.display == "block"){
          secondObject.style.marginTop = "50px";
        } else {
          secondObject.style.marginTop = "0";
        }
    })


text:
Q: CCRenderTexture size and position in Cocos2d-iphone I was trying to use CCRenderTexture for pixel perfect collision detection, as outlined in this forum posting:
http://www.cocos2d-iphone.org/forum/topic/18522/page/2
The code "as is" works, and I have integrated it with my project
But I am having trouble doing some of the other things discussed:
If I create the renderTexture to be any size less than the screen size, the collision detection doesn't work properly - It seems to show collisions when the sprites are close (<15px) to each other but not actually colliding.
Also I have trouble changing the location of the render texture. Regardless of the position I specify, it seems to go from bottom left (0,0) till the width & height specified. I followed this post:
http://www.cocos2d-iphone.org/forum/topic/18796
But it doesn't solve my problem. I still get bad collisions like specified above. Also, the first post I mentioned on the list contains comments by many users who have resized their textures to 10x10, and repositioned them off screen.
Does anyone have any sample code, so I can see what I am doing wrong? I just use the boilerplate code:
    CCRenderTexture* _rt = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];

    _rt.position = CGPointMake(winSize.width*0.5f, winSize.height*0.5f);
    [[RIGameScene sharedGameScene]addChild:_rt];
    _rt.visible = YES;

I use cocos2d-iphone 1.0.1

A: You need to move the sprites you intend to draw into the region of the renderTexture before calling draw or visit. Moving the renderTexture does not change the position of _rt.sprite.
The intersection rectangle must be in the region of the renderTexture, otherwise you get inaccurate collisions.
It seems that you cannot change the position of _rt.sprite.
The solution that I use is to determine the origin (x,y) of the intersection box, and offset both the colliding sprites by that much. This will ensure that the intersection rectangle will have its origin at 0,0.  Then I calculate the intersection rectangle again (after ensuring the origin of the intersection rect is 0,0) . Then I follow the instructions in the forum posting.
When determining the dimensions of the render texture, I ensure that they are at least as large as the intersection rectangle, and I ensure that the intersection rectangle is fully inside the render texture. This way there are accurate collisions. If even part of the intersection box is outside the render texture i get inaccurate collisions, so before drawing into the render texture, make sure you move the sprites you intend to visit so that the intersection box is entirely within the render texture.
Remember to move the sprites back after you're done. :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Way to save nested dictionary data to django model my dictionary
{
id : 123
"data":{
    "name" : "sample name"
    "description" : "sample discriptio"
    "address":{
        "address": {
            "h.no" : '420'
            "streat": 'some streat'
        }
        "city" : "Hyd"
        "State" : "S"
        "Country": "xyz"
    }
    "geoLocation":{
        "latitude": 40.0000,
        "longitude": -118.0000

    }
    "links":
    [
        {"rel": "image", "url":"http://image.com/1.jpg"},
        {"rel": "image", "url":"http://image.com/2.jpg"},
        {"rel": "some other", "url":"http://some/other/url"},
    ]

}
}

and here is my model:
class my_model(models.Model):
    name = models.CharField(max_length=255)
    latitude = models.DecimalField(max_digits=55, decimal_places=20)
    description = models.TextField()
    longitude = models.DecimalField(max_digits=55, decimal_places=20)
    h_no = models.CharField(max_length=255)
    streat = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=55)
    state = models.CharField(max_length=25)
    postal = models.CharField(max_length=25)
    country = models.CharField(max_length=25)
    currency = models.CharField(max_length=25)
    updatedOn = models.DateTimeField(auto_now=True)
    images_links = models.ManyToManyField(rental_images)

    def __unicode__(self):
        return self.name

Add_or_Update_view logic:
instance = mymodel.objects.get_or_create(id=id)
for key,value in data['data'].items():

    field = mymodel._meta.get_field(key)
    if not field:
        continue
    if isinstance(field, models.ManyToManyField):
        # to handle ManyToManyField fields, like skils ['java', python]
    elif isinstance(field, models.ForeignKey) and hasattr(value, 'items'):
        # to handle ForeignKey fields
        setattr(instance, key, rel_instance)
    else:
        setattr(instance, key, value)
instance.save()

with data['data'].items() not possible to get all child dict key, values to use in setattr(instance, key, value) for fields like h_no, streat, latitude, longitude(these values are in nested dictionaries).
above dictionary has links list in that i want save all 'rel':'image' my images = models.ManyToManyField(images_model)
Is there any best approach to save directly date to django model.
and how to handle model relations while saving data.


text:
Q: If Function with Multiple Text Criteria in Same Cell I've got an google sheet that I copy paste into an excel sheet.
One of the columns in the google sheet contains options that a client selected out of; Lift Pass, Rentals, Lessons, and Helmet
The selected options (Lift Pass, Helmet, Rentals, Lessons) are in one cell, with the client info in separate cells.
What I'm trying to do is have an If function return 1 if certain products are selected.
Currently I can get the function to work if there's only one product selected (I.e. "Lift Pass" only), but I can't figure out how to make it work with multiple products selected.
My working functions:
Lesson Only:
=IF(AND(NOT(OR('Paste Here'!B2="Lift Pass",'Paste Here'!B2="Rentals")),'Paste Here'!B2="Lessons"),1,"")

Rental Only:
=IF(AND('Paste Here'!B2="Rentals",NOT(OR('Paste Here'!B2="Lift Pass",'Paste Here'!B2="Lessons"))),1,"")

Lift Pass only:
=IF(AND('Paste Here'!B2="Lift Pass",NOT(OR('Paste Here'!B2="Rentals",'Paste Here'!B2="Lessons"))),1,"")

The products are listed in the B:B column. I've tried a SUMIF, COUNTIF and a few others only to receive #VALUE back. Each client should end up with a 1 under the column that specifies what products they've ordered.
This is the data I'm working with:

Help?

A: If your formula is on google sheets, use REGMATCH.
If your formula is in Excel, then use SEARCH.
The example I set up was to enter "Rentals, Helmet, Lessons" into cell A1.

*

*In google sheets then, in cell B1 I used the formula =if(REGEXMATCH(A1,"Helmet"),1,"").

*In Excel then, in cell B1 I used the formula =IF(IFERROR(SEARCH("Helmet",A1),0)>0,1,"")
The SEARCH formula will return an error if the string is not found in the cell, so it must be handled similar to the example.
You can stack these up in If statements as much as needed. As an example, if you need to detect if three of the products are present, stack up the IF statements (in Excel) like this:
=IF(IFERROR(SEARCH("helmet",A1),0)>0,IF(IFERROR(SEARCH("rental",A1),0)>0,IF(IFERROR(SEARCH("lift pass",A1),0)>0,1,""),""),"")


text:
Q: Ayuda! diferencia entre form action y $http.post() Buen día, tengo un formulario en el cual los valores que capturo en el necesito enviarlos a un controlador. Dicho controlador en mvc asp.net me retorna una nueva vista como respuesta.
Mi pregunta es, mediante $http.post(), puedo obtener esa vista que me retorna el controlador?. o necesariamente debo utilizar el form action desde el HTML para obtener esa nueva vista?
Asi como lo tengo, realiza la petición post, el controlador hace lo que tiene que hacer, pero no me retorna la nueva view().
Este es mi formulario:

DATOS

Ingrese datos:

 Codigo: <input type="text" id="codigo"/>

 Nombres: <input type="text" id="nombres"/>

 Apellidos: <input type="text"id="apellidos" />

 Correo: <input type="text" id="correo" />

 Estado: <input type="number" id="estado"/>

    <button ng-click="registrar()" name="registrar"> REGISTRAR </button>

Este es el codigo que tengo para la petición en $http.post
angular.module("MyApp", [])
.controller("FirstController", function ($scope, $http) {
    $scope.registrar = function () {
        var req = {
            method: 'POST', url: '/Cliente/Create',
            data: {
                "codigo": document.getElementById("codigo").value,
                "nombres": document.getElementById("nombres").value,
                "apellidos": document.getElementById("apellidos").value,
                "correo": document.getElementById("correo").value,
                "estado": document.getElementById("estado").value
            }
        };
        $http(req).then(function (res) {
        });
    };
});

Y este es mi controlador:
        [HttpPost]
    public ActionResult Create([Bind(Include = "codigo,nombres,apellidos,correo,estado")] clientes e)
    {
            clientes q = new clientes();
            q.create(e);

        return View(q);
    }

A: Tanto el Form como el $http te devolverán lo que sea que envíe el servidor como respuesta.
La diferencia entre los dos es que con el form la respuesta se recibe como una nueva página.
Y con $http lo mismo que con ajax, la respuesta llega como un callback a un objecto en javascript / angular sin refrescar la página.


text:
Q: RxJava flatmap crashing even though onError is present I am trying to debug a crash on Android that occurs when a device does not have a network connection. The crash only occurs sometimes (~50% of the time) and I am not sure why. If anyone can either explain what is going on or give a solution I will be very grateful.
I am using a flat map to fetch images in parallel and I subscribe with an onError() block. Despite this the app still crashes.
Here is the code (I labelled the line it crashes on with "Crash here:"):
fun downloadImages() {
    var progress = 0
    var maxProgress = 0

    downloadModel.postValue(
            Resource.inProgress(getString(R.string.downloading_offline_data)))

    disposables.add(Observable
            .create<Pair<String, File>> { emitter ->
                val files = readFileDirs()

                for (file in files) {
                  val urlList = readUrlListFrom(file)
                  maxProgress += urlList.size

                  for (url in urlList) {
                    emitter.onNext(url to file)
                  }
                }
                emitter.onComplete()
            }
            .flatMap { (url, file) ->
                downloadImage(url, file)
                        .subscribeOn(Schedulers.computation())
                        .andThen(Observable.fromCallable {
                            ++progress
                        })
            }
            .doOnDispose {
                downloadModel.postValue(Resource.idle())
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                Log.d(TAG, "Done downloading $it")

                if (it % 100 == 0) {
                    refreshCacheSize()
                }

                downloadModel.postValue(Resource.inProgress(
                        getString(R.string.downloading_offline_data),
                        it,
                        maxProgress
                ))
            }, { error ->
                val errorId = when (error) {
                    is SocketTimeoutException ->
                        NETWORK_TIMEOUT_ERROR
                    is InterruptedIOException -> {
                        // do nothing
                        return@subscribe
                    }
                    is UnknownHostException ->
                        NETWORK_ERROR
                    is IOException ->
                        UNKNOWN_ERROR
                    is UnsupportedServerVersionException ->
                        UNSUPPORTED_VERSION_ERROR
                    else -> {
                        UNKNOWN_ERROR
                    }
                }
                downloadModel.postValue(Resource.error(errorId))
            }, {
                refreshCacheSize()

                downloadModel.postValue(Resource.success())
            })
    )
}

private fun downloadImage(url: String, outFile: File): Completable {
    val outFileTmp = File(outFile.canonicalPath + ".tmp")
    return Completable
            .create { emitter ->
                val request = Request.Builder()
                        .url(url)
                        .build()
                try {
Crash here:          val response = Client.get().newCall(request).execute()
                    val sink: BufferedSink
                    try {
                        Log.d(TAG, "Writing to file")
                        val body = response.body()
                        if (body != null) {
                            sink = Okio.buffer(Okio.sink(outFileTmp))
                            sink.writeAll(body.source())
                            sink.close()
                        } else {
                            if (!emitter.isDisposed) {
                                emitter.onError(DownloadImageException("Body was null."))
                            }
                        }
                    } finally {
                        response.body()?.close()
                    }

                    outFileTmp.renameTo(outFile)

                    emitter.onComplete()
                } catch (e: Exception) {
                    Log.e(TAG, "Could not save splash", e)
                    emitter.tryOnError(e)
                }
            }
            .doOnDispose {
                outFileTmp.delete()
            }
            .doOnError {
                outFileTmp.delete()
            }
}

Stack trace:
2018-10-08 02:50:07.055 21984-22263/com.ggstudios.lolcatalyst E/AndroidRuntime: FATAL EXCEPTION: RxComputationThreadPool-2
    Process: com.ggstudios.lolcatalyst, PID: 21984
    java.lang.Throwable: Unable to resolve host "mywebsite.com": No address associated with hostname
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:157)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
        at java.net.InetAddress.getAllByName(InetAddress.java:1154)
        at okhttp3.Dns$1.lookup(Dns.java:40)
        at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:185)
        at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:149)
        at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:84)
        at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:214)
        at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
        at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
        at okhttp3.RealCall.execute(RealCall.java:77)
        at com.ggstudios.lolcatalyst.offline.OfflineDownloadViewModel$downloadImage$1.subscribe(OfflineDownloadViewModel.kt:372)
        at io.reactivex.internal.operators.completable.CompletableCreate.subscribeActual(CompletableCreate.java:39)
        at io.reactivex.Completable.subscribe(Completable.java:1918)
        at hu.akarnokd.rxjava2.debug.CompletableOnAssembly.subscribeActual(CompletableOnAssembly.java:39)
        at io.reactivex.Completable.subscribe(Completable.java:1918)
        at io.reactivex.internal.operators.completable.CompletableSubscribeOn$SubscribeOnObserver.run(CompletableSubscribeOn.java:64)
        at io.reactivex.internal.schedulers.ScheduledDirectTask.call(ScheduledDirectTask.java:38)
        at io.reactivex.internal.schedulers.ScheduledDirectTask.call(ScheduledDirectTask.java:26)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.lang.Throwable: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
        at libcore.io.Linux.android_getaddrinfo(Native Method)
        at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:172)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:137)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
        at java.net.InetAddress.getAllByName(InetAddress.java:1154)
        at okhttp3.Dns$1.lookup(Dns.java:40)
        at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:185)
        at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:149)
        at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:84)
        at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:214)
        at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
        at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
        at okhttp3.RealCall.execute(RealCall.java:77)
        at com.ggstudios.lolcatalyst.offline.OfflineDownloadViewModel$downloadImage$1.subscribe(OfflineDownloadViewModel.kt:372)
        at io.reactivex.internal.operators.completable.CompletableCreate.subscribeActual(CompletableCreate.java:39)
        at io.reactivex.Completable.subscribe(Completable.java:1918)
        at hu.akarnokd.rxjava2.debug.CompletableOnAssembly.subscribeActual(CompletableOnAssembly.java:39)
        at io.reactivex.Completable.subscribe(Completable.java:1918)
        at io.reactivex.internal.operators.completable.CompletableSubscribeOn$SubscribeOnObserver.run(CompletableSubscribeOn.java:64)
        at io.reactivex.internal.schedulers.ScheduledDirectTask.call(ScheduledDirectTask.java:38)
        at io.reactivex.internal.schedulers.ScheduledDirectTask.call(ScheduledDirectTask.java:26)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)

A: I figured out both the cause and some possible solutions.
Let's start with the cause first.
My code can be simplified like this: Observable #1 starts off n other Observables that execute on other threads via flatMap().
For simplicity let's assume that all of the Observables execute on their own thread. Then when an error is thrown by one observable, the error is propagated to all of the other Observables and dispose them.
The issue is that this propagation is not synchronized (the reasoning appears to be for performance reasons). Because of this tryOnError() can pass the isDisposed() check, then be disposed, and then fire the error. Which explains why the exception still occurs even though tryOnError() is used.
Some solutions
I ultimately came up with two main solutions after some research and discussion.
One way is to convert all errors into results in the Observables via onErrorReturn(). This solution works but might not be great if you want to halt execution as soon as an error is hit.
The other way to is to register a global error handler and just ignore these errors.
I went with the latter solution however I am not fully satisfied. I really wish there was a way to register a local error handler. Eg. have a method on Observables to ignore errors emitted after disposal of an Observable.
Oh well.


text: Q: How can I force YouTube app on iPad to use the highest video quality all the time? I did select "Higher picture quality" in the settings but by default videos won't play higher than 1080p, even if 1440p and 2160p are available to select manually for that given video. I use iPadOS 15.


text:
Q: Is it possible to save html element changes offline in NW.js? I am working on an simple app which allows user to upload images and videos while doing so automatically generates a
 for each content that was uploaded and wraps it.  Each uploaded picture stays next to the previous one specially stylized.
What I want is to after every upload I make (image or video), it stays there even if I close my app. And if I remove it in the future, naturally it would dissapear.
Is it possible to do it without any local database, if not what is the best way to do it with a database and which module to use?

//image upload

function uploadImage(file) {

  var reader = new FileReader();
  var div_img = $('

');
  reader.onload = function(event) {

    img_url = event.target.result;

    div_img.html((''));
    div_img.appendTo('#wrapper');

  }

  reader.readAsDataURL(file);

}

$("#the-image-file-field").change(function() {

  uploadImage(this.files[0])
});

//video upload

function renderVideo(file) {
  var reader = new FileReader();
  var div_vid = $('

');
  reader.onload = function(event) {

    vid_url = event.target.result;

    div_vid.html(('<video controls><source src="' + vid_url + '" type="video/mp4" /> '));

    div_vid.appendTo('#vid_container');
  }

  reader.readAsDataURL(file);
}

$("#the-video-file-field").change(function() {

  renderVideo(this.files[0])
});

<input type='file' id="the-image-file-field" accept="image/*" />
<input type="file" id="the-video-file-field" accept="video/*" />

A: Interesting question.  There is no correct answer to your question without understanding all the details of your app, but here is some information.
Question:  Is it possible to do this without a local database?
Answer: Yes, it is possible but understand the consequences.
First, consider your goal.  You want the user to have access to the image/file in your application.  There are two main ways this can be done.

*

*The user uploads the image/file to your server (or a binary representation of the image/file)

*The user uploads the path to the image/file on their local machine to your server.  Whenever your app requests this image it will know where to find it on their local machines (assuming the path didn't change)

As you can imagine there are a number of consequences with either, but that is a bit off topic for this question.
Question: How do I persist uploads even if I close the app?
Answer:  This will be dependent on how you handle the first part, but overall this is a much easier task.  This could be easily accomplished using a front-end framework like jQuery, Angular, or many others.  What you will want to do is query your database for the users current collection of images/files, and then for each image/file render it in a particular way on the page.  The actual code for this will vary greatly depending on the framework your choose, but overall the idea of how to do this will be the same.
Other Considerations: If you choose to store all the image/file data on your servers, this could turn into a scaling issue in the future.  What is the benefit of doing it that way instead of using one of the many local storage options built for nwjs (storage options)?
Also, not sure what OS you are running but definitely take a look in your nwjs projects folder.  If you have a mac it will most likely be located at the following path:

*

*Users/YourName/Library/Application Support/Your_Project_Name (matches package.json name)

Many people are unaware of the built in functionality already included with nwjs and that is always a good place to start searching around.

A: A simple way to do this is to store the metadata of the users changes (which images, what order etc.) in localstorage. On startup you then just iterate through the metadata and re-create the html to look like before.
Since you are using nw.js you don't have to worry about limitations on localstorage since you can set the size in the manifest:
https://github.com/nwjs/nw.js/wiki/manifest-format
(look for dom_storage_quota)
Internally nw.js uses sqldatabse for localstorage so this is really just a painless way to get cheap data storage.


text:
Q: Delete rows in dataframe based on 2 column conditional match in separate dataframe I have two data frames DF1 and DF2. I need to remove all rows in DF2 that match both the EEnum and Date from DF1. There are multiple date columns in DF2 but I need Date in DF1 to validate to Date5 in DF2.
DF1:

EEnum
Date

123
01/01/2022

123
06/01/2022

123
06/15/2022

124
01/01/2022

124
01/02/2022

DF2:

EEnum
Date5

123
01/01/2022

123
05/01/2022

123
06/01/2022

123
06/25/2022

124
01/01/2022

124
01/03/2022

Result DF2:

EEnum
Date5

123
05/01/2022

123
06/25/2022

124
01/03/2022

I tried the following but it is removing all rows in DF2 where the Date in DF1 exists regardless of EEnum.
DF2 = DF2.loc[~((DF2.EEnum.isin(DF1['EEnum']))&(DF2.Date5.isin(DF1['Date']))),:]

Any ideas as to where I am going wrong? Or a better way to go about this? Pretty new so any help is appreciated.

A: Use a merge with indicator=True, then filter:
(df2.merge(df1.rename(columns={'Date': 'Date5'}),
           indicator=True, how='outer')
    .query('_merge == "left_only"')
    .drop(columns='_merge')
)

output:
   EEnum       Date5
1    123  05/01/2022
3    123  06/25/2022
5    124  01/03/2022

intermediate (merge only):
   EEnum       Date5      _merge
0    123  01/01/2022        both
1    123  05/01/2022   left_only
2    123  06/01/2022        both
3    123  06/25/2022   left_only
4    124  01/01/2022        both
5    124  01/03/2022   left_only
6    123  06/15/2022  right_only
7    124  01/02/2022  right_only


text:
Q: Does Visual C# 2010 Express need Windows 7 SDK? To create programs with Visual C#, do I need to install the Windows 7 SDK?

A: No, you don't have to.

A: No, you only need the SDK if you want the reference dlls without installing VS 2010.  For example, you might want to install it on a build server.
Well, or if you want anything from the SDK specifically, like the code samples.

A: No, but it does contain useful tools like FxCop, which I find quite useful just for catching silly mistakes that don't break your program, but maybe slow it down or make it more difficult to maintain.


text:
Q: Toggle visibility of sibling element jquery I have several divs on a page. Each div has a heading which I can click to toggle visibility of the corresponding div. The divs are set to display:none by default.
I have used #ids in the click functions of each of the divs , however since I have several divs on the same page. I would want to use  a single .class so that I have a single class thus a single function that controls the visibility.
I am guessing i would then need to use .parent and .sibling classes to do this.
Below is an excerpt from my code:
HTML:

    <legend>

            Div

    </legend>

Div to be shown

JS:
$('#show_table').click(function(){
    $("#toshow").slideToggle();
})

I would think to make this more efficient, so that I don't have to do this for every div using the #ids I would want to know how to use a single .class , probably parent and siblings of it to make this.
As an addition, I would like to have a minus/plus sign toggle functionality on the plus_minus span. I had the same working using the individual ids . How would I be able to achieve this using a single .class. I attempted this using below:
$('.div_show').click( function(){

$(this).parent().next().slideToggle();

if($(this).parent().next().is(':visible'){

$(this).closest('span').find('plus_minus').text('+');

}

else {

$(this).closest('span').find('plus_minus').text('-');

}

 });

However it seems not to work.
Suggestions on how to achieve this +/- toggle functionality appreciated.

A: Why not try this
$('.show_table').click(function(){

    $(this).parent().next().slideToggle();

})

UPDATED CODE
Because you are using SlideToggle the changes to the DOM is not readily updated.. So you have to handle the visibility issues in the callback function of it..
Try this code
$('.show_table').click(function(){
      var $elem = $(this);
      $(this).parent().next().slideToggle('slow', function() {
          if($(this).is(':visible')){
             $elem.find('span').html('+');
          }
          else{
             $elem.find('span').html('-');
          }
      });
})

UPDATED FIDDLE

A: $('#show_table').click(function(){
    $(this).parent().parent().find("div.toshow").slideToggle();
});

A: You can use .parent() to get the legend element, and .next() to get the following sibling (which is your div):
$(".show_table").click(function () {
    $(this).parent().next().slideToggle();
});

If your markup is likely to change in structure, you could make this a little more flexible by using .closest() instead of .parent(), and then using .find():
$(".show_table").click(function () {
    $(this).closest("div").find(".toshow").slideToggle();
});

Here's a working example.

A: You can try this
$('.show_table').on('click', function(){
   $(this).closest('div').find(".toshow").slideToggle();

}) ;

or you can place a class on your container div for title and div like

  <legend>

       Div

   </legend>

Div to be shown

Then you can try this
$('.show_table').on('click', function(){
   $(this).closest('.container').find(".toshow").slideToggle();

}) ;

A: You can try this:
$('.show_table').each(function(){
    $(this).parent().parent().find('.my-toggle-class').slideToggle();
});


text:
Q: Dimension of C(X,R) Let X be an infinite metric space.
Can we say that the dimension of C(X,R) the space of continuous real valued functions on X is infinite?
For spaces like Z,N it's true. But I can't even visualize the space for let's say something like Q.

A: Yes.
Let $X$ be a metric space and fix, for every $n\in \Bbb N$, subspaces $X_n$ of $X$ containing $n$ distinct points. Since $X_n$ is discrete we have that any function $X_n\to\Bbb R$ is continuous, and it's not hard to see that a basis of $C(X_n,\Bbb R)$ is given by the delta functions $\delta\colon X_n\to\Bbb R$ defined by $$\delta_i(y)=\begin{cases}1 & y=x_i\\
0&\text{otherwise}\end{cases},$$ so in particular $\dim C(X_n,\Bbb R)=n$.
Note that $X_n$ is also closed, being a finite union of closed singletons, so by Tietze's extension theorem every function in $C(X_n,\Bbb R)$ can be extended to a function in $C(X,\Bbb R)$, in other words the restriction map $C(X,\Bbb R)\to C(X_n,\Bbb R)$ is surjective, but it is also linear, so $\dim C(X,\Bbb R)\geq \dim C(X_n,\Bbb R)=n$ and since $n$ was arbitrary we conclude that the dimension of $C(X,\Bbb R)$ must be infinite.

A: Fix $n$. We will show that for every $n$, there are  $n$ linearly independent functions in $C(X,\mathbb R)$. Indeed, fix $n\ge 2$ and let $y_1,\dots,y_n$ be distinct in $X$. Set
$$f_j(x) =\prod_{i\ne j} d(x,y_i)$$.
Then $f_j(y_i)=0$ for $i\ne j$ and $f_j(y_j)>0$.
Suppose the linear combination $\sum_{j=1}^n c_j f_j \equiv 0.$ For any $j_0\in \{1,\dots,n\},$
$$0= c_{j_0}\underset{>0}{f_j(y_{j_0})} + \sum_{j\ne j_0}  c_j \underset{=0}{f_j(y_{j_0})} .$$
Therefore  $c_{j_0}=0$. Since $j_0$ is arbitrary, $c_{j}=0$ for all $j$, showing that  $f_1,\dots,f_n$ are linearly independent.


text:
Q: Showing Categories in WordPress loop HI I have added a loop code to a WP page to display a list of thumb of posts.
It works fine, but it shows each post I have published, even if isn't in the categories choosen. It's a problem because some posts shouldn't be showed!
Could you help me please?
<?php  $posts = get_posts('category=Products&numberposts=-1');
            foreach($posts as $post) : setup_postdata($post);
                ?>

<a class="fotoBox" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); the_title(); ?>

            <?php  endforeach; ?>

Posts of category "Products" are showed, posts of categories child of "Products" are showed too, but are showed posts of other categories including "uncategorized".
PS: is printed, below the title of the page, "cat : 11,10,13,14,16,9,12, | " there is method to avoid this printing? thanks to everyone

A: Is "Products" the actual slug of the category you're trying to grab? I would double-check that. You want the category's slug, not its display name.

A: The category has to be the ID not the name. Also, try setting up the get_posts() using an arguments array instead of doing it inline:
<?php
$args = array(
'category' => '*ID*',
'numberposts' => -1
);

$posts = get_posts($args);
foreach($posts as $post) : setup_postdata($post); ?>

       <a class="fotoBox" href="<?php the_permalink(); ?>">
       <?php the_post_thumbnail(); the_title(); ?>

<?php endforeach; ?>

From WordPress Codex - Note: The category parameter needs to be the ID of the category, and not the category name.
http://codex.wordpress.org/Template_Tags/get_posts


text:
Q: Why has the 'total users' count of several beta sites (as listed in Area51) gone down? I'm keeping track of some statistics on 3 beta sites I participate on, by listing bi-weekly the site's statistics from Area 51. I've been doing this for about 4 years but today I noticed that for the first time the 'total users' count of a site went down. This happened on all 3 sites. For example Martial Arts had 5479 users on January 10th, and today it's 5397 users.
For interested people, the historic statistics are in this Sustainability SE Meta post, this Martial Arts SE meta post and this Personal Productivity SE post
Has there been a cleanup of user accounts again (this post says it's not done anymore)? Or has there been a change in how this number is calculated?

A: I deleted a bunch of spam accounts last week; somewhere around 46 thousand network-wide, including 114 users on Martial Arts, 107 on Sustainable Living, and another 114 on Personal Productivity.
There are, of course, plenty of spam accounts left... But this took care of about 4 massive campaigns that had URLs and/or phone numbers listed in thousands of profiles network-wide, so hopefully it'll help make these sites look a little bit less spammy.


text:
Q: The conversion of the varchar value '9000437060' overflowed an int column. Maximum integer value exceeded I'm having trouble figuring out this stack trace, everything is moving away from .NET but because its all tied to a 2000 MSSQL sever that the IT admin isn't willing to upgrade, I still have to deal with some low priority apps that connect with it if something goes wrong. Nomrally I see only one stack, but here there seem to be two. I also can't tell which file it's wanting to me to check because the issue usually is at the top of the stack? I mainly do PHP, so a lot of this is unfamiliar to me.
The stack(s) are here.
[SqlException (0x80131904): The conversion of the varchar value '9000437060' overflowed an int column. Maximum integer value exceeded.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1950890
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4846875
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
   System.Data.SqlClient.SqlDataReader.HasMoreRows() +157
   System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout) +197
   System.Data.SqlClient.SqlDataReader.Read() +9
   System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping) +78
   System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue) +164
   System.Data.Common.DataAdapter.Fill(DataSet dataSet, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords) +353
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +164
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +287
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +94
   MV.Library.UserHandler.GetByMaryvilleID(String maryvilleID) in C:\Code\MV\MV.Library\User.cs:333

[UserException: UserHandler()::Get: UserHandler - The conversion of the varchar value '9000437060' overflowed an int column. Maximum integer value exceeded.]
   MV.Library.UserHandler.GetByMaryvilleID(String maryvilleID) in C:\Code\MV\MV.Library\User.cs:341
   Apps.rewards.administrator.Event.btnAddAttendee_Click(Object sender, EventArgs e) in C:\Code\Web\Apps\Apps\rewards\administrator\Event.aspx.cs:122
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

From what I researched
The app is trying to store more bytes in the column than int type allows. I planned to change the table column to nvarchar or bigint but was wondering if that was all I needed to do? Would nvarchar be the better choice?
Thanks in advance.

A: An int max value range is 2^32 so with sign = -2147483648 to 2147483648 or unsigned 0 to 4294967296 Your value, 9000437060, is larger. You need a long which in SQL is a BIGINT

A: Looks like you are overflowing an int with the value from the database. Try changing your c# data type to long


text:
Q: Multipath Raid 6 - MDADM can't find superblocks - 18.04 I am running a server that connects to a multi-drive disk array,  It is connected in a dual path configuration. Because of this, all of the drives show up twice.
I suffered a power outage and now the array is not assembling.  I do however have the original commands I use.  When I have attempted to assemble it says that there is no superblock.
mdadm: No super block found on /dev/mapper/35000c500415cbb87 (Expected magic a92b4efc, got 00000000)
mdadm: no RAID superblock on /dev/mapper/35000c500415cbb87

I have two questions:

*

*Is it possible to reassemble the array at this point or is any data lost?

*How should I do this properly to avoid this in the future.

Initial commands run:
-Attempted to setup array, realized that I had twice as many drives.
-Learned about multipath
-Built a config that included the excluded the non-multipath drivers (see below)
 - Created a Raid6 array using the /dev/mapper/drives.
Commands:
sudo mdadm --create --verbose /dev/md0 --level=6 --raid-devices=12 /dev/mapper/35000c500415cbb87 /dev/mapper/35000c500415cbbef /dev/mapper/35000c500415cfea3 /dev/mapper/35000c500415d0e3b /dev/mapper/35000c500415d6e3b /dev/mapper/35000c500415e456b /dev/mapper/35000c500415e4e5f /dev/mapper/35000c500415e8223 /dev/mapper/35000c500415ee867 /dev/mapper/35000c5004160b2df /dev/mapper/35000c5004160b6bb /dev/mapper/35000c50041611daf

sudo mdadm -A /dev/mapper/35000c500415cbb87 /dev/mapper/35000c500415cbbef /dev/mapper/35000c500415cfea3 /dev/mapper/35000c500415d0e3b /dev/mapper/35000c500415d6e3b /dev/mapper/35000c500415e456b /dev/mapper/35000c500415e4e5f /dev/mapper/35000c500415e8223 /dev/mapper/35000c500415ee867 /dev/mapper/35000c5004160b2df /dev/mapper/35000c5004160b6bb /dev/mapper/35000c50041611daf

sudo mkfs.ext4 -F /dev/md0
sudo mkdir -p /mnt/md0
sudo mount /dev/md0 /mnt/md0
sudo mdadm --detail --scan | sudo tee -a /etc/mdadm/mdadm.conf
sudo update-initramfs -u

At that point, I setup folders and started using the drive, until the power outage shut it down.  Upon restart, I cannot get it to reassemble.
/etc/multipath.conf
defaults {
        user_friendly_names no
}
blacklist {
    wwid "600508e000000000997d2e0655fb5108"
    wwid "5002538d408c9715"
    device {
        vendor "Dell    "
        product "Virtual Disk    "
    }
}

/etc/mdadm/mdadm.conf
# wildcards if desired.
#DEVICE partitions containers

DEVICE /dev/mapper/35000c500415cbb87
DEVICE /dev/mapper/35000c500415cbbef
DEVICE /dev/mapper/35000c500415cfea3
DEVICE /dev/mapper/35000c500415d0e3b
DEVICE /dev/mapper/35000c500415d6e3b
DEVICE /dev/mapper/35000c500415e456b
DEVICE /dev/mapper/35000c500415e4e5f
DEVICE /dev/mapper/35000c500415e8223
DEVICE /dev/mapper/35000c500415ee867
DEVICE /dev/mapper/35000c5004160b2df
DEVICE /dev/mapper/35000c5004160b6bb
DEVICE /dev/mapper/35000c50041611daf

# automatically tag new arrays as belonging to the local system
HOMEHOST <system>

# instruct the monitoring daemon where to send mail alerts
#MAILADDR root

# definitions of existing MD arrays

# This configuration was auto-generated on Wed, 25 Jul 2018 23:01:52 +0000 by mkconf
ARRAY /dev/md0 metadata=1.2 name=media:0 UUID=5cfbe80c:d11c6b57:4beaff64:ed3bc6dd

A: The problem was due to using the devices and not targeting partitions.
First step was to pre-partition each of the drives.
sudo mkfs.ext4 -F /dev/mapper/35000c500415cbb87
sudo mkfs.ext4 -F /dev/mapper/35000c500415cbbef
sudo mkfs.ext4 -F /dev/mapper/35000c500415cfea3
sudo mkfs.ext4 -F /dev/mapper/35000c500415d0e3b
sudo mkfs.ext4 -F /dev/mapper/35000c500415d6e3b
sudo mkfs.ext4 -F /dev/mapper/35000c500415e456b
sudo mkfs.ext4 -F /dev/mapper/35000c500415e4e5f
sudo mkfs.ext4 -F /dev/mapper/35000c500415e8223
sudo mkfs.ext4 -F /dev/mapper/35000c500415ee867
sudo mkfs.ext4 -F /dev/mapper/35000c5004160b2df
sudo mkfs.ext4 -F /dev/mapper/35000c5004160b6bb
sudo mkfs.ext4 -F /dev/mapper/35000c50041611daf

Then I was able to go through the same create process using the partitioned drives
sudo mdadm --create --verbose /dev/md0 --level=6 --raid-devices=12 /dev/dm-0 /dev/dm-1 /dev/dm-2 /dev/dm-3 /dev/dm-4 /dev/dm-5 /dev/dm-6 /dev/dm-7 /dev/dm-8 /dev/dm-9 /dev/dm-10 /dev/dm-11
sudo mkfs.ext4 -F /dev/md0
sudo mkdir -p /mnt/md0
sudo mount /dev/md0 /mnt/md0
sudo mdadm --detail --scan | sudo tee -a /etc/mdadm/mdadm.conf
sudo update-initramfs -u

Then I had to add to the /etc/mdadm/mdadm.conf instead of the /dev/mapper entries
DEVICE /dev/dm-0
DEVICE /dev/dm-1
DEVICE /dev/dm-2
DEVICE /dev/dm-3
DEVICE /dev/dm-4
DEVICE /dev/dm-5
DEVICE /dev/dm-6
DEVICE /dev/dm-7
DEVICE /dev/dm-8
DEVICE /dev/dm-9
DEVICE /dev/dm-10
DEVICE /dev/dm-11


text:
Q: KDE auto scaling screen after login with HiDPI monitor connected or not I have an internal 3840x2160 monitor, and an external 2560x1440 monitor.
I recently installed Manjaro with KDE 5.9. I have tried using xrandr with scale 2x2. It seems ok but is laggy.
I don't really need to use both screens. When I use Ubuntu with Unity, I can set different scale factor separately. When I use internal monitor only, it can be 200% scaled, when I plug in external monitor, the internal one black out, the external monitor lighted and is not scaled.
But in KDE, it cannot remember scale settings for two scenarios, for now I should login first, change scale settings, logout and back again. How can I get it working? Or take a step back, can I setup two custom login session config files to choose when logging in? What environment variables should I export or do something else?
I have noticed QT_SCREEN_SCALE_FACTORS and some other variables, but I have no idea how to manipulate with them.


text:
Q: How to prove the following identity regarding Laplace transforms? I tried solving it by integrating by parts but i was unsuccessful.

$${\cal L}\left[\int_0^xf(x-t)g(t)\ dt\right]=F(p)G(p)$$

A: \begin{align}
F(p) G(p)
&= \int_0^\infty e^{-pu}f(u)\ du\int_0^\infty e^{-pv}g(v)\ dv \\
&= \int_0^\infty\int_0^\infty e^{-p(u+v)}f(u)g(v)\ du\ dv  \,\,\, , \,\,\, \text{u+v=t} \,\, , \,\, \text{v=x}\\
&= \int_0^\infty\int_x^\infty e^{-pt}f(t-x)g(x)\ dt\ dx \,\, , \,\, \text{changing order of integration}\\
&= \int_0^\infty e^{-pt}\Big[\int_0^tf(t-x)g(x)\ dx \Big]\ dt  \\
&= {\cal L}(f*g)(t)
\end{align}


text:
Q: Filter based on values after join operation - MongoDB I have two collections in the following format -
collection 1
{
    "_id": "col1id1",
    "name": "col1doc1",
    "properties": [ "<_id1>", "<_id2>", "<_id3>"]
}

collection 2
{
    "_id": "<_id1>",
    "name": "doc1",
    "boolean_field": false
}
{
    "_id": "<_id2>",
    "name": "doc2",
    "boolean_field": true
}
{
    "_id": "<_id3>",
    "name": "doc3",
    "boolean_field" : false
}

the desired output is -
{
    "_id": "col1id1",
    "name": "col1doc1",
    "property_names": ["doc1", "doc3"]
}

The field proerties of document in collection1 has three IDs of documents in collection2 but the output after join operation should contain only those which have the boolean_field value as false. How can I perform this filter with join operation in MongoDB?

A: $lookup can be used along with $unwind to achieve this.
db.col1.aggregate([
  {
    "$unwind": "$properties"
  },
  {
    "$lookup": {
      from: "col2",
      localField: "properties",
      "foreignField": "_id",
      "as": "property_names"
    }
  },
  {
    "$match": {
      "property_names": {
        "$elemMatch": {
          "bool_field": false
        }
      }
    }
  },
  {
    "$unwind": "$property_names"
  },
  {
    "$group": {
      "_id": "$_id",
      "properties": {
        "$push": "$properties"
      },
      "property_names": {
        "$push": "$property_names"
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "name": 1,
      "property_names": {
        "name": 1
      }
    }
  }
]);


text:
Q: Diccionario de diccionarios y vuelos Se me pide una función donde retorne los aeropuertos que reciben vuelos, pero que no despegue ninguno. Los valores son:
aerolínea, que corresponde al nombre de la aerolínea
origen, que corresponde al código de aeropuerto de origen
destino, que corresponde al aeropuerto destino del vuelo
distancia, que corresponde a la distancia entre el origen y el destino
retraso, que corresponde a la cantidad de minutos de retraso que tuvo el vuelo
duracion, que corresponde a la duración planeada del vuelo en minutos
salida, que corresponde a un entero que representa la hora de salida.
La hora de salida se representa usando la hora en formato 24 horas multiplicada por 100 más la cantidad de minutos (por ejemplo, las 2007 indica que el vuelo salió a las 8:07 pm).
def listar_aeropuertos_sin_salida(vuelos:dict)->list:
        aeropuertos = []
        visitas = {}
        for codigo in vuelos:
            info_vuelos = vuelos[codigo]
            origen = info_vuelos['origen']
            destino = info_vuelos['destino']
            duracion = info_vuelos['duracion']
            salida = info_vuelos['salida']
            retraso = info_vuelos['retraso']
            tiempo_vuelo = salida + duracion + retraso
            visitas[destino] = visitas.get(destino,0) + 1
            visitas[origen] = visitas.get(origen,0) + 1
            if visitas[origen] == 0:
                if visitas[destino] > 0:
                    if tiempo_vuelo < 2400:
                        aeropuertos.append(origen)
        return aeropuertos

No tengo ningún diccionario con dicha información, por ende no puedo poner ningún intento que haya realizado.
El problema es que descubre correctamente que NO hay aeropuertos sin salida, pero no en los casos  que no hay aeropuertos sin salida cuando realmente sí los hay.


text:
Q: Object Orientation Types errors I have some home work which I am to try and do in order to try and understand OO types better. I have read it and I am not exactly sure how to go about doing it.
Here is the question:
Write a simple object-orientated program twice in two different languages. Language A and language b.  (they can be any oo language).
Demonstrate that the Type system of language A is "Too Strict".
-- Where as the program which you have written will run error free in language b.
-- The compile for language A should raise a Type-Error-Warning for the program.
Question2:
same as above but I need to show that language A is "too lenient" and that it will result in a runtime-fault.
-- language b will lead to a Type=Error-Warning
The languages can differ from the two questions
Ok so that is the task at hand. Now my thoughts of going about analysing this is:
1. I need to find a specific type error
2. I need to find two languages which Handel the error differently?
Am I going about this correctly? Or am I completely misunderstanding the question?


text:
Q: Extracting data from API with pagination offset using Azure Data Factory I am having a below API
http://example.com/?mdule=API&method=Live.getLastVisitsDetails&filter_limit=2000&filter_offset=0

Have to extract more data by increasing the offset into 2000
http://example.com/?mdule=API&method=Live.getLastVisitsDetails&filter_limit=2000&filter_offset=2000

http://example.com/?mdule=API&method=Live.getLastVisitsDetails&filter_limit=2000&filter_offset=4000

http://example.com/?mdule=API&method=Live.getLastVisitsDetails&filter_limit=2000&filter_offset=6000

I have a maximum of 6000 records. I don't know how to pass the offset value of every 2000 in the data factory
I can able to extract individually with the above links but wanted to do it automatically for all 6000 records.
Can anyone show me some documentation or advise how to execute this in the datafactory?
I saw the pagination documentation, but no success

A:
Extracting data using copy activity from rest API

Step1: Create a new pipeline and add a Copy Data activity.
Step2: Configure the source of copy activity, adding a pagination rule configured as below

Follow this sample URL and also make sure ={offset} at the end of URL.

Pagination rule either select option1 or option2 .In my case I selected Range:0:8:2

In your scenario you can  follow the range as below  :

*

*Option1: QueryParameter.{offset}: Range:0:6000:2000

*Option2: AbsoluteUrl.{offset}:Range:0:6000:2000
Range option are using 0 as the start value,6000 as the max value, and increasing by 2000 each time.

Storage account

For more detail information refer this official article.


text:
Q: Opentok output mode both individual and composed? I am working on generating archives with Opentok. It allows me to choose the output type.
Output:individual allows me to have individual video files in a zip including a json file , which is perfect. But I also need a composed video file or in another saying a merged video file composed of each stream in the archive.
Why do I need both of them?
outputMode: "individual"
The reason is that I need each video streams in order to have "watson" speech to text running over it . This way, I can generate the speech text in the right order.
outputMode: "composed"
I also need a composed video at the end of the recording because I do not want to merge the video after the recording ends.
Can anyone tell me how to succeed it?

A: It is not possible to have 2 different types of archives for 1 session going at the same time. You might be able to have 2 sessions though and have everyone publish to both of them at the same time and archive them both, one with individual archive and the other as composed.


text:
Q: Merging rows to columns I have the following situation (heavily abstracted, please ignore bad design):
CREATE TABLE dbo.PersonTest (Id INT, name VARCHAR(255))

INSERT INTO dbo.PersonTest
        (Id, name )
VALUES  (1, 'Pete')
,       (1, 'Marie')
,       (2, 'Sam')
,       (2, 'Daisy')

I am looking for the following result:
Id  Name1   Name2
1   Marie   Pete
2   Daisy   Sam

So, for each Id, the rows should be merged.
Getting this result I used the following query:
WITH PersonRN AS
(
    SELECT  *
    ,       ROW_NUMBER() OVER(PARTITION BY Id ORDER BY name) RN
    FROM    dbo.PersonTest
)

SELECT      PT1.Id
,           PT1.name Name1
,           PT2.name Name2
FROM        PersonRN AS PT1
LEFT JOIN   PersonRN AS PT2 -- Left join in case there's only 1 name
        ON  PT2.Id = PT1.Id
        AND PT2.RN = 2
WHERE       PT1.RN = 1

Which works perfectly fine.
My question is: Is this the best way (best in terms of performance and resilience)? If, for example, one of these Id's has a third name, this third name is ignored by my query. I'm thinking the best way to deal with that would be dynamic SQL, which would be fine, but if it can be done without dynamic, I would prefer that.

A: Aside from dynamic PIVOT, you can do this using Dynamic Crosstab, which I prefer for readability.
SQL Fiddle
DECLARE @sql1 VARCHAR(1000) = '',
        @sql2 VARCHAR(1000) = '',
        @sql3 VARCHAR(1000) = ''
DECLARE @max INT

SELECT TOP 1 @max = COUNT(*) FROM PersonTest GROUP BY ID ORDER BY COUNT(*) DESC

SELECT @sql1 =
'SELECT
    ID' + CHAR(10)

SELECT @sql2 = @sql2 +
'   , MAX(CASE WHEN RN =' + CONVERT(VARCHAR(5), RN)
    + ' THEN name END) AS ' + QUOTENAME('Name' + CONVERT(VARCHAR(5), RN)) + CHAR(10)
FROM(
    SELECT TOP(@max)
        ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RN
    FROM sys.columns
)t
ORDER BY RN

SELECT @sql3 =
'FROM(
    SELECT *,
        RN = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY name)
    FROM PersonTest
)t
GROUP BY ID
ORDER BY ID'

PRINT (@sql1 + @sql2 + @sql3)
EXEC (@sql1 + @sql2 + @sql3)


text:
Q: Replacing words matching regular expressions in python import re
replacement_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'cannot'),
(r'i\'m', 'i am'),
(r'ain\'t', 'is not'),
(r'(\w+)\'ll', '\g<1> will'),
(r'(\w+)n\'t', '\g<1> not'),
(r'(\w+)\'ve', '\g<1> have'),
(r'(\w+)\'s', '\g<1> is'),
(r'(\w+)\'re', '\g<1> are'),
(r'(\w+)\'d', '\g<1> would')
 ]
class RegexpReplacer(object):

   def __init__(self, patterns=replacement_patterns):
      self.patterns = [(re.compile(regex), repl) for (regex, repl)
                      in pattern]
   def replace(self, text):
      s = text
      for (pattern, repl) in self.patterns:
          (s, count) = re.subn(pattern, repl, s)
   return s

 rep=RegexpReplacer()
 print rep.replace("can't is a contradicton")

I have copied this code from Python Text Processing with NLTK 2.0 Cookbook by Jacob Perkins
However my expected output is:
cannot is a contradiction
Actual Output is:
can't is a contradiction
I'm unable to pinpoint the error in t

A: Your code has some indentation issues and typos - I'm not quite sure how the interpreter was giving you any output at all.  After I fixed those, I got your expected output.
import re
replacement_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'cannot'),
(r'i\'m', 'i am'),
(r'ain\'t', 'is not'),
(r'(\w+)\'ll', '\g<1> will'),
(r'(\w+)n\'t', '\g<1> not'),
(r'(\w+)\'ve', '\g<1> have'),
(r'(\w+)\'s', '\g<1> is'),
(r'(\w+)\'re', '\g<1> are'),
(r'(\w+)\'d', '\g<1> would')
 ]
class RegexpReplacer(object):

   def __init__(self, patterns=replacement_patterns):

      # Fixed this line - "patterns", not "pattern"
      self.patterns = [(re.compile(regex), repl) for (regex, repl) in patterns]

   def replace(self, text):
      s = text
      for (pattern, repl) in self.patterns:
          (s, count) = re.subn(pattern, repl, s)

      # Fixed indentation here
      return s

rep=RegexpReplacer()
print rep.replace("can't is a contradicton")

A: Either use raw strings or escape the quotation marks, but not both.
>>> print r'won\'t'
won\'t
>>> print 'won\'t'
won't

or, if you prefer raw strings:
>>> print r"won't"
won't


text:
Q: APEX 5 get_blob does not work I am working on an Oracle APEX (Oracle APEX 5.03.00.03 on Oracle 11.2.0.1.0) project and want to add a BLOB download field in a classic report. When I try to implement the build-in BLOB function, I get the following error when I try to use the download functionality:

The requested URL /apex/apex_util.get_blob was not found on this server

When I simply display the ID of the table containing the BLOB, it seems to work fine.
Can anyone suggest why I get this error message?
Detailed error message:
 Fri, 03 Feb 2017 16:14:58 GMT

 ORA-01403: no data found
 ORA-06512: at "APEX_050000.WWV_FLOW_DML", line 2614
 ORA-06512: at "APEX_050000.HTMLDB_UTIL", line 2358
 ORA-06512: at line 30

   DAD name: apex
   PROCEDURE  : apex_util.get_blob
   URL        : http://XDB HTTP Server:8080/apex/apex_util.get_blob?s=11054899794271&a=101&c=6567838787688550&p=1&k1=387&k2=&ck=trxxXovenh8JXNmrbJU-kW8fuqA&rt=CR
   PARAMETERS :
   ===========
   s:
    11054899794271
   a:
    101
   c:
    6567838787688550
   p:
    1
   k1:
    387
   k2:

   ck:
    trxxXovenh8JXNmrbJU-kW8fuqA
   rt:
    CR

   ENVIRONMENT:
   ============
     PLSQL_GATEWAY=WebDb
     GATEWAY_IVERSION=2
     SERVER_SOFTWARE=Oracle Embedded PL/SQL Gateway/11.2.0.1.0
     GATEWAY_INTERFACE=CGI/1.1
     SERVER_PORT=8080
     SERVER_NAME=XDB HTTP Server
     REQUEST_METHOD=GET
     QUERY_STRING=s=11054899794271&a=101&c=6567838787688550&p=1&k1=387&k2=&ck=trxxXovenh8JXNmrbJU-kW8fuqA&rt=CR
     PATH_INFO=/apex_util.get_blob
     SCRIPT_NAME=/apex
     REMOTE_HOST=
     REMOTE_ADDR=***.***.***.***
     SERVER_PROTOCOL=HTTP/1.1
     REQUEST_PROTOCOL=HTTP
     REMOTE_USER=ANONYMOUS
     ORACLE_SSO_USER=
     OSSO_IDLE_TIMEOUT_EXCEEDED=
     OSSO_USER_GUID=
     HTTP_CONTENT_LENGTH=0
     HTTP_CONTENT_TYPE=
     HTTP_USER_AGENT=Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0
     HTTP_HOST=***.***.***.***:8080
     HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
     HTTP_ACCEPT_ENCODING=gzip,deflate
     HTTP_ACCEPT_LANGUAGE=de,en-US;q=0.7,en;q=0.3
     HTTP_ACCEPT_CHARSET=
     HTTP_COOKIE=GLog=%7B%0D%20%20%20%20trackRPC%3Afalse%0D%7D; ORA_WWV_USER_69403427360201=ORA_WWV-e_s8viZvzgtsU3VEWxrb2fiA; ORA_WWV_REMEMBER_UN=INFADOKU_MCS:INFADOKU; LOGIN_USERNAME_COOKIE=marcel.cossijns%40dimq.com; ORA_WWV_APP_101=ORA_WWV-oDjbL3JTO9dSkhc-G3eXZUCk; ORA_WWV_APP_104=ORA_WWV-NCAzle-H4Do3Okc0SfsHHkGa
     HTTP_IF_MODIFIED_SINCE=
     HTTP_REFERER=http://**.***.***.***:8080/apex/f?p=101:1:11054899794271:::::
     HTTP_SOAPACTION=
     HTTP_ORACLE_ECID=
     HTTP_ORACLE_CACHE_VERSION=
     HTTP_AUTHORIZATION=
     WEB_AUTHENT_PREFIX=
     DAD_NAME=apex
     DOC_ACCESS_PATH=docs
     DOCUMENT_TABLE=wwv_flow_file_objects$
     PATH_ALIAS=r
     REQUEST_CHARSET=AL32UTF8
     REQUEST_IANA_CHARSET=UTF-8
     SCRIPT_PREFIX=
     HTTP_IF_MATCH=
     HTTP_CACHE_CONTROL=
     SOAP_BODY=
     HTTP_X_ORACLE_DEVICE_CLASS=
     HTTP_X_ORACLE_DEVICE_ORIENTATION=
     HTTP_X_ORACLE_DEVICE_MAXDOCSIZE=
     HTTP_X_ORACLE_DEVICE=
     HTTP_X_ORACLE_ORIG_ACCEPT=
     HTTP_X_ORACLE_ORIG_USER_AGENT=
     HTTP_X_ORACLE_USER_LOCALE=
     HTTP_X_ORACLE_USER_NAME=
     HTTP_X_ORACLE_USER_DISPLAYNAME=
     HTTP_X_ORACLE_USER_USERKIND=
     HTTP_X_ORACLE_USER_AUTHKIND=
     HTTP_X_ORACLE_USER_DEVICEID=
     HTTP_X_ORACLE_USER_LOCATION_ADDRESSLINE1=
     HTTP_X_ORACLE_USER_LOCATION_ADDRESSLINE2=
     HTTP_X_ORACLE_USER_LOCATION_ADDRESSLASTLINE=
     HTTP_X_ORACLE_USER_LOCATION_BLOCK=
     HTTP_X_ORACLE_USER_LOCATION_CITY=
     HTTP_X_ORACLE_USER_LOCATION_COMPANYNAME=
     HTTP_X_ORACLE_USER_LOCATION_COUNTY=
     HTTP_X_ORACLE_USER_LOCATION_STATE=
     HTTP_X_ORACLE_USER_LOCATION_POSTALCODE=
     HTTP_X_ORACLE_USER_LOCATION_POSTALCODEEXT=
     HTTP_X_ORACLE_USER_LOCATION_COUNTRY=
     HTTP_X_ORACLE_USER_LOCATION_TYPE=
     HTTP_X_ORACLE_USER_LOCATION_X=
     HTTP_X_ORACLE_USER_LOCATION_Y=
     HTTP_X_ORACLE_SERVICE_HOME_URL=
     HTTP_X_ORACLE_SERVICE_PARENT_URL=
     HTTP_X_ORACLE_HOME_URL=
     HTTP_X_ORACLE_MODULE_CALLBACK_URL=
     HTTP_X_ORACLE_MODULE_CALLBACK_LABEL=
     HTTP_X_ORACLE_CACHE_USER=
     HTTP_X_ORACLE_CACHE_SUBID=
     HTTP_X_ORACLE_CACHE_AUTH=
     HTTP_X_ORACLE_CACHE_DEVICE=
     HTTP_X_ORACLE_CACHE_LANG=
     HTTP_X_ORACLE_CACHE_ENCRYPT=
     HTTP_X_ORACLE_ASSERT_USER=

A: You will need to add these to your page,

*

*Hidden page item, say P60_DOC_ID

*One file browse page item, say P60_DOC

*Automatic Row Fetch process after page header execution point, say
FETCH DOC
And then you can implement built-in BLOB function in following way,
APEX_UTIL.GET_BLOB_FILE_SRC('P60_DOC',DOC_ID,NULL,'inline')

Screenshot of item and process properties for reference,


text:
Q: How to use an image as a link (which is stored as an expression in jinja templating) in HTML I have a data expression which is called
img_tweets = ['http://pbs.twimg.com/media/EQYzCP4VAAEN0UJ.jpg']

In jinja
{{img_tweets}}

I want to use the value (which is a url) in img_tweets as an image for one of my pages. I'm not sure how to do that. This is what I have:

Please let me know if this is not clear.
Thank you.

A: According to the Jinja documentation, attribute values need to be wrapped in quotes. So in your case, you'd write:


text:
Q: Selecting columns of dataset without using the number of the column but the name of the column I tried to select columns of dataset without using the index number of the column but the name of the column
data(iris)
y<-iris[, colnames = "Species"]
z<-iris[, colnames != "Species"]

Can anyone tell why line 2 & 3 are wrong

A: *

*colnames is a function, you need to call functions with (). colnames needs a dataframe or matrix as input. So you need to use colnames(iris) to get the column names of iris dataset.

*= is an assignment operator. What you need here is comparison operator which is ==.
y<-iris[, colnames(iris) == "Species", drop = FALSE]
z<-iris[, colnames(iris) != "Species"]

When subsetting a dataframe if the output is only of 1 column R drops its dimension and you get output as a vector. To keep data as dataframe in y we use drop = FALSE.


text:
Q: IDEA 12 error "Cannot reload AVD list: Error parsing /tools/lib/devices.xml"? I installed new IntelliJ IDEA 12, Community Edition. I used it top open an Android project created in IDEA 11 (the last version before 12 appeared). When I tried to run Android app, I got error:

Cannot reload AVD list: Error parsing MY_PATH/tools/lib/devices.xml

Did anyone get this error? How to solve it?
This is IDEA 12 for Linux 64bit machines.
EDIT
I am using SDK Tools r21.

A: Copy the devices.xml file from "../sdk/tools/lib/devices.xml."
to your local folder:
C:\Users\USERNAME.android\
Solved my problem.

A: This is a solution for those who (like myself) in IDEA 11.x changed the content of XMl file Android-SDK/adt-bundle-linux/sdk/tools/lib/devices.xml.
The solution is to take the file devices.xml from the original SDK folder and copy it to lib folder in your Android SDK folder.
No need to touch devices.xml in your .android directory as IDEA 12 disables it during the installation.

A: Cannot reload AVD list: Error parsing MY_PATH/tools/lib/devices.xml  for this error

*

*copy device.xml from C:\Users\admin\AppData\Local\Android\android-sdk\tools\device.xml

*replace MY_PATH/tools/lib/devices.xml

A: I was able to get rid of this error after updating my SDK to 4.3 and sdk platform tools to 18.
Thanks to the link below
How to have single android SDK and AVD for eclipse and android studio


text:
Q: Careers: create PDF is not handling properly the sections Writing and Reading Scenario #1: no items in the section Writing, a few items in Reading

*

*click on create pdf

*in the PDF you get your readings under the title "Writing" (should be "Reading")

Scenario #2: one item in the section Writing, a few items in Reading

*

*click on create pdf

*in the PDF you get:

*

*your readings under the title "Writing" (should be "Reading"), as in scenario #1

*there are no writings (there should be one)

Hope it to be clear. Let me know in case it isn't.
Thank you!

A: There were two issues here. The "Writing" section on the PDF was actually just a list of all articles on your profile - whether they were ones you'd written or just ones you'd read. And books were completely ignored!
So a book that you'd written wouldn't appear under "Writing", but all of the blog posts you'd read did. Oops.
I've now fixed this so it lists books and articles you've written.
If anybody really thinks it's necessary or desirable to add a "Reading" section to the PDF, just ask and we'll add it. (But really, this feels like padding to me, and I think you'd be better off if your CV just concentrated on the interesting stuff).


text:
Q: Problem with generic return type in guice assisted inject factory So far, I successfully used google guice 2. While migrating to guice 3.0, I had troubles with assisted inject factories. Assume the following code
public interface Currency {}
public class SwissFrancs implements Currency {}

public interface Payment<T extends Currency> {}
public class RealPayment implements Payment<SwissFrancs> {
    @Inject
    RealPayment(@Assisted Date date) {}
}

public interface PaymentFactory {
    Payment<Currency> create(Date date);
}

public SwissFrancPaymentModule extends AbstractModule {
    protected void configure() {
        install(new FactoryModuleBuilder()
             .implement(Payment.class, RealPayment.class)
             .build(PaymentFactory.class));
    }
}

While creating the injector, I get the following exception:
com.google.inject.CreationException: Guice creation errors:

1) Payment<Currency> is an interface, not a concrete class.
   Unable to create AssistedInject factory. while locating Payment<Currency>
   at PaymentFactory.create(PaymentFactory.java:1)

With the assisted inject creator from guice 2 my configuration works:
bind(PaymentFactory.class).toProvider(
FactoryProvider.newFactory(PaymentFactory.class, RealPayment.class));

The only workaround I found so far is to remove the generic parameter from the return type of the factory method:
public interface PaymentFactory {
    Payment create(Date date);
}

Does anybody know, why guice 3 doesn't like the generic parameter in the factory method or what I generally misunderstood about assisted inject factories? Thanks!

A: There are two issues with your code above.
First, RealPayment implements Payment<SwissFrancs>, but PaymentFactory.create returns Payment<Currency>. A Payment<SwissFrancs> cannot be returned from a method that returns Payment<Currency>. If you change the return type of create to Payment<? extends Currency>, then RealPayment will work (because it's a Payment for something that extends Currency).
Second, you DO need to use the version of implement that takes a TypeLiteral as its first argument. The way to do that is to use an anonymous inner class. To represent `Payment' you can use
new TypeLiteral<Payment<? extends Currency>>() {}

See the Javadoc for that TypeLiteral constructor for more information.


text:
Q: C++ program crashes when code is linked to exe but works fine when code is compiled into exe, how come? I have a program that have been running fine for long time on one platform. Because of its success it is to be ported to another platform. No problem, I thought since it is written in Standard C++...
My approach (illustrated with pseudo CMake):

*

*setup the development environment by sourcing the platform specific toolchain to ensure that correct platform is targeted

*factor out all core business logic into an application object and build a library out of that (one library for each platform from the same source code):
add_library(appLib STATIC app.cpp)
target_link_libraries(appLib utilLib networkLib dbLib ${boostLibs})

*have one main_a.cpp and another main_b.cpp, which do the platform-specific initialization for platform a and b respectively, and let the main function in those instantiate the application object.
int main()
{
    auto result = initAndDoPlatformStuff();
    App app(result);
    app.run();
}

*instruct compiler and linker to assemble an executable:
if (Platform_A)
add_executable(appExe main_a.cpp)
else()
add_executable(appExe main_b.cpp)
endif()
target_link_libraries(appExe appLib)
In principle, this is a perfectly valid approach I guess. But in reality it does not work. Within a second program crashes, and the crashes are different almost every time; inspecting the core dumps indicate it sometime crashed in the standard library, sometime in boost library and also in my code, but this is nonsense I guess. Program seem to work 1 out 10 times, but eventually crashes.
However, if I use the same exact code, only extract it into its original main.cpp file and then build it together differently, like this:
int main()
{
    auto result = initAndDoStuff();
    processForever(result); // Business logic
}
add_executable(appExe main.cpp)
target_link_libraries(appExe utilLib networkLib dbLib ${boostLibs})

then it works!
I'm puzzled and confused. I'm suspecting it has to do something with code layout, I've therefore played around with different variants of PIC and PIE but have had no success with that. Are there any tools available that allows you to get a comprehensive overview of the binary code layout? I know about nm, od, objdump but they are low-level and I don't know what to look for...
Maybe I'm on the wrong path anyway, maybe the problem is related to something completely different. Does anyone got any hunch of what can cause this behavior? How else can I approach this problem?

A: Actually, the fault was mine. Of course...
I really tried to get all details correct when I refactored the code into a lib, but obviously I was not careful enough, and blind when searching for the problem.
The problem, which I finally found, was that I still kept one variable as a local variable after refactoring, which then went out of scope causing deallocated memory to be referenced, which resulted in all sorts of undefined behavior.


text:
Q: How do I avoid making methods and variables static in this code? I was solving past exams for my java class and I'm struggling with one of them. I keep getting wrong result and I think its because all of classes and instance variables are static. How do I avoid making them static? Also this question basically wants you to find same letters of the location given in args[1] and convert them to the "S" if they are near of the given location (Args are "K,K,K,Y-K,Y,M,M-K,Y,Y,Y 2,1 S" if you need)
public class MatrixRefill {
    public static String[][] matrix;
    public static int rows;
    public static int cols;
    public static String enemy;
    public static String target;
    public static void main(String[] args) {
        target = args[2];
        rows = Integer.parseInt(args[1].substring(0,1));
        cols = Integer.parseInt(args[1].substring(2));
        matrix = matrixCreator(args[0]);
        enemy = matrix[rows][cols];
        recursive(rows, cols, target);
        printer(matrix);
    }
    public static String[][] matrixCreator(String mx) {
        int ro = 0;
        int co = 0;
        for (int i = 0; i < mx.length(); i++) {
            if (mx.substring(i,i+1).equals(","))
                co++;
            if (mx.substring(i,i+1).equals("-"))
                ro++;
        }
        String[][] matriks = new String[ro+1][co/3+1];
        ro = 0;
        co = 0;
        for (int j = 0; j < mx.length(); j++) {
            if (mx.substring(j,j+1).equals(","))
                co++;
            else if (mx.substring(j,j+1).equals("-")) {
                ro++;
                co = 0;
            }
            else
                matriks[ro][co] = mx.substring(j,j+1);
        }
        return matriks;
    }
    public static void recursive(int row, int col, String target) {
        if (valid(row,col)) {
            recursive(row+1,col, target);
            recursive(row,col+1, target);
            recursive(row,col-1, target);
            recursive(row-1,col, target);
            matrix[row][col] = target;
        }
    }
    public static boolean valid(int row, int col) {
        boolean result = false;
        if (row >= 0 && row < matrix.length && col >= 0 && col < matrix[row].length)
            if (matrix[row][col] == enemy)
                result = true;
        return result;
    }
    public static void printer(String[][] owo) {
        for(int i = 0; i < owo.length; i++) {
            for(int j = 0; j < owo[i].length; j++) {
                System.out.print(owo[i][j]);
                if(j < owo[i].length - 1)
                    System.out.print(" ");
            }
            System.out.println();
        }
    }
}

A: Remove the static keyword from your methods and instance fields.  But to call them from within main you need to create an instance of the containing class (in this case the one that contains the main method) and use that to call the other methods.  What I do sometimes is to create an instance method (i.e. non-static) and call that to start the process.  Then everything that would be in main I would put in that method.  Here is an example.
    public static void main(String[] args) {
        MatrixRefill mr = new MatrixRefill();
        mr.start();
    }
    public void start() {
        target = args[2];
        rows = Integer.parseInt(args[1].substring(0,1));
        cols = Integer.parseInt(args[1].substring(2));
        matrix = matrixCreator(args[0]);
        enemy = matrix[rows][cols];
        recursive(rows, cols, target);
        printer(matrix);
    }
    // rest of code here
}

By putting what was in main in the start method you can call the other instance methods and access instance fields without qualifying them with a reference to the class (i.e. in this case prefixing with mr.)


text:
Q: Can I rewrite this expression with a Dirac $\delta$-function? I am looking at the following scalar product of divergences in $4$ dimensions (in momentum space):
$$\partial_{p_1} \cdot \partial_{p_2} \frac{1}{p_1^2p_2^2}. \tag{1}$$
There is a further integration over $p_1$ and $p_2$ on the full space. I mention it because it means that $p_1$ and $p_2$ can coincide, and an especially interesting case of that is $p_1^2=p_2^2=0$. Now I am wondering if I can extract a Dirac $\delta$-function, since:
$$\partial_p^2 \frac{1}{p^2} = - (2\pi)^2 \delta^4(p). \tag{2}$$
($1/p^2$ is the Green's function of $\partial_p^2$ in $4$ dimensions) and
$$\partial_p^2 \frac{1}{p^4} = \partial_{p_\mu}\partial_{p_\mu} \left( \frac{1}{p^2}\frac{1}{p^2} \right) = \frac{8}{p_2^6} - \frac{8\pi^2}{p_2^2} \delta^{4}(p). \tag{3}$$
(using the product rule to isolate a $\partial_p^2 (1/p^2)$).
It seems to me that at $p_1=p_2=0$, I have a somewhat similar situation, and ideally I would love to write $(1)$ in the following form:
$$\begin{align}\partial_{p_1} \cdot \partial_{p_2} \frac{1}{p_1^2p_2^2} &= \text{(terms valid at $p_1,p_2\neq0$)} \cr &+ \text{(term with $\delta$-function for case $p_1=p_2=0$)}.\end{align} \tag{4}$$
Is that possible? I think not, but it would be so useful in the computation I am doing that it is worth asking.

A: If we regularize OP's expressions as a smooth function in $C^{\infty}(\mathbb{R}^4)$, in the sense of generalized functions$^1$
$$ \frac{1}{p^2+\varepsilon}~\rightarrow~ {\rm P.V.}\frac{1}{p^2}
\quad\text{for}\quad\varepsilon\to 0^+,  \tag{2i}$$
then the derivatives $\partial_{\mu} ~:=~\frac{\partial}{\partial p_{\mu}}$ are well-defined:
$$ \partial_{\mu}\frac{1}{p^2+\varepsilon}~=~- \frac{2p_{\mu}}{(p^2+\varepsilon)^2}~\rightarrow~ -{\rm P.V.}\frac{2p_{\mu}}{(p^2)^2}
\quad\text{for}\quad\varepsilon\to 0^+,  \tag{2ii}$$
$$ \partial^2\frac{1}{p^2+\varepsilon}~=~ -\frac{8\varepsilon}{(p^2+\varepsilon)^3} ~\rightarrow~  (2\pi)^2\delta^4({\bf p})
\quad\text{for}\quad\varepsilon\to 0^+.  \tag{2iii}$$
$$\begin{align} \partial_{(1)}\cdot \partial_{(2)}\frac{1}{p^2_{(1)}+\varepsilon}\frac{1}{p^2_{(2)}+\varepsilon}~=~& \frac{4p_{(1)}\cdot p_{(2)}}{(p^2_{(1)}+\varepsilon)^2(p^2_{(2)}+\varepsilon)^2}\cr
~\rightarrow~& {\rm P.V.}\frac{4p_{(1)}\cdot p_{(2)}}{(p^2_{(1)})^2(p^2_{(2)})^2}
\quad\text{for}\quad\varepsilon\to 0^+ .\end{align} \tag{1/4}$$
In particular, there are no Dirac delta like contributions in eq. (1/4), cf OP's question. On the other hand,
$$ \partial_{\mu}\frac{1}{(p^2+\varepsilon)^2}~=~- \frac{4p_{\mu}}{(p^2+\varepsilon)^3} , \tag{3i}$$
$$ \partial^2\frac{1}{(p^2+\varepsilon)^2}~=~ \frac{8p^2-16\varepsilon}{(p^2+\varepsilon)^4},  \tag{3ii}$$
are too singular to make sense as generalized functions.
--
$^1$Here ${\rm P.V.}$ is the Cauchy principal value and $p^2=\sum_{\mu=1}^4 p_{\mu}^2$.


text:
Q: PreparedStatement continues to insert if Error I have a little concern with Objet PreparedStatement in java to insert in an Oracle database.
Infect I prepare well the model of my INSERT query in the PreparedStatement I add well all my parameters with an addBatch() for each record I want to insert.
I add several batches to insert a 500 record hits for example.
Until then all of them work well I can insert what I want
On the other hand, in case my PreparedStatement generates a BatchUpdateException error (for example violation of constraint) on the 500 line that I want to insert it inserts me nothing at all.
I want to the limit remove the record that raises concern (with violation constraint) and insert at least the 499 line that are OK
How can I do that ? if she gives me a track I'd be grateful.
Just for Info I want to insert several lines of a stroke from 500 lines, so the solution to insert line by line does not fit me too much performance level.
Cordially

A: maybe this is not what you want but oracle has some built in error logic
you have to create an error table
e.g. if the table is called emp, run this
exec dbms_errlog.create_error_log(dml_table_name=>'emp');

that will create a table err$_emp that will catch the errors
then you can do something like this below(note the log errors into clause)
the batch will succeed and you will have to check the error table for errors after you run it
import java.sql.*;

public class Class1 {

    public static void main(String[] args) throws SQLException {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        PreparedStatement preparedStatement;
        int records = 20;

        try {
            Connection connection = DriverManager.getConnection(
                    "jdbc:oracle:thin:@//host/db","scott","tiger");

            String compiledQuery = "INSERT INTO EMP(EMPNO)" +
                    " VALUES" + "(?) LOG ERRORS INTO ERR$_EMP REJECT LIMIT UNLIMITED";
            preparedStatement = connection.prepareStatement(compiledQuery);

            for(int index = 1; index <= records; index++) {
                preparedStatement.setInt(1, index);
                preparedStatement.addBatch();
            }

            long start = System.currentTimeMillis();

            int[] inserted;

            try {
                inserted = preparedStatement.executeBatch();
            }
            catch (SQLException e)
            {
                System.out.println("sql error");
            }
            long end = System.currentTimeMillis();

            System.out.println("total time taken to insert the batch = " + (end - start) + " ms");
            System.out.println("total time taken = " + (end - start)/records + " s");

            preparedStatement.close();
            connection.commit();
            connection.close();

        } catch (SQLException ex) {
            System.err.println("SQLException information");
            while (ex != null) {
                System.err.println("Error msg: " + ex.getMessage());
                ex = ex.getNextException();
            }
            throw new RuntimeException("Error");
        }
    }
}


text:
Q: AdColony Video advertisment in ios I Have register a demo app on Adcolony and get appId and zoneId and Implement AdColony in my iOS(7.1 xcode 5.1). [AdColony configureWithAppID:myAppID
                         zoneIDs:@[myZoneID]
                        delegate:self
                         logging:YES];
[
[AdColony playVideoAdForZone:@[myZoneID withDelegate:nil];
Here are the logs:
 AdColony zone ID you provided (myZoneID) is not valid. No ad will display.
Please Give me better Solution as soon as.

A: It looks like you are providing an incorrect ID in your code.  Double check both App and Zone IDs and verify that they are correct in your code.


text:
Q: How can I do a multi level ORDER BY where rows with specific values will get preference? Sample table
+------+--------+------------------+
| Code |  City  |       Role       |
+------+--------+------------------+
|    1 | Mumbai | Designer         |
|    2 | Mumbai | Designer         |
|    3 | Delhi  | Designer         |
|    4 | Delhi  | Project Manager  |
|    5 | Mumbai | Project Manager  |
|    6 | Pune   | Designer         |
|    7 | London | Network Engineer |
+------+--------+------------------+

Level 1 sort will be on City field - First Delhi, then Mumbai then anything else.
Level 2 sort will be on Role field - First Project Manager, then Designer, then anything else.
Output after the sort should be
+------+--------+------------------+
| Code |  City  |       Role       |
+------+--------+------------------+
|    4 | Delhi  | Project Manager  |
|    3 | Delhi  | Designer         |
|    5 | Mumbai | Project Manager  |
|    1 | Mumbai | Designer         |
|    2 | Mumbai | Designer         |
|    6 | Pune   | Designer         |
|    7 | London | Network Engineer |
+------+--------+------------------+

A: In MySQL, one method is:
order by (case when city = 'Delhi' then 1
               when city = 'Mumbai' then 2
               else 3
          end),
         city,
         (case when role = 'Project Manager' then 1
               when role = 'Designer' then 2
               else 3
          end)

A shorter, but somewhat enigmatic method uses:
order by field(city, 'Mumbai', 'Delhi') desc,
         city,
         field(role, 'Designer', 'Project Manager') desc

field() returns 0 when there is no match.  So the arguments are in reverse order relative to how you want them searched.  The desc then puts them in the correct order.

A: SELECT * FROM table
ORDER BY (case when City = 'Delhi' then 1
              when City = 'Mumbai' then 2
              else 3
         end asc),
         (case when role = 'Project Manager' then 1
              when City = 'Designer' then 2
              else 3
         end asc)


text:
Q: Get return value of python class function after timer I have a simple python class called Timer_ that takes an interval in seconds and runs the timer in the background. When it is done, it runs a finished function that returns true. How would I get the value of this function when the timer stops in the form of a variable? Thank you!
import threading

class Timer_():

    def __init__(self, interval):
        #interval in seconds
        self.interval = interval
        self.finished = False

    def run(self):
        self.timel = threading.Timer(float(self.interval), self.finish)
        self.timel.start()

    def finish(self):
        self.finished = True
        return True

    def cancel(self):
        self.timel.cancel()

time = Timer_(5)
time.run()
print(time.finished)

A: Sounds like you want to wait until time.finished is True
Try using a while loop over the value of time.finished:
time = Timer_(5)
timer.run()
while not timer.finished:
    pass
x = timer.finished
print(x)

This will loop through the while until timer.finished is True then you can use that value as a variable or continue on.


text:
Q: App stuck in white screen in iOS ionic 5 app I pushed newly created ionic app to test flight and got bellow error.
    ITMS-90809: Deprecated API Usage - New apps that use UIWebView are no longer accepted. Instead, use WKWebView for improved security and reliability. Learn more (https://developer.apple.com/documentation/uikit/uiwebview).
Follow the below steps to Fix it.
1) Created new ionic app (Ionic version 5.0.0)
2) Added iOS platform (ionic cordova platfrom add ios@5.1.1)
3) After adding platform below plugins will get added to package.json & config.xml
     Package.json :

    "cordova-plugin-device": "^2.0.2",
    "cordova-plugin-ionic-keyboard": "^2.2.0",
    "cordova-plugin-splashscreen": "^5.0.2",
    "cordova-plugin-statusbar": "^2.4.2",
    "cordova-plugin-whitelist": "^1.3.3",
    "cordova-plugin-ionic-webview": "^4.1.1",

    Config.xml
    <plugin name="cordova-plugin-whitelist" spec="1.3.3" />
    <plugin name="cordova-plugin-statusbar" spec="2.4.2" />
    <plugin name="cordova-plugin-device" spec="2.0.2" />
    <plugin name="cordova-plugin-splashscreen" spec="5.0.2" />
    <plugin name="cordova-plugin-ionic-keyboard" spec="^2.0.5" />
    <plugin name="cordova-plugin-ionic-webview" spec="^4.0.1">

4) Removed Webview plugin as suggested ionic Cordova plugin rm cordova-plugin-ionic-webview.
5) Removed platform ionic cordova platform rm ios
6) Added plugin cordova-plugin-wkwebview-engine@1.2.1 --save
7) Added preference attribute CordovaWebViewEngine to the config.xml as below.
8) Added feature attribute CDVWKWebViewEngine to the config.xml as below.
9) Added preference WKWebViewOnly to the config.xml as below.
    "<platform name="ios">
    <preference name="WKWebViewOnly" value="true" />
    <feature name="CDVWKWebViewEngine">
        <param name="ios-package" value="CDVWKWebViewEngine" />
    </feature>
    <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
    </platform>"
10) Added ios platform "ionic cordova platform add ios@5.1.1 --save"
11) Build project "ionic cordova build iOS"
12) Open project in XCode and try to launch app in Simulator and iPhone getting white screen after splash screen

Now app got stuck in white screen after splash screen, Please help me to resolve this issue.

Thanks
Anshul