text:
Q: Tricky Yet "Elementary" Set Theory Questions I'm currently working through Jech's Set Theory. It's slow to read but I can understand pretty much everything I come across if I sit down and think about it long enough.
However, I don't feel very familiar with the material. In my experience, the best way to get familiar with a subject is to do problems. But I find the problems in this text quite easy. Most of them follow from definitions and the only somewhat trickier questions are those for which hints are given (and these hints typically give away the whole problem).
Thus I am looking for some problems, preferably but not necessarily with solutions, which are "tricky" in the sense that they require some insight and aren't just a simple application of some theorem, but are also "elementary" (to a set theorist) in that they don't require you to know something more advanced like several different kinds of forcing.
The topics I'm trying to improve in are:

*

*Cofinality

*Well-founded recursion

*Topology of $\mathbb{R}$ (things like closed sets, perfect sets) and the Baire space $\omega^{\omega}$

*Cardinal arithmetic problems involving $\sf{SCH}$, $\sf{GCH}$, and maybe problems to do with cardinals in the absence of $\sf{AC}$

*Filters/Ultrafilters

*Boolean algebras

*Club/Stationary sets

I realize this question might be a bit unclear, so here's an example of some easy problems and a slightly harder one:
(Easy) Show that the number of open sets of reals is $\mathfrak{c}$.
(Easy) Show that the number of continuous functions $f:\mathbb{R}\rightarrow\mathbb{R}$ is $\mathfrak{c}$.
(Slightly trickier) Show that the number of open sets of reals equals the number of continuous functions $f:\mathbb{R}\rightarrow\mathbb{R}$.
I am more fond of the third problem because it is not immediately obvious that one solution uses the cardinality of the reals (or, at least, it would not be obvious to someone who knows only that rationals are dense in the reals, how continuous functions are defined, and that $|\mathbb{R}|=2^{\aleph_{0}}$). Hopefully this illustrates the sort of problems I am looking for.

A: One such book is
Problems and Theorems in Classical Set Theory (Problem Books in Mathematics)


text:
Q: Android minifyEnabled option Recently I have noticed the difference in android application behaviour as minifyEnabled option value changes. Assuming that by default minifyEnabled option is set to false.
android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId ""
        minSdkVersion 24
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled false
        }
    }
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}

The configuration above is the default configuration of my android project. At the time as the application is compiled everything is working fine.
However when the value of minifyEnabled is set to true, the application throws different exceptions and is not working properly. The one of the errors is:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
        at b.c.a.a.d.i.a(:94)
        at b.c.a.a.d.b.a(Unknown Source:10)
        at b.c.a.a.d.j.onPostExecute(:36)
        at android.os.AsyncTask.finish(AsyncTask.java:696)
        at android.os.AsyncTask.access$600(AsyncTask.java:180)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:713)
        at android.os.Handler.dispatchMessage(Handler.java:112)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

What is more, I cannot notice the source of the exception. (Unknown Source:10)
When minifyEnabled is false, in similar situation there is no exception.
Could anyone explain why changing the value causes the application to not work properly.
It does not matter whether the option is changed within the debug or release version

A: minifyEnabled activates ProGuard or R8 (depending on Gradle plugin version) which attempts to trim unused code and obfuscate (rename) classes and methods. That's why you're seeing at b.c.a.a.d.i.a(:94) in your error stack.
In most cases this does not affect how your app works but there are some instances (usually when using reflection) where it causes errors. In those cases you have to manually add exceptions to the proguard-rules.pro files.
Read in detail on official page: Shrink, obfuscate, and optimize your app

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Fit the Downloaded Images into the ImageView (to Eliminate the Need for Scrolling) My app gets the album cover images from an Internet source. The image dimensions are varying from 200*200 to 400*400, therefore making scrolling necessary on some smaller devices. The layout resource codes and layout view are below.
The ImageView is the view with the red borders.
All I need is to make downloaded image to fit the imageView, so that the users won't have to scroll vertically to see the view below. How can I accomplish that? Thanks in advance...

<LinearLayout
    android:id="@+id/llayoutAlbumCover"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight="1"
    android:gravity="top|center" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <ImageView
            android:id="@+id/albumCover"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="3sp"
            android:scaleType="fitCenter"
            android:src="@drawable/loading" >
        </ImageView>

    </FrameLayout>

</LinearLayout>

A: use imgview.setScaleType(ScaleType.FIT_XY);
Through xml also you use like this
<ImageView
            android:id="@+id/albumCover"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="3sp"
             android:scaleType="fitXY"
            android:src="@drawable/loading" >
        </ImageView>

PS:: I know this is what you wanted, but for images where you care about aspect ratio, this will stretch it out.

A: You can set scale, for example imageView.setScaleType(ScaleType.fitCenter)
Samples: http://etcodehome.blogspot.com/2011/05/android-imageview-scaletype-samples.html

A: Using android:scaleType="fitCenter" guarantees at least one axis will be fitted in the view. Use android:scaleType="centerInside" instead. The dimensions will be equal or smaller then your view. For more options please check ImageView.ScaleType


text:
Q: Find if an element with a specific property value is found in a list I'm trying to find a value in a list of objects in kotlin, using for it "filter", but I need to return true or false if the value is found, but filter returns me a list of object in the case of match.
t.filter { it.retailerId == value }

¿How I can return a boolean when I find this value in the list of objects?

A: You can use firstOrNull() with the specific predicate:
val found = t.firstOrNull { it.retailerId == value } != null

If firstOrNull() does not return null this means that the value is found.

A: If you need that the element is exactly one:
t.filter { it.retailerId == value }.size == 1

if not:
t.any { it.retailerId == value }

With foldRight and a break when you found it:
t.foldRight(false) {val, res ->
                if(it.retailerId == value) {
                    return@foldRight true
                } else {
                    res
                }
            }

A: For single element
list.first { it.type == 2 (eg: conditions) }
or
list.firstOrNull { it.type == 2 (eg: conditions) }

For list of elements
list.filter { it.type == 2 (eg: conditions) }

A: In alternative to firstOrNull you can also use any with the same predicate:
val found = t.any { it.retailerId == value }

A: Kotlin has this nice extension function which u can use
if (none { it.isSelected == true }) {
                first().isSelected = true
            }


text:
Q: To test the convergence of $\int_0^{1} \frac{x^p \log x}{1+ x^2} dx$ To test the convergence of the improper integral:
$$\int_0^{1} \frac{x^p \log x}{1+ x^2} dx$$
Here we see that $0$  is the point of infinite discontinuty  for  $p<0$.
Let $f(x) = \frac{x^p \log x}{1+ x^2}$ and $g(x) = x^p$.
Now as we take..
$$\lim_{x \to 0} \frac{f(x)}{g(x)} = \lim_{x \to 0} \frac{\log x}{1+ x^2}$$
Will this $g(x)$ work? Not getting clue to solve it. Thanks in advance.

A: You may observe that
$$
\frac{x^p \log x}{1+ x^2} \sim x^p \log x, \quad \quad x \to 0^+.
$$ The integral
$$
\int_0^1x^p \log x \: dx
$$ is convergent if and only if $p>-1$, with (using integration by parts) the value
$$
\int_0^1x^p \log x \: dx =-\frac{1}{(p+1)^2}, \quad \quad p>-1.
$$
Then $$
\int_0^1\frac{x^p \log x}{1+ x^2} \:dx
$$ is convergent if and only if $p>-1$.


text:
Q: When to use plural of "archipelago" The definition of archipelago by Oxford Dictionary is the following:

an extensive group of islands

The definition of archipelago given by Cambridge Dictionary is instead the following one:

a group of small islands or an area of sea in which there are many small islands

I can conclude that, by both definitions, archipelago itself always means plural.
Both dictionaries give us the plural of the word as well, which are archipelagos and archipelagoes.
When should we use archipelagos or archipelagoes which means the plural of an extensive group of islands?

A: Archipelago is a singular noun as the group of islands is viewed as a collective whole. Archipelagos or archipelagoes is the plural noun referring to more than one group of islands.

A: Your two dictionaries say that an archipelago is an extensive group of islands or a group of small islands. As Jasper Loy says, collective nouns are singular by definition: they refer to a group of things.
Here's another example of plural use: There are three archipelagos off the north and north-west coasts of Scotland: the Orkney Islands, the Shetland Isles and the Western Isles (or Outer Hebrides).


text:
Q: couchdDB dbroot issue I am using couchdb. I am new to it. I don't know what to have in dbroot value in place of "db/". I have taken this code from one of coucdb tutorial.
Thanks in advance for your help.
//Use a namespace to protect the scope of function and variable names
 var poq = {
//Some variables global to the local namespace ("poq")
root: "http://localhost:5984/",
dbroot: "db/",
max_quotes: 6,

//Invoked when the HTML page is first loaded
loadPage: function()
{
    var six_latest = poq.root + "poquotes/_design/document/_view/by_year?&limit="
        + poq.max_quotes + "&descending=true&callback=?";
    $.getJSON(six_latest, poq.handleMainQuotes);
    $('#donewquote').click(function() {
        var db_link = poq.dbroot + "poquotes";
        var record = {
            "type": "quote",
            "author": $("#author").val(),
            "text": $("#text").val(),
            "work": {
                "title": $("#title").val(),
                "link": $("#link").val(),
                "year": parseInt($("#year").val())
            }
        };
        $.ajax({
            url : db_link,
            data : JSON.stringify(record),
            contentType : "application/json",
            type : 'POST',
            processData : false,
            dataType : "json",
            success : function(resp) {
                alert("New document created: " + JSON.stringify(resp));
            }
        });
        return false;
    });
    //Set up the collapsible form for adding new quotes
    $('#popup').click(function(){
        $("#newquote").slideToggle();
    });
    //Start out with the create quote form collapsed
    $("#newquote").slideToggle();
},

//Invoked with the result of the AJAX call to load quote documents
handleMainQuotes: function(json)
{
    //Load up to six records, as available
    quote_count = Math.min(poq.max_quotes, json["total_rows"])
    for (var i=0; i<quote_count; i++) {
        var doc = json["rows"][i]["value"]
        var year = doc["work"]["year"].toString()
        var title = doc["work"]["title"].toString()
        var link = doc["work"]["link"].toString()

        //Create an HTML snippet from the fields of each quote document
        qblock = $("

")
          .append("
" + doc["author"] + "
")
          .append("
" + doc["text"] + "
")
          .append("
" + year + "
")
          .append("
" + title + "
")
          .append("
View details »
")
        //jQuery's eq selector to find the target div corresponding to the loop index
        $('div.featured-quote:eq(' + i.toString() + ')').replaceWith(qblock);
    }
},

}

A: Looks like dbroot here is meant to be the name of your database.  If you haven't created a database yet, you can do so with:
curl -X PUT http://localhost:5984/mynewdatabase

Being new to CouchDB I recommend you start with The Definitive Guide (http://guide.couchdb.org)


text:
Q: How to get a diff between 2 objects as a mongodb update query? I have object a and object b:
var a = {x: 1};
var b = {x: 5};

And I would like to get this:
var update = getDiffUpdate(a, b);
// update should be {$inc: {x: 4}}

Do you have any idea on how to do it?
Thanks.

A: Seems to be a basic JavaScript problem:
var inc = Math.abs( a.x - b.x );
db.collection.update(query,{ "$inc": { "x": inc }});

Or something along those lines. You can traverse the object and construct if neeeded


text:
Q: Where can I host GeoServer that will allow multiple users to edit on ArcMap? We have several spatial data editors spread across the US, each having to access the same data. What we need is a multi-user spatial database that can be served up through GeoServer, hosted on the cloud, and accessed/edited within ArcMap. Does this exist?

A: There is no problem with hosting GeoServer in the cloud. My employers provide this as a service to several clients, but you could manage it yourself with little effort. Googling for "geoserver commercial cloud" turns up a number of companies offering this service.
ArcMap/ArcGis should have no difficulty in using WFS-T to edit your data layers via GeoServer and a PostGIS (or other spatial) database either on the same host or an RDS platform (if you go with AWS).

A: Cloud hosting of Geoserver is available probably on most cloud service providers.
Be mindful of caching configuration, or tile caches, this is potentially where you may get unstuck if you have dynamic space setup in AWS for example. But if you have managed Geoserver caching before in a fixed space environment, thats the way I would go.
Also be mindful of Highly available or clustered Geoserver installations and transaction queues, as sometimes the queues can be out of sync. (might be easier to manage transaction queues on one instance only, caching services on another instance, or similar, a good article can be found here. https://docs.geoserver.geo-solutions.it/edu/en/clustering/clustering/passive/passive.html. )
Geoserver supports OGC WFS-T  see here for more detail.
https://www.ogc.org/standards/wfs and https://docs.geoserver.org/latest/en/user/services/wfs/reference.html
ArcMap supports WFS-T as per previous answers.

A: For use with GeoServer, my experience is that it works more easily with QGIS.
If you are bound by using ArcMap, I may suggest using ArcGIS Online to host your spatial data (perhaps from GeoServer) and then connect to it using ArcMap/ArcGIS Pro.
You can get a free developer account (https://developers.arcgis.com/sign-up/) giving access and quite a reasonable amount of online storage. In addition, this also gives the possibility to edit the layers online directly (using Mac/Windows).


text:
Q: Is there any possible way to have multi layer view in ionic? Is there any possible way to show or to have multi layer view. I mean  UI component in are independently but both of them could be focused?
for example :
showing text box over an image, and person could  entering text in text box, without closing input box could replace or dragging image under the box.
Update
I used something like this but I used the fallowing code but it shows error
<ion-fab top>
     <ion-item>
       <ion-label fixed>Username</ion-label>
     <ion-input type="text" value=""></ion-input>
  </ion-item>


text:
Q: React Bootstrap Dropdown I am new to React and Boostrap, so please excuse my basic question. I have been looking for documentation, but can only find snippets, and not how it should all tie together.
I am using react-bootstrap and have rendered a dropdown successfully.
I have the following component:
import React, { Component } from 'react';
import Dropdown from 'react-bootstrap/Dropdown';

class VesselDropdown extends Component {

    constructor(props) {
        super(props)
        this.state = {
            vessels:[]
        }
    }

    componentDidMount() {
        fetch('http://localhost:3001/get/vessels')
        .then(res => res.json())
        .then((data) => {
          this.setState({
              vessels: data,
              test: 'xyz'
            })
        })
        .catch(console.log)
    }

    render() {
        console.log(this.state);
        return (

            <Dropdown>
            <Dropdown.Toggle variant="success" id="dropdown-basic">
                Select a Vessel
            </Dropdown.Toggle>

            <Dropdown.Menu>
                {
                    this.state.vessels.map(d => {
                        return <Dropdown.Item href="#/{d.vesselimo}">{d.vesselname}</Dropdown.Item>
                    })
                }
            </Dropdown.Menu>
            </Dropdown>

        );
      }
}

export default VesselDropdown;

Question
I need to now add the action functionality.

*

*How do I make a click on a Dropdown.Item invoke another component (VesselDetails) and display its output? Do I need to change the href on the item (to what)?

*How does the VesselDetails component receive the parameter passed to it (the vessel identifier vesselimo)?

Thanks
More info:
the VesselDetails component is still a work in progress, but this is what I have so far:
import React, { Component } from 'react';
import Table from 'react-bootstrap/Table';

class VesselDetails extends Component {

    constructor(props) {
        super(props)
        this.state = {
        }
    }

    componentDidMount() {
        fetch('/get/latestcalls/:imo')
        .then(res => res.json())
        .then((data) => {
          this.setState({
            latestcalls : data
            })
        })
        .catch(console.log)
    }

    render() {
        return (

Port Calls

                    #
                    Detail1

                    1
                    Mark

        );
      }
}

export default VesselDetails;

A: With onSelect you can access to vesselimo
    handleSelect (evt) {
      // pass as props or call api
      console.log(evt)
  }

....

<Dropdown.Item onSelect={(evt)=>{this.handleSelect(evt)}}
       eventKey={d.vesselimo}>{d.vesselname}</Dropdown.Item>


text:
Q: Show version of app in launch screen with Swift Scenario
I want to show the version of my iOS 9 app made with Swift.
What I did
I know how to get the version (let version: String = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)
I also have a custom label on my home screen.
My problem
My problem is now, that it is not allowed to use your own UIViewController for the splash / launch screen.
Many apps show their version right on that screen. That's why I think that there must be a way how to do it.

A: Updated @Repose script
#   ON/OFF Script Toggle (script ON with #, script OFF without #)
#exit 0

#   Increment Build Number Bool (Increment ON with true, increment OFF with false)
shouldIncrement=true

#   App vesion / Build version constants
versionNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "$INFOPLIST_FILE")
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")

#   Increment build number
if [ "$shouldIncrement" = true ]; then
    buildNumber=$(($buildNumber + 1))
    /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
fi

#   Output version & build numbers into a label on LaunchScreen.storyboard
sed -i bak -e "/userLabel=\"APP_VERSION\"/s/text=\"[^\"]*\"/text=\"Version: $versionNumber Build: $buildNumber\"/" "$PROJECT_DIR/$PROJECT_NAME/Base.lproj/LaunchScreen.storyboard"

A: You can create a script in Build Phases of your project. But make sure you do a couple of things first.
Go to your LaunchScreen.storyboard ViewController and create your version Label. Make sure to name your label to "APP_VERSION" in Identity Inspector pane -> Document -> Label.
Then go to your project's build phases and create your script by clicking the "+" button in the top left corner, then select "New Run Script Phase" from the pulldown menu and then drag it before "Copy Bundle Resources" phase.
UPDATE: My older answer didn't work in the newest Xcode environment. I've fixed the current issues and refactored the script. I'll update when I have the incrementer working. FYI, make sure you reinstall the app for the updated LaunchScreen.storyboard to show (due to system managing caching of the launch screen in latest versions of iOS).
And here's the final working script  with shell: /bin/sh in XCode 11 (Swift 5):
#   ON/OFF Script Toggle (script ON with #, script OFF without #)
#exit 0

#   App vesion / Build version constants
sourceFilePath="$PROJECT_DIR/$PROJECT_NAME/Base.lproj/LaunchScreen.storyboard"
versionNumber="$MARKETING_VERSION"
buildNumber="$CURRENT_PROJECT_VERSION"

#   Output version & build numbers into a label on LaunchScreen.storyboard
sed -i .bak -e "/userLabel=\"APP_VERSION\"/s/text=\"[^\"]*\"/text=\"$versionNumber($buildNumber)\"/" "$sourceFilePath"

A: Its not allowed to use any UIViewController in LaunchScreen thus what other applications does is place a UILabel in LaunchScreen xib/Storyboard and write their version number as text.
There might be some work around's, Its still not preferred or allowed by Apple, don't waste your time searching you will get the following error if you tried to set custom class :
error: Illegal Configuration: Launch screens may not set custom classnames

NOTE: What usually apps do is create another LaunchScreen UIViewConttoller directly after the default launch screen with same design and presented without animation, for example to receive some data.

A: You can try to do it with LaunchScreen.storyboard. Try to add new LaunchScreen to your project with New File -> User Interface -> Launch Screen It automatically creates a storyboard type of LaunchScreen. Then you can change the initial Launch Screen on project settings -> General in this section:

And work with this storyboard with your custom class


text:
Q: msi not getting unistalled properly I want to revert all my custom action on uninstallation.
Here are my custom action

*

*Create a registry entry using installscript

*Install service  --> created under launch an executable option

*Start Service    --> created under launch an executable option

Here is code that I wrote in installscript to add a registry entry
#include "ifx.h"

export prototype SetRegistryParameters(HWND);

function SetRegistryParameters(hMSI)
    NUMBER  ret;
    STRING  formatStr;
begin

    RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);
    SprintfBox(WARNING, "SetRegistryParameters", "Hi from internal", 0);

    ret = RegDBSetKeyValueEx("Software\\XYZ", "InstallDir", REGDB_STRING, INSTALLDIR, -1);
    if (ret < 0) then
        formatStr = "RegSetValue failed with ret: 0x%x";
        SprintfBox(WARNING, "SetRegistryParameters", formatStr, ret);
    endif;

    return ret;

end;

To stop the service and remove it  I created custom actions

*

*StopService      --> created under launch an executable option

*RemoveService    --> created under launch an executable option

To remove a registry entry I wrote a installscript code,
export prototype DeleteRegistryParameters(HWND);

function DeleteRegistryParameters(hMSI)
    // To Do:  Declare local variables.
begin

    // To Do:  Write script that will be executed when MyFunction is called.

    RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);
    SprintfBox(WARNING, "SetRegistryParameters", "Bye from internal", 0);

    ret = RegDBDeleteKey("XYZ");
    if (ret < 0) then
        formatStr = "RegSetValue failed with ret: 0x%x";
        SprintfBox(WARNING, "SetRegistryParameters", formatStr, ret);
    endif;
    return ret;
end;

Here is sequence of all actions
1. Create a registry entry using installscript
    Install Execute Sequence = After CostFinalize
    Install Execute Condition: "Not INSTALLED"
2. Install Service
    Install Execute Sequence = After SetRegistryParameters
    Install Execute Condition: "Not INSTALLED"
3. Start Service
    Install Execute Sequence = After Install Service
    Install Execute Condition: "NOT Installed"
4. Stop Service
    Install Execute Sequence = After InstallFiles
    Install Execute Condition: Remove = "ALL"
5. Remove Service
    Install Execute Sequence = After Stop Service
    Install Execute Condition: Remove = "ALL"
6. Remove Registry
    Install Execute Sequence = After Remove Service
    Install Execute Condition: Remove = "ALL"

But the package is not getting uninstalled and

A: A service is a service is a service.  Doesn't matter if it's C++, C#, Java, .PL, .PY using ServAny.exe or whatever.  Windows Installer's ServiceInstall and ServiceControl tables can handle it.  The Registry table handles Registry.  InstallShield authores MSI's.  In other words, ditch the custom actions and get rollback / uninstall for free.
See: Zataoca: Custom actions are (generally) an admission of failure.

a.  The setup developer wrote a custom action that was already
  supported by the underlying engine. This is essentially reinventing
  the wheel with a less stable solution.  Invariably this comes down to
  lack of documentation or lack of effort on the developer's part.
  Either way a failure to use the most optimal solution.


text:
Q: Does Leaflet.js support Edge browser? Leaflet.js 1.0 was released last month. Their website mentions a list of of supported browsers----but doesn't include MS Edge. I surmise that list is out of date, but I wanted to know if Leaflet officially supports Edge?

A: The Leaflet code includes some hacks to make sure Edge behaves as expected with some cases involving touchscreens (see https://github.com/Leaflet/Leaflet/blob/63fd4edc76893ab2a2f83d54e703e0a4da73de7b/src/dom/DomEvent.DoubleTap.js#L65 ), so yes, we do pay attention to the Edge browser.


text:
Q: Browser Cached image is not update for me if i append time at the end of Image url Please help me I have image update issue just because of browser cache.
Here is my code not working for me:
$("#artist-icon-box img").attr('src', artist_icon_src+'?vr='+Math.random());
Here artist icon src content image path value from database.
artist_icon_src = /ws/ABC/artist/download/id/9/field/icon/last_updated/1400513937

if i open this url in another browser tab then it open actual image that i want but not load in application.
 i try :
localhost/ws/ABC/artist/download/id/9/field/icon/last_updated/1400513937

then it display actual image.
In this code i try both time stamp and also Math.random() and it return different value each time but it does not pick up image from server.


text:
Q: All coordinates with an specific distance to one point I'm sorry for my english!
I have to get the following informations:
I have a specific point with long/lat.
Then i draw a circle with a specific radius (e.g. 5km).
The intersections of all roads on the line of the circle must be displayed as a point.
My idea with photoshop:

I'm not a real coder, but a mathematician...
So I had the idea to calculate all coordinates, which have the specific radius (e.g. 5km) on the first step. The second step is to check, if the point is on a road. If the point is on a road, I save it in an array. If the point isn't on a road, I delete the point for the session. The third step is to display all points of the array on a map.
That first step works. The distance between the points on the line of the circle are about 0,5m. That is an acceptable tolerance. I get a list of coordinates with PHP. E.g. with 1km radius:

*

*B 32.0179859432° L 20.999880002°

*B 32.0179846637° L 20.9997800137°

*B 32.0179825847° L 20.9996800441°

*B 32.0179797064° L 20.9995801021°

*B 32.0179760289° L 20.9994801966°

*B 32.0179715527° L 20.9993803363°

*B 32.0179662781° L 20.9992805303°

*B 32.0179602056° L 20.9991807874°

*B 32.0179533358° L 20.9990811164°

*...

But that are to many results depending on the distance.
1km: 6663 points
10km: 66630 points
...
That are to many points. I can't use a reverse geocoding service to check, if every point is on a road. That would be about 60000 requests in one query. I believe, that only 0,1 % of the points are on a road, so my solution is not very efficient.
Do you habe any idea to solve my problem??
Maybe with frameworks like openlayers, or ...?
Or API's, which can display all coordinates with an specific distance to one point?


text:
Q: WP Background Processing - Class 'WP_Async_Request' not found I need to do some background processing on WordPress, I found this library:
https://github.com/deliciousbrains/wp-background-processing
I tried using the example plugin found here:
https://github.com/A5hleyRich/wp-background-processing-example
And every time I tried to activate the plugin The website crash and on PHP log show
PHP Fatal error:  Uncaught Error: Class 'WP_Async_Request' not found in....
Any help please, I really need this.
Thank you

A: WP_Async_Request class is not a part of WordPress.
You should have been installed woocommerce or install WP_Async_Request class and all this library directly.


text:
Q: switch to an existing Terminal Emulator using command (wmctrl) or shortcut key It's rather hard to do it. wmctrl needs to know the window title in order to operate on it, but it is damn hard to know the title of any terminal emulator, be it gnome-terminal, rxvt, xterm...
Because

*

*Often .bashrc specify PS1 to change window's title to current path.

*editor like VIM changes window's title to the current file.

*command line tools like mosh love to change window title.

*ssh into another machine, usually the shell (bash) on the remote host changes the title. So if you remove title-changing part of PS1 you need to do it to every computer you may connect to -- a long list of which for any seasoned sysop.

*Even if you run GNU Screen in a terminal, the session inside screen can still change the title of the outter terminal emulator.

fluxbox exceptionally allows referring to a window by other properties of the X-window (xwininfo) than title. but switching to fluxbox is too big a change for this small need.
In short, there seems to be no way to know the title of the terminal emulator window ... or, is there one?

A: Many terminal emulators (at least Xterm, Rxvt, Gnome-terminal and Konsole) set the WINDOWID environment variable to the X11 window ID. You can pass this window ID to wmctrl:
wmctrl -i -a "$target_window_id"

Beware that inside a Screen or Tmux session, you'll get the window ID where you initially started the multiplexer, not the one where it's currently attached.

A: Use wmctrl -l before and after the start of the terminal emulator and store the output both times. The line differing between the outputs will give you the ID of the window, using cut to automatically retrieve the first value (it is the ID).
This ID is independent of the title of the terminal emulator window. You can use that to do wmctrl -a ID until you close the terminal emulator and the ID is no longer valid.


text:
Q: [NodeJS]: Cannot set headers after they are sent to the client A full overview and answer can be find in the first answer:
Error: Can't set headers after they are sent to the client
I am using:

*

*Express

*mongoose (for MongoDB)

In registering new users, I wanted to check if the user's email or name already exist (cause they have to be unique).
I had this piece of code:
    try {
  let user = await User.findOne({ email })

  if (user) {
    res
      .status(400)
      .json({ status: 'error', body: [{ msg: 'email already exist' }] })
  }

  user = await User.findOne({ name })

  if (user) {
    res
      .status(400)
      .json({ status: 'error', body: [{ msg: 'name already exist' }] })
  }

// ... some more code

} catch(err) {

//... code

}

I was keep getting: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. Terminal doesn't show the exact place the error is created.

A: The response were res.status(400).json({ ... }) and not return res.status(400).json({ ... }).
Because of that, the code went on to the second condition and tried again to send a response, BUT express let us know that the response was already sent and it cannot change those resposne anymore...
The solution was quite simple - add return and make sure this code stops before trying to send another response.

A: I had the same problem but with a typo trying to send 2 times the response into my function. It seems its your case too. As mentioned by @David, the return statement makes a go out of the function...
resp.send('OK')
do_stuff
resp.send('OK')


text:
Q: How to access to the ServiceManager with Xamarin Android I'm developing an Android app using Xamarin.Android. I have to access to the ServiceManager in order to retrieve a specific IBinder. The ServiceManager is accessible and visible by Java applications, but I cannot see it on my Visual Studio project with the referenced Mono.Android dll.
Relative Java code:
IBinder b = ServiceManager.getService("<service-name>");

How can I get the same behaviour on C# with Xamarin.Android library?

A: try in your activity this: var a = Application.GetSystemService ("name-service");
Good luck


text:
Q: How to know If the given space is torsionfree? I'm given a metric
$$ds^2=g_{\mu\nu}dx^\mu dx^\nu=\left(1-\frac{r_g}{r}\right)c^2dt^2-\left(1+\frac{r_g}{r}\right)dr^2-r^2d\theta^2-r^2\sin^2\theta d\phi^2$$
where $r_g$ is a constant.
The torsion tensor is
$$T^k_{ij}\equiv \Gamma^k_{ij}-\Gamma^k_{ji}.$$
But the formula that I'm using that is
$$\Gamma^m_{ik}=\frac{1}{2}g^{ml}\left(\frac{\partial g_{li}}{\partial x^k}+\frac{\partial g_{lk}}{\partial x^i}-\frac{\partial g_{ik}}{\partial x^l}\right)$$
already assumes that the torsion tensor is zero. Can anyone help me out, How to see if $T^k_{ij}$ is zero or not?

A: Both torsion and curvature are properties of a connection, not an intrinsic property of a metric manifold itself.  For a given manifold $\mathcal M$ with pseudo-Riemannian metric $g$, you could equally well equip it with a connection $\nabla$ which has torsion or a connection $\nabla'$ which does not, so the metric components are not going to help you here.
Of the infinity of possible choices of connection for a given $(\mathcal M,g)$, there is one unique connection $\nabla^{LC}$ which is both metric-compatible $(\nabla^{LC} g = 0)$ and torsion-free; this is the Levi-Civita connection, and it is the choice that is made in standard GR.  Imposing both of those constraints yields the expression for the connection coefficients written in the OP,
$$\left(\Gamma^{LC}\right)^m_{ik}=\frac{1}{2}g^{ml}\left(\frac{\partial g_{li}}{\partial x^k}+\frac{\partial g_{lk}}{\partial x^i}-\frac{\partial g_{ik}}{\partial x^l}\right)$$
When we talk about torsion and curvature in the context of standard GR, we're talking about the torsion and curvature of the Levi-Civita connection.  Different choices for connection would yield different torsion and curvature. For example, the coefficients of any metric-compatible connection can be expressed in terms of those of the Levi-Civita connection via
$$\Gamma^m_{ik} = \left(\Gamma^{LC}\right)^m_{ik} + K^m_{ik}$$
where $K$ is the contorsion tensor.  As a more interesting example, one might consider teleparallel gravity which equips $(\mathcal M,g)$ with the Weitzenbock connection rather than the Levi-Civita connection; this connection is curvature-free but does possess generally non-vanishing torsion, and it is this torsion which is manifested in the effects of gravity.


text:
Q: Restrict querying for senders to a certain package I know there's SOUL. But perhaps Pharo can do the following without any additional packages: How can I restrict searches for senders and implementers to a certain category? Like: I want to see all senders of compile: in OmniBrowser.
More generally, how would you go and find the spot where compilation is invoked from OmniBrowser? (I roughly remember that some special code text pane was responsible for the compiler invocation, but forgot the details.)

A: *

*There is a detailed description of doing what you ask for in Pharo by Example, Chapter 14.4.

*Depending on the browsing context this is the method accept:notifying: of OBClassDefinition or OBMethodDefinition.

A: It is easy. Pharo comes with what it is called the Refactoring Browser, which has a lot of stuff, not only refactors. To do what you want, do:

*

*Go to the OmniBrowser package, select any category you want from OmniBrowser

*Right button -> Refactoring Scope -> category

That will open a new windows with all the classes of that scope (a particular category in this case). Then, if you search for senders for example, it will be only in that scope.
Cheers


text:
Q: How can I get first component of type? I want to get the first MonoBehaviour component to run a public void function.
I actually use ObjectReference.GetComponent<ComponentName>().FunctionName(); but it would take me so much time because there's multiple ObjectReference and that implicates that I can't use the same script name with diff source.

A: I found the solution here, thank you all for helping!!! https://answers.unity.com/questions/376676/accessing-a-script-without-knowing-its-name.html


text:
Q: Parsing json "dict of dicts" into sqlite3 database I love this new card game called Keyforge and I am an amateur data scientist that wants to provide the community with some cool tools and features. My ultimate aim is to develop an app that scans a fresh new deck's QR code and it tells you on the spot how good your new deck is and how it places compared to the rest of decks in the world. All of this using machine learning.
The company that makes the game has an API where I am pulling all the data from and it comes as a JSON object. I believe that it is a dict of dicts (I copied some of the JSON file below for you to confirm I am right). I don't have too much experience with JSON objects, but I am comfortable with python in general.
I am trying to parse or extract the data (all of it or some of it) into an sqlite3 database. I am fairly new to databases, so I am struggling.
Apart from doing JSON to sqlite 3, I also need to manipulate the data into the format I need for my learning algorithm, but I think I can cope with that.
I have tried many things that I found here and online, but none of them are working.
Below is the beginning and some middle part of one of the JSON files, so you can understand how the data is structured. I have read that I need to flatten it out first and I have tried a few things, but I have had no luck so far.
My aim is to have a table where each row is a deck (or sample for the learning algorithm). Below you can see a couple of decks: "Dr. The Old Jeffries" and "Gendry V. Rineity, the Enigmatic". The columns of the table would be a unique id number (the main key, auto-increase, etc.), basically 1, 2, 3, ... and so on, and the rest of the columns would be "name", "expansion", "power_level", etc. The actual minimum data I really need is the id number (the main key, auto-increase), the "card_number" for each of the 36 cards in each deck (this is a number from 1 to 370, which are the cards in the game) and then columns for "wins", "losses", "casual_wins" and "casual_losses", which is vital to train the learning algorithm on what is a good successful deck.
{
  "count": 459959, #this is how many decks are live in the World
  "data": [        #this contains the name of each deck and other data
    {
      "name": "Dr. \"The Old\" Jeffries",
      "expansion": 341,
      "power_level": 0,
      "chains": 0,
      "wins": 0,
      "losses": 0,
      "id": "ec86db52-e41e-4e6a-9f1a-a2d0e3d3277d",
      "is_my_deck": false,
      "notes": [],
      "is_my_favorite": false,
      "is_on_my_watchlist": false,
      "casual_wins": 0,
      "casual_losses": 0,
      "_links": {
        "houses": [
          "Brobnar",
          "Dis",
          "Logos"
        ],
        "cards": [        #this is the list of 36 cards for this deck
          "d438faa9-7920-437a-8d1c-682fade5d350",
          "d438faa9-7920-437a-8d1c-682fade5d350",
          "0ef760a3-68b9-42a9-93fa-419ea171917b",
          "68e2188c-4002-43d4-9fe1-0262df26c33f",
          "68e2188c-4002-43d4-9fe1-0262df26c33f",
          "3d650fe4-817a-4922-ba0f-297c1ebf816d",
          "652c4e38-c4fa-4e30-8f8d-036e95249529",
          "d4f666db-302f-43d0-b0af-bd03071f92ce",
          "0c3231e1-1230-4e7d-890e-6d3149125de2",
          "d792387f-8392-49b3-ad7c-ccaf7552256f",
          "f2c71c05-7a23-4465-8a89-82ab8e258a68",
          "e1312fbf-c297-4d9f-b403-2d892271de62",
          "d2edea65-7c2f-487f-a6f4-f44a077c4a65",
          "10715fd2-031a-47ca-9119-9b7b2ec1d2c0",
          "10715fd2-031a-47ca-9119-9b7b2ec1d2c0",
          "be492d70-5c87-441e-8223-79fb2bce85c9",
          "d42dd1d0-3462-410f-b683-dd0768b84188",
          "5607fecd-b90e-4e12-84bc-cb36d079117c",
          "ea2a390e-e121-4cbd-96c5-2430cc600e81",
          "96548d93-b318-40e3-9f5c-3297c8070ebd",
          "17e9dbd4-53cb-4c75-bdad-48e1550ff1e7",
          "916f271b-9928-437c-bfc4-d60d32af8c7c",
          "9ed7d241-1ca3-4a2a-b067-bb44776f7d4b",
          "b8343462-b5d7-48b0-9e3b-f020c5e73c55",
          "1283215c-3ea2-4d2b-9af4-452d7c0d57d9",
          "1283215c-3ea2-4d2b-9af4-452d7c0d57d9",
          "448c1335-d45b-473e-b222-d71f31ba0292",
          "448c1335-d45b-473e-b222-d71f31ba0292",
          "45d564a2-fcc9-4baa-8dc8-8e1a0fe2a37a",
          "5a521238-f524-48e3-b121-40c16e1f7610",
          "57bccc52-b6a1-4d11-b9d9-6356d8ac279c",
          "cd83ebe7-f961-4e5e-a00e-046d1be5e5d3",
          "53f7d3ec-a65f-4b05-8c82-74f44a7bdc44",
          "60f095d7-1816-4f14-88ec-04412ebde43b",
          "60f095d7-1816-4f14-88ec-04412ebde43b",
          "bec84d69-68f0-456c-a7bd-9f1e94d55a22"
        ]
      }
    },
    {
      "name": "Gendry V. Rineity, the Enigmatic",
      "expansion": 341,
      "power_level": 0,
      "chains": 0,
      "wins": 0,
      "losses": 0,
      "id": "48761c52-1bf0-4437-ba12-f0544237da4e",
      "is_my_deck": false,
      "notes": [],
      "is_my_favorite": false,
      "is_on_my_watchlist": false,
      "casual_wins": 0,
      "casual_losses": 0,
      "_links": {
        "houses": [
          "Dis",
          "Logos",
          "Mars"
        ],
        "cards": [
          "699f06e3-e47b-4910-90b9-c67fac157d6e",
          "10715fd2-031a-47ca-9119-9b7b2ec1d2c0",
          "10715fd2-031a-47ca-9119-9b7b2ec1d2c0",
          "aa73a693-e1e6-4097-8010-ddc820cc6d96",
          "9644c85a-12a7-44ff-a8bb-877dddb46995",
          "750a9323-9c07-4ae7-be5e-79367b4a2a8d",
          "c5ed37f7-0d05-48bc-a595-4f25c0ec1e6d",
          "f97316b0-75a4-45a4-8735-15e72cc1568c",
          "916f271b-9928-437c-bfc4-d60d32af8c7c",
          "3d6a02d0-b5c8-49be-93e4-dfdd5c1200eb",
          "9152cbad-d83f-4ee4-9846-87cc60d185f1",
          "b8343462-b5d7-48b0-9e3b-f020c5e73c55",
          "8c763540-bb69-47aa-be43-4a8ace89864c",
          "f51e8ec0-ab0e-46a8-a5f5-680039d6e664",
          "1838fbaa-a062-4593-acbe-53ecfadfb5cc",
          "1838fbaa-a062-4593-acbe-53ecfadfb5cc",
          "2cb1f58c-5979-4d3a-ae86-9dadc6000288",
          "2cb1f58c-5979-4d3a-ae86-9dadc6000288",
          "2cb1f58c-5979-4d3a-ae86-9dadc6000288",
          "448c1335-d45b-473e-b222-d71f31ba0292",
          "3c5c1881-486c-4911-a3ce-497ef258e8ba",
          "2ec5cbf6-3c41-41ef-9cb7-33a0601fd607",
          "2ec5cbf6-3c41-41ef-9cb7-33a0601fd607",
          "c08c91f0-043a-4a8a-8761-6080e9f46183",
          "16168a85-bbfa-4e54-8c84-5ea02e2a7da1",
          "cc44ca9a-6994-4897-9308-ff332cc8de57",
          "19b74b4e-bec8-4fbb-bd35-cb635f500249",
          "0cc7c1ea-5196-40ff-b408-f31997c8ab4d",
          "179f877a-9b59-46d6-a43e-15b4524af3c6",
          "0e5e8a55-ab05-44be-8637-8362974dad8b",
          "aabeebf7-1da5-4149-afab-e7e221b47d93",
          "a8a3578c-7a61-4e15-90ac-483daf2aff16",
          "1a84631d-7fcb-4c9a-a50c-9539dcb84928",
          "211c5213-7838-4292-b9c4-fb3a663898ee",
          "ac8fb9f6-ee8e-4434-85e8-d084a66c50db",
          "ff104cf4-f99d-4021-a570-dd949e559e97"
        ]
      }
    },

#...
#... there are 25 decks per page. I can only get that many per API call
#...

  "_linked": {     #here are the actual houses per deck and the actual cards
    "houses": [
      {
        "id": "Brobnar",
        "name": "Brobnar",
        "image": "https://cdn.keyforgegame.com/media/houses/Brobnar_RTivg44.png"
      },
      #...more data was in here but there is URL limit
      {
        "id": "Mars",
        "name": "Mars",
        "image": "https://cdn.keyforgegame.com/media/houses/Mars_CmAUCXI.png"
      }
    ],
    "cards": [
      {
        "id": "469dd68d-cdd6-40e0-8fc9-a167c45a9aea",
        "card_title": "Grasping Vines",
        "house": "Untamed",
        "card_type": "Action",
        "front_image": "https://cdn.keyforgegame.com/media/card_front/en/341_324_VH9R4P26824V_en.png",
        "card_text": "Play: Return up to 3 artifacts to their owners' hands.",
        "traits": null,
        "amber": 1,
        "power": 0,
        "armor": 0,
        "rarity": "Uncommon",
        "flavor_text": null,
        "card_number": 324,
        "expansion": 341,
        "is_maverick": false
      },
      {
        "id": "1a84631d-7fcb-4c9a-a50c-9539dcb84928",
        "card_title": "Yxilo Bolter",
        "house": "Mars",
        "card_type": "Creature",
        "front_image": "https://cdn.keyforgegame.com/media/card_front/en/341_204_H9HQ5F59FJQX_en.png",
        "card_text": "Fight/Reap: Deal 2<D> to a creature. If this damage destroys that creature, purge it.",
        "traits": "Martian • Soldier",
        "amber": 0,
        "power": 3,
        "armor": 0,
        "rarity": "Common",
        "flavor_text": null,
        "card_number": 204,
        "expansion": 341,
        "is_maverick": false
      },   #the data goes on for quite a bit

import json
import requests
import sqlite3
from datetime import datetime

DATE_FORMAT = '%Y-%m-%d'

class Keyforge():
#    def __init__(self):

    def download(self,pagestart,pagestop):
        #Downloads batches of 25 decks per page. pagestart=1,pagestop=5 will download the first 100 decks in the master vault
        for i in range(pagestart,pagestop):
            response = requests.get("https://www.keyforgegame.com/api/decks/?page="+str(i)+"&links=cards&page_size=25")
            raw_data = json.loads(response.text)
            someitem = raw_data.items()
            columns = list(someitem)
            print (columns)

            with open("keyforge_scraped"+str(i)+".json","w") as data_file:
                json.dump(raw_data,data_file,indent=2)
                print ("Generating batch number %d." % i)
        conn = sqlite3.connect('keyforge.db')
        c = conn.cursor()
        c.execute("CREATE TABLE "keyforge" ( `deck number` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, `deck name` TEXT, `cardID0` INTEGER, `cardID1` INTEGER, `cardID2` INTEGER, `cardID3` INTEGER, `cardID4` INTEGER, `cardID5` INTEGER, `cardID6` INTEGER, `cardID7` INTEGER, `cardID8` INTEGER, `cardID9` INTEGER, `cardID10` INTEGER, `cardID11` INTEGER, `cardID12` INTEGER, `cardID13` INTEGER, `cardID14` INTEGER, `cardID15` INTEGER, `cardID16` INTEGER, `cardID17` INTEGER, `cardID18` INTEGER, `cardID19` INTEGER, `cardID20` INTEGER, `cardID21` INTEGER, `cardID22` INTEGER, `cardID23` INTEGER, `cardID24` INTEGER, `cardID25` INTEGER, `cardID26` INTEGER, `cardID27` INTEGER, `cardID28` INTEGER, `cardID29` INTEGER, `cardID30` INTEGER, `cardID31` INTEGER, `cardID32` INTEGER, `cardID33` INTEGER, `cardID34` INTEGER, `cardID35` INTEGER, `Wins` INTEGER, `Losses` INTEGER, `Casual wins` INTEGER, `Casual losses` INTEGER )")
        for i in raw_data:
            c.execute("insert into keyforge values (columns[1],?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",columns)
            conn.commit()

        conn.close()
        return raw_data

"""    def updateDB(raw_data):
        conn = sqlite3.connect('keyforge.db')
        c = conn.cursor()
        c.execute("CREATE TABLE IF NOT EXISTS keyforge (id varchar(3), raw_data json)")
        for i in raw_data:
            c.execute("insert into keyforge values (?,?)",[i['id'], json.dumps(raw_data)])
            conn.commit()

        conn.close()
"""

start = int(input("Enter start page: "))
stop = int(input("Enter stop page: "))
a = Keyforge()
raw_data = a.download(start,stop)
#a.updateDB(raw_data)

You can see the mess I have created in my code by trying many different things. I am successful in downloading the JSON objects from the website and archiving them to my disk, but I am having no such luck with the sqlite database.
I have created manually using the GUI, the table I want, but I don't know how to populate such table from the JSON data.
Ultimately, what I want is to run my keyforge.py code, select from which page to which page (each page contains 25 decks worth of data) I want to download and process (archive in disk and store in database) and for this database to be updated and increased over time. Obviously, I would also process the data to feed it to my learning algorithm.
Can you guys give me a hand, please? I am stuck in the hole. Please, help me get out of the hole :)


text:
Q: Mysql FULLTEXT MATCH score is zero, in boolean mode, even though both terms are present I have a table squirrel_schools that has a FULLTEXT index on the keywords field (among others).
I'm doing a BOOLEAN search against two of the words in keywords and getting a score of zero, which doesn't make sense:
SELECT record_id, keywords, (MATCH (keywords) AGAINST ("+l4 +3rx" IN BOOLEAN MODE)) AS score
FROM squirrel_schools WHERE record_id = 46465;
+-----------+---------------------------+-------+
| record_id | keywords                  | score |
+-----------+---------------------------+-------+
|     46465 | l4 3rx l43rx 46465 104651 |     0 |
+-----------+---------------------------+-------+
1 row in set (0.017 sec)

As you can see, both "l4" and "3rx" are present in that column.  When the data is indexed, with this particular thing (a postcode), I also concatenate it and save that into keywords too.  Searching for the concatenated form DOES work:
SELECT record_id, keywords, (MATCH (keywords) AGAINST ("+l43rx" IN BOOLEAN MODE)) AS score
FROM squirrel_schools WHERE record_id = 46465;
+-----------+---------------------------+--------------------+
| record_id | keywords                  | score              |
+-----------+---------------------------+--------------------+
|     46465 | l4 3rx l43rx 46465 104651 | 22.382286071777344 |
+-----------+---------------------------+--------------------+

(When I say 'it works' i mean it gives it a score higher than zero)
Can anyone explain what's going on here?  Is there some hidden rule that is breaking the search, in the first example?
I'm using MYSQL 5.6.51.  Thanks.
EDIT:  i now suspect it breaks if I include any search word that is 2 characters long, or less.  Is that a general rule?

A: Read https://dev.mysql.com/doc/refman/5.6/en/fulltext-fine-tuning.html:

Configuring Minimum and Maximum Word Length
The minimum and maximum lengths of words to be indexed are defined by the innodb_ft_min_token_size and innodb_ft_max_token_size for
InnoDB search indexes, and ft_min_word_len and ft_max_word_len for
MyISAM ones. After changing any of these options, rebuild your
FULLTEXT indexes for the change to take effect. For example, to make
two-character words searchable, you could put the following lines in
an option file:
[mysqld]
innodb_ft_min_token_size=2
ft_min_word_len=2

Then restart the server and rebuild your FULLTEXT indexes.

I recommend reading the rest of the documentation about fulltext indexes if you are going to use them.


text:
Q: Como hacer echo de una variable superglobal en HTML Tengo una variable superglobal $_SESSION con un valor dentro y quiero hacer un echo en una pagina HTML pero no me aparece nada. Mi codigo es el siguiente :

  LogOut
  <?php echo $_SESSION['login']; ?>

Quiz: crazy questions

La cosa es que el echo no se ejecuta. Alguien sabe arreglarlo?

A: En la parte inferior de tu sitio tienes que poner la siguiente sentencia:
<?php session_start(); ?>

Supongo claramente que la variable $_SESSION la estas asignando desde un login.

Tu codigo html si debe quedar asi como lo tienes:

  LogOut
  <?php echo $_SESSION['login']; ?>

Quiz: crazy questions

Ejemplo:
<?php session_start();
$_SESSION['login'] = "wilson";
?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

      LogOut
      <?php echo $_SESSION['login']; ?>

Quiz: crazy questions

Puedes comprobar que existe tu variable $_SESSION con la siguiente condicional:
if(!isset($_SESSION["login"]))
 {
    echo "No existe o no esta seteada la SESSION";
    die();
 }else {
    echo "La SESSION login si existe $_SESSION['login']";
}

Esa condicional la debes poner justo después del session_start();, siempre va de primero de todo el session_start();


text:
Q: flutter icon is not centered in container I was trying to center the icon in a circular background but it failed even if I use a center widget as child unless increase container size.

    Container(
                  height: 22,
                  width: 22,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Color(0xffF7825C),
                  ),
                  child: Center(
                    child: Icon(
                      Icons.add,
                      color: Colors.white,
                    ),
                  ),
                )

A: Try this:
             Container(
              alignment: Alignment.center,
              height: 22,
              width: 22,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Color(0xffF7825C),
              ),
              child: Icon(
                  Icons.add,
                  color: Colors.white,
                  size: 22
                ),
            )

A: You need to set the size of your icon with size attribute, so your Icon widget should look like this
Icon(
    Icons.add,
    color: Colors.white,
    size: 22
)

A: You can also use RawMaterialButton, You can set it like this
RawMaterialButton(
              onPressed: () {},
              fillColor: Color(0xffF7825C),
              child: Icon(
                Icons.add,
                size: 22.0,
                color: Colors.white,
              ),
              shape: CircleBorder(),
            )

A: Issue can be solve by giving size to Icon
Container(
    width: 40,
    height: 20,
    child: Icon(
        Icons.arrow_right_alt_outlined,
        color: Colors.white,
        size: 20,),
    ),

the above thing works because now we have the container which can contain whole icons size
( 40x20(container) can contain 20(icon))
but if this icons size gets bigger than container dimension there we meshed up the centering of icon inside container
hope this explanation works!

A: use the following :
Container(
              height: 22,
              width: 22,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Color(0xffF7825C),
              ),
              alignment: Alignment.center,
                child: Icon(
                  Icons.add,
                  color: Colors.white,
                ),

            )


text:
Q: Permission error running any git command in makefiles I've been slowly going insane from a recurring permission error encountered when running any git command within any makefile:
for instance running make against:
a:
    git --version

will result in:
make: git: Permission denied
make: *** [makefile:<line number>: <target>] Error 127

Observations:

*

*occurs for even the most trivial of commands, e.g. git status

*occurs when running as root

*occurs regardless of directory and file permissions

*the given command runs without issue if run directly

*after reformatting and reinstalling my OS the problem went away but has resurfaced after a few months

*BSD bmake seems to work okay

Environment:

*

*Arch Linux x86-64

*GNU Make v4.3

*Git v2.26.2

I use makefiles extensively at work and this problem has slowly become more and more frustrating. If anyone has any insights or suggestions on how to fix this issue it would be greatly appreciated. Thank you.

A: It would be really, really helpful if you provided the recipe you're trying to run that's giving the above error, or even the make output of the command that was invoked.  Without that we can only guess, which is kind of a waste of everyone's time :)
My suspicion is this: you have a directory on your $PATH which has a directory named git in it, and this appears before /usr/bin in your $PATH.
There's a bug in GNU make 4.3 (actually the bug was in gnulib, which GNU make uses) which didn't correctly ignore directories when searching PATH.
However, this cannot be the problem if your recipe invokes git in a non-trivial way (as part of a shell script).
The fastest way to check this is just to add a semicolon to your command line; you didn't show us the entire recipe so we can't be sure but if you have:
foo:
        git --version

try changing this to:
foo:
        git --version;

and see if it works.


text:
Q: SELECT max(item.id) FROM Table not working I'm trying to run this query SELECT max(item.id) FROM Table, but it returns javax.persistence.PersistenceException: java.lang.NullPointerException. The table is not empty. I tried it in PHPMyAdmin and it works.
This is my code:
public Long generateId(String beanName, String idName) {
        String requete = "SELECT max(item." + idName + ") FROM " + beanName + " item";
        List<Long> maxId = getEntityManager().createQuery(requete).getResultList();
        if (maxId == null || maxId.isEmpty() || maxId.get(0) == null) {
            return 1L;
        }
        return maxId.get(0) + 1;
    }

The relevant stack:
Caused by: javax.persistence.PersistenceException: java.lang.NullPointerException
    at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:480)
    at service.AbstractFacade.generateId(AbstractFacade.java:61)
    at service.NotificationFacade.preparerNotification37(NotificationFacade.java:340)
    at service.NotificationFacade.estimerMontantNotification(NotificationFacade.java:417)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
    at sun.reflect.GeneratedMethodAccessor95.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.GeneratedMethodAccessor94.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    ... 54 more
Caused by: java.lang.NullPointerException
    at org.eclipse.persistence.internal.sessions.CollectionChangeRecord.addAdditionChange(CollectionChangeRecord.java:106)
    at org.eclipse.persistence.internal.queries.ContainerPolicy.compareCollectionsForChange(ContainerPolicy.java:560)
    at org.eclipse.persistence.mappings.CollectionMapping.compareCollectionsForChange(CollectionMapping.java:574)
    at org.eclipse.persistence.mappings.CollectionMapping.calculateDeferredChanges(CollectionMapping.java:541)
    at org.eclipse.persistence.descriptors.changetracking.AttributeChangeTrackingPolicy.createObjectChangeSet(AttributeChangeTrackingPolicy.java:75)
    at org.eclipse.persistence.descriptors.changetracking.DeferredChangeDetectionPolicy.calculateChanges(DeferredChangeDetectionPolicy.java:91)
    at org.eclipse.persistence.descriptors.changetracking.AttributeChangeTrackingPolicy.calculateChangesForExistingObject(AttributeChangeTrackingPolicy.java:48)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:664)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.writeChanges(RepeatableWriteUnitOfWork.java:438)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:863)
    at org.eclipse.persistence.internal.jpa.QueryImpl.performPreQueryFlush(QueryImpl.java:963)
    at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:207)
    at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:469)
    ... 86 more


text:
Q: Which event is called first? OnTick() or OnTimer()? If I am processing OnTick events as well as OnTimer events, is there a preference in the queue?  When calculating time sensitive algorithms in seconds, I am wondering whether it is easier to write a whole EA inside OnTimer to avoid event handling issues.

A: OnTimer is the scheduled call. If your current OnTimer call takes long to process, the succeeding OnTimer might be skipped. Same with OnTick.
If suppose the EA starts at 00:00:00.021 with EventSetTimer(1);, then the EA will call it each second at 21-th millisecond( well, some people says that is not always true but it is acceptable in most cases). At the same time it is possible that you receive more ticks during a second, or no ticks at all. If some action is important, OnTimer() may help with that.
What is the criteria that you should use OnTimer()? In MT4 one of the examples is using renko charts(in real time, for tests the call is off in MT4). For both MT4&5 OnTimer() is fine if you work with multicurrency expert. You may control OnTick of one symbol but not for both/all, OnTimer is called even if new tick did not arrive.


text:
Q: Why define \0 as the first element of a char array in C? When I read BlueZ source code, I often see char arrays defined like this:
// bluez/android/sco-msg.h
static const char BLUEZ_SCO_SK_PATH[] = "\0bluez_sco_socket";

What good is it to define the first element as \0?

A: In your particular case this array is used as pathname for a PF_LOCAL socket; see here. And leading NUL is used to point that address is an abstract one. From man 7 unix:

an abstract socket address is distinguished by the fact that
  sun_path[0] is a null byte ('\0').

And this is the only reason why the first element is \0.


text:
Q: App does not save data before activity closes, or not loading data after activity is created - SharedPreferences Data on main activity doesn't save / load properly with SharedPreferences
See link above to original questions and responses from other people... to sum it up, SharedPreferences is either not saving or not loading data properly... see pictures of my app, it will better show the problem:
Screenshots of my app in progress
As far as the code behind main activity, I have tried different things suggested by different people, and i appreciate anyone who was or is willing to help :)  At this very moment, this is the code relevant to the problem in MainActivity:  (Please note:  To save on space, I am only showing one Bundle (getFromQuizOne), but I have the same kind of Bundle / Bundle code for all 10 quizzes.    Also, I only put in one quiz button setOnClickListener, but same kind of code applies for all other quiz buttons).
            //Get points from Quiz One
            Bundle getFromQuizOne = getIntent().getExtras();
            if(getFromQuizOne != null)
            {
                //Get points from Quiz One
                numberQuizOnePoints = getFromQuizOne.getInt("PointsFromAllQuizOne");

                SharedPreferences shareInt = getApplicationContext().getSharedPreferences(QUIZ, MODE_PRIVATE);
                SharedPreferences.Editor editInt = shareInt.edit();

                //Save the value of points from Quiz One with SharedPreferences
                editInt.putInt("quizOnePointsYeah", numberQuizOnePoints);
                editInt.commit();

                //Call arrayMethod, which uses for loop to get and display value of points for each quiz
                arrayMethod();
            }//end if

            //My actual project has same kind of Bundle for all other quizzes, but to save space, i am just listing Bundle for quiz 1

            //Directs user to Quiz One, first screen
            quizOneButton.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    //Subtract out any points that user already got for Quiz 1 from total...
                    //In case user wants to or has to re-take Quiz 1
                    totalPoints = totalPoints - numberQuizOnePoints;

                    //Subtract out any points that user already got for Quiz 1 from itself, equal 0
                    numberQuizOnePoints -= numberQuizOnePoints;

                    //Go to the Quiz One, first screen

                    Intent directToQuizOnePartOne = new Intent();
                    directToQuizOnePartOne.setClass(getBaseContext(), QuizOnePartOne.class);
                    startActivity(directToQuizOnePartOne);
                    finish();
                }//end void onClick quizOne
            });//end setOnClickListener quizOne

            //My project has button click listeners for all 10 quizzes, that look similar to quizOneButton onClick action listener, but to save on space, I didn't paste it here

        public void arrayMethod()
        {
            int[] points = {numberQuizOnePoints, numberQuizTwoPoints, numberQuizThreePoints,
            numberQuizFourPoints, numberQuizFivePoints, numberQuizSixPoints, numberQuizSevenPoints,
            numberQuizEightPoints, numberQuizNinePoints, numberQuizTenPoints};

            String[] prefKeys = {"quizOnePointsYeah", "quizTwoPointsYeah", "quizThreePointsYeah",
            "quizFourPointsYeah", "quizFivePointsYeah", "quizSixPointsYeah", "quizSevenPointsYeah",
            "quizEightPointsYeah", "quizNinePointsYeah", "quizTenPointsYeah"};

            SharedPreferences shareInt = getApplicationContext().getSharedPreferences(QUIZ, MODE_PRIVATE);

            for (int i = 0; i < 10; i++)
            {
                if (shareInt.getInt(prefKeys[i], 0) > 0)
                {
                    points[i] = shareInt.getInt(prefKeys[i], 0);
                }//end if
                else
                {
                    points[i] = 0;
                }//end else
            }//end for loop

            //Sum up points from each quiz, and put sum in totalPoints variable
            totalPoints = numberQuizOnePoints + numberQuizTwoPoints + numberQuizThreePoints
                    + numberQuizFourPoints + numberQuizFivePoints + numberQuizSixPoints
                    + numberQuizSevenPoints + numberQuizEightPoints + numberQuizNinePoints
                    + numberQuizTenPoints;

            quizOnePointsText.setText(String.format("%d", numberQuizOnePoints));
            quizTwoPointsText.setText(String.format("%d", numberQuizTwoPoints));
            quizThreePointsText.setText(String.format("%d", numberQuizThreePoints));
            quizFourPointsText.setText(String.format("%d", numberQuizFourPoints));
            quizFivePointsText.setText(String.format("%d", numberQuizFivePoints));
            quizSixPointsText.setText(String.format("%d", numberQuizSixPoints));
            quizSevenPointsText.setText(String.format("%d", numberQuizSevenPoints));
            quizEightPointsText.setText(String.format("%d", numberQuizEightPoints));
            quizNinePointsText.setText(String.format("%d", numberQuizNinePoints));
            quizTenPointsText.setText(String.format("%d", numberQuizTenPoints));
            actualPointsText.setText(String.format("%d", totalPoints));
        }//end void arrayMethod
    }//end class MainMenu

A: I'm not completely sure that I know what you want, but from my understanding you should be loading and saving that data during a state that you know will get called such as onPause();. You should also take a look at the Android Activity Lifecycle
here's a somewhat related snippet from my app
@Override
protected void onPause(){
    super.onPause();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState); // the UI component values are saved here.
    outState.putStringArrayList("mList", new ArrayList<>(fretList));
    Toast.makeText(this, "Activity state saved", Toast.LENGTH_SHORT).show();
}

@Override
protected void onRestoreInstanceState(Bundle inState) {
    super.onRestoreInstanceState(inState); // the UI component values are saved here.
    // if there is a non empty bundle, then pull arraylist from it, clear old list
    // just in case, and add all bundle items to it.
    if (inState != null) {
        ArrayList bundledList = inState.getStringArrayList("mList");
        if (bundledList != null && bundledList.size() > 0) {
            fretList.clear();
            fretList.addAll(bundledList);
        }
    }
    mAdapter.notifyDataSetChanged();
    Toast.makeText(this, "Activity state restored", Toast.LENGTH_SHORT).show();
}

Edit: I'm now looking over your other linked question trying to understand your question better. You can do some simple checking with Log.d() to find out where you lose the bundle/data
if (getFromQuizOne != null)
    {
        Log.d("Test", "not null");
    } else {
        Log.d("Test", "null");
    }

If you want to explicitly save something without waiting you can move it to your own method and call it whenever you want (this is using shared prefs rather than bundle):
public void save(Context context, String text) {
    SharedPreferences settings;
    SharedPreferences.Editor editor;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();

    editor.putString("someString", text);
    editor.commit();
}


text:
Q: SQL PHP Search column name with value Ok so I have a db of Users (ID) and their T or F results to different Hobbies.  So something like this, excuse the formating I didn't know how to space it.
ID   | swimming | running | rock climbing | learning to program.

user1       T         F            T                  T

user2       F         T            T                  F

OK I wanted to do a SQL search where I return all Column names of a table, if the value of that column is "T" where the ID is the users ID.
so if the ID is user1, I return swimming, rock climbing, learning to program.
Now I couldn't figure out how to do this with SQL so I figured I could try do this manually with PHP.
So I tried something like this.
 $stmt = $this->con->prepare("SELECT swimming, running, rock,
 program FROM mytablehere WHERE ID = ?");
 $stmt->bind_param("s", $ID);  // specific ID is went in via here
        $stmt->execute();
        $stmt->bind_result( $swimming, $running, $rock, $program);
        $stmt->fetch();
        $user = array();
 if($swimming == "T"){
 $swimming ="swimming";
 $user['swimming'] = $swimming; }
  ...
return $user;

So the idea is it would find the binds that are "T" and insert them into the user array, and leave the ones that are "F" out.
However my postman tells me, no data is found.
So my question is how do do I get this sort of function.  Is there an SQL search to make this easier or how do I need to approach my PHP code differently.
Can I not if then the bind $swimming or do I have to bind them all to one array, and then return a different array at the end?

A: if($user['swimming'] == "T"){
    $hobby['swimming'] = "swimming"; }

  return $hobby

there should really be an easier way to do this.  If anyone has an sql search that would be great.  But this will allow you to do it via php.  I was having issues with my postman which was stopping me from getting data, but once I did the code up top will just give you an useless mess.  This will return only the column names but it has to be done manually.


text:
Q: Prove that if $a^n-1$ is prime, then $a=2$ and $n$ is prime. Prove that if $a^n-1$ is prime, then $a=2$ and $n$ is prime.
I just started a semester with Number Theory, and I don't know how I am expected to be dealing with such questions. I am really frustrated. I would really appreciate your help.

A: Hint:$a^n-1= (a-1)(a^{n-1}+\cdots+a+1)$.


text:
Q: How to handle multiple forms in google app engine? Say if I have  multiple forms with multiple submit button in a single page, can I somehow make all of these buttons work using webapp as backend handler? If not, what are the alternatives?

A: The framework you use is irrelevant to how you handle forms. You have a couple of options: you can distinguish the forms by changing the URL they submit to - in which case, you can use the same handler or a different handler for each form - or you can distinguish them based on the contents of the form. The easiest way to do the latter is to give your submit buttons distinct names or values, and check for them in the POST data.

A: One way to do this—that is specific to Google App Engine—is the following:
HTML forms:
<input type="submit" name="number1">
<input type="submit" name="number2">

Then add the following to your python handler:
number1_button = self.request.get('number1')
number2_button = self.request.get('number2')

if number1_button:
    #number 1 was pressed
elif number2_button:
    #number 2 was pressed


text:
Q: How to make App Bundle for Google play on Unity3D 2018.1.4f I am trying to make a .aab file for my Unity3D game, but I can't find any option for .abb in build settings.
I'm using Unity 2018.1.4f.
Does this version of Unity not have support for .abb?

A: 2018.1 doesn't support app bundle, you need upgrade to 2018.3 at least.


text:
Q: Firebase deleting value not working properly I want to delete the post of the current user or current uid. The uid of the user who posted is specified in the JSON by the String: uid. So i search for the uid in the snapshot, and if it exists i delete the parent of that uid. The problem is that all posts get deleted instead of just the one with the current uid stored.
JSON tree
Posts
    -LBzjsl0Yfwdyh9xg6D2 (this is random uid)

           photoUrl: "https://firebasestorage.googleapis.com/v0/b/blo..."

           uid: "BBPHwd0RRibXFCvHcXA2aKbHoTm1" (this is uid of the current user)

Code:
let user = Auth.auth().currentUser?.uid

databaseRef.child("Posts").queryOrdered(byChild: "uid").queryEqual(toValue: user).observeSingleEvent(of: .value, with: { (snapshot) in

            if snapshot.exists() {

            //find out parent of current post
                let parent = snapshot.ref.parent!.key
                let ref = Database.database().reference()
                print (parent)
                func remove(child: String) {
                    ref.removeValue { error, _ in

                    }
                }
                remove(child: parent)

A: When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
So your snapshot variable holds a list of results. The parent of that list is the Posts node. So if you delete the parent, all nodes will be removed.
To remove only the nodes matching your query, you need to loop over the snapshot's child nodes, and delete those:
databaseRef.child("Posts").queryOrdered(byChild: "uid").queryEqual(toValue: user).observeSingleEvent(of: .value, with: { (snapshot) in
  for child in (snapshot?.children)! {
    (child as AnyObject).ref.removeValue()  { error, _ in
    }
  }
}


text:
Q: Visualforce: Dynamically ReRender a row within  by passing $Component through controller I have a typical form with <apex:repeat> for some fields. The <apex:inputText> elements have an onChange attribute that references a script that then calls an <apex:actionFunction>, for example:
Repeat Fields:
<apex:repeat value="{!myList}" var="i">
    <apex:outputPanel id="rowOfMyList" styleClass="row field-row" layout="block">
        <apex:inputText id="inputId" value="{!i.obj.value}" html-data-index="{!i.obj.index}" html-data-render="{!$Component.rowOfMyList}" onChange="updateField(this)"/>
    </apex:outputPanel>
</apex:repeat>

JS Script:
function updateField(row) {
    myActionFunction(row.getAttribute('data-index'), row.value, row.getAttribute('data-render'));
}

Action Function:
<apex:actionFunction action="{!pageRefMethod}" name="myActionFunction" rerender="{!renderRow}" >
    <apex:param name="index" value=""/>
    <apex:param name="goal" value=""/>
    <apex:param name="render" assignTo="{!renderRow}" value=""/>
</apex:actionFunction>

When I debug my controller I get exactly what I would expect, the dynamic Id selector that salesforce puts on my managed <apex:outputPanel>. I even then take that debug and run a search on the html source code and get an exact match on the element I expected to rerender. Unfortunately it does not rerender.
If I concatenate another ID from outside of the repeat tag to my html-data-render attribute it too gets passed through to my rerender="{!renderRow}" and it does rerender
Any thoughts on this would be awesome!

A: Through attempting this same problem on another project I was able to get a fresh look at the issue. What I learned through countless testing is that rerender attribute can be very tricky. For example:

*

*As many already know, if you do not provided the rerender attribute in your actionFunction then your parameters will not be sent.

*Rerender cannot be a dynamic value, meaning that EVEN IF you statically put the visualforce rendered ID (i.e. j_id0:j_id38), it will not rerender

*Rerender cannot be bound to a controller instance variable. Along the lines of the previous statement, besides the trickyness of dynamically binding a component ID to a variable, even if you do it would not rerender

What it comes down to is, in order to provide a dynamic component Id to the rerender attribute you must use the $Component variable to dot notate through your ID.
Here is a barebones look at what I mean within the context of the OP:
Visualforce Repeat Fields:
<apex:repeat id="myRepeater" value="{!myList}" var="i">
    <apex:outputPanel id="myRow" layout="block">
        <apex:inputText id="inputId" value="{!i.obj.value}" html-data-index="{!i.obj.index}" html-data-render="" onChange="updateField(this)"/>
    </apex:outputPanel>
</apex:repeat>

NOTE: Added an ID to the repeat tag, AND remove the html-data-render attribute since there is no use attempting to dynamically PASS the component ID

Visualforce JS Script:
function updateField(row) {
    myActionFunction(row.getAttribute('data-index'), row.value);
}

Visualforce ActionFunction:
<apex:actionFunction action="{!pageRefMethod}" name="myActionFunction" rerender="{!$Component.myRepeater.myRow}" >
    <apex:param name="index" value=""/>
    <apex:param name="goal" value=""/>
</apex:actionFunction>

Notice that rather than PASSING the specific row ID through some html pass-through attribute, I instead call the ID within rerender attribute directly.

Now don't believe this ONLY rerenders my "affected/selected" row, pretty sure all rows that fall within that Component ID selector are being rerendered (I can't even tell), BUT on the plus side it only rerenders the rows themselves and not the container, which to the user makes no difference (considering there is no flickering or visual glitch). Really the best part is, it WORKS!


text:
Q: tokenize a char* for a shell program I'm making a shell program that supports both user arguments and io redirection. I am having trouble with io redirection, eg:
$cat < hello > world

first I save the arguments in a char* array. I check if the first char is < or > and if it is I need to shave off the first character and make a file descriptor.
Here's what I'm doing.
    char* args[50];//<-- cat <hello and >world are in here
    char* fd[2];
    int fdin, fdout;
    if(args[j][0] == '<'){
        close(fdout);
        strncpy(fd[0], args[j][1]. strlen(args[j])-1);
        fdin = open(fd[0], O_RDONLY);
    }

A: To ease your work, begin drafting what your input looks like in some formal language, for example:
line : ID+ ( '<' ID | '>' '>'? ID )* ( '|' line )* '\0'

Where ID is run of chars where each either isAlpha or isDigit or isSpecial separated by other chars (like spaces, tabs, '>', '<', '|' and so on.
During the parsing it will be easier to add the first part (ID+) in a linked list and later translate that list to argv-argc pair.
The rest are treated specially (not in the linked list because they are not as general):

*

*IO redirection with '<' and '>' and '>>'; then

*pipelining with '|'.

Since the language is recursive (note the ( '|' line )*) your parser lends itself easily also to a recursive function (see? you have a function parse and when it reaches '|' it calls itself to parse the rest).
NB: although I expressed the line syntax in something like BNF notation doesn't mean that you should use a language parsing lib or compiler (yacc comes to mind). This language is just too simple and easy to implement to worth all the headache that come with these tools.

A: I assume you have never worked with the argc and argv parameters of main() before? You don't need to create your own array, C already does that for you.  You end up with this argv array:
argv[0] = "cat"
argv[1] = "<"
argv[2] = "hello"
argv[3] = ">"
argv[4] = "world"

Or:
argv[0] = "cat"
argv[1] = "<hello"
argv[2] = ">world"

Or any combination of that, depending on the whitespace used on the command line parameters.
Then you can do something like this (error handling omitted from brevity):
int main(int argc, char** argv)
{
    char* fd[2];
    int fdin = -1, fdout = -1;

    fd[0] = fd[1] = NULL;

    for (int i = 1; i < argc; ++i)
    {
        if (argv[i][0] == '<')
        {
            if (argv[i][1] != '\0')
                fd[0] = &(argv[i][1]);
            else
                fd[0] = argv[i+1];

            fdin = open(fd[0], O_RDONLY);
        }

        else if (argv[i][0] == '>')
        {
            if (argv[i][1] != '\0')
                fd[1] = &(argv[i][1]);
            else
                fd[1] = argv[i+1];

            fdout = open(fd[1], O_WRONLY);
        }
    }

    ...

    if (fdin != -1)
        ... read from fdin as needed ...
    else
        ... read from stdin as needed ...

    ...

    if (fdout != -1)
        ... write to fdout as needed ...
    else
        ... write to stdout as needed ...

    ...

    if (fdin != -1)
       close(fdin);

    if (fdout != -1)
        close(fdout);

    return 0;
}


text:
Q: How to use a variable docker image in github-actions? I am trying to write a custom github-action that runs some commands in a docker container but allows the user to select which docker container they are run in (i.e. so I can run the same build instructions across different versions of the runtime environment)
My gut instinct was to have my .github/actions/main/action.yml file as
name: 'Docker container command execution'
inputs:
  dockerfile:
    default: Dockerfile_r_latest
runs:
  using: 'docker'
  image: '${{ inputs.dockerfile }}'
  args:
   - /scripts/commands.sh

However this errors with:
##[error](Line: 7, Col: 10): Unrecognized named-value: 'inputs'. Located at position 1 within expression: inputs.dockerfile
Any help would be appreciated !
File References
My .github/workflow/build_and_test.yml file is:
name: Test Package

on:
  [push, pull_request]

jobs:

  R_latest:

    name: Test on latest
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@master
        name: Checkout project

      - uses: ./.github/actions/main
        name: Build and test
        with:
          dockerfile: Dockerfile_r_latest

And my Dockerfile .github/actions/main/Dockerfile_r_latest is:
FROM rocker/verse:latest
ADD scripts /scripts
ENTRYPOINT [ "bash", "-c" ]

A: Interesting approach! I'm not sure if it's possible to use expressions in the image field of the action metadata. I would guess that the only fields that can take expressions instead of hardcoded strings are the args for the image so that the inputs can be passed.
For reference this is the args section of the action.yml metadata.
https://help.github.com/en/articles/metadata-syntax-for-github-actions#args
I think there are other ways to achieve what you want to do. Have you tried using the jobs.<job_id>.container syntax? That allows you to specify an image that the steps of a job will run in. It will require that you publish the image to a public repository, though. So take care not to include any secrets.
For example, if you published your image to Docker Hub at gowerc/r-latest your workflow might look something like this:
name: Test Package

on:
  [push, pull_request]

jobs:

  R_latest:

    name: Test on latest
    runs-on: ubuntu-latest
    container: gowerc/r-latest
    steps:
      - uses: actions/checkout@master
        name: Checkout project

      - name: Build and test
        run: ./scripts/commands.sh

ref: https://help.github.com/en/articles/workflow-syntax-for-github-actions#jobsjob_idcontainer
Alternatively, you can also specify your image at the step level with uses. You could then pass a command via args to execute your script.
name: my workflow
on: push
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@master
      - name: Check container
        uses: docker://alpine:3.8
        with:
          args: /bin/sh -c "cat /etc/alpine-release"

ref: https://help.github.com/en/github/automating-your-workflow-with-github-actions/workflow-syntax-for-github-actions#example-using-a-docker-hub-action

A: In addition to @peterevans answer, I would add there's a 3rd option where you can use a simple docker run command and pass any env that you have defined.
That helped to solve 3 things :

*

*Reuse a custom docker image being build within the steps for testing actions. It seems not possible to do so with uses as it first tries to pull that image that doesn't exist yet in a Setup job step that occurs before any steps of the job.

*This specific image can also be stored in a private docker registry

*Be able to use a variable for the docker image

My workflow looks like this :
name: Build-Test-Push
on:
push:
    branches:
    - master
env:
    AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
    AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
    ECR_REGISTRY: ${{ secrets.AWS_ECR_REGISTRY }}
    ECR_REPOSITORY: myproject/myimage
    IMAGE_TAG: ${{ github.sha }}

jobs:

build-and-push:
    runs-on: ubuntu-latest
    steps:
    - name: Checking out
    uses: actions/checkout@v2
    with:
        ref: master

    - name: Login to AWS ECR
    id: login-ecr
    uses: aws-actions/amazon-ecr-login@v1

    - name: Build
    run: |
        docker pull $ECR_REGISTRY/$ECR_REPOSITORY || true
        docker build . -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG -t $ECR_REGISTRY/$ECR_REPOSITORY:latest

    - name: Test
    run: |
        docker run $ECR_REGISTRY/$ECR_REPOSITORY:latest /bin/bash -c "make test"

    - name: Push
    run: |
        docker push $ECR_REGISTRY/$ECR_REPOSITORY

A: Here is another approach. The Docker image to use is passed to a cibuild shell script that takes care of pulling the right image.
GitHub workflow file:
name: 'GH Actions CI'

on:
  push:
    branches: ['*master', '*0.[0-9]?.x']
  pull_request:
    # The branches below must be a subset of the branches above
    branches: ['*master', '*0.[0-9]?.x']

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest

    strategy:
      fail-fast: true
      matrix:
        include:
          - FROM:     'ubuntu:focal'
          - FROM:     'ubuntu:bionic'
          - FROM:     'ubuntu:xenial'
          - FROM:     'debian:buster'
          - FROM:     'debian:stretch'
          - FROM:     'opensuse/leap'
          - FROM:     'fedora:33'
          - FROM:     'fedora:32'
          - FROM:     'centos:8'

    steps:
    - name: Checkout repository
      uses: actions/checkout@v2
      with:
        # We must fetch at least the immediate parents so that if this is
        # a pull request then we can checkout the head.
        fetch-depth: 2

    # If this run was triggered by a pull request event, then checkout
    # the head of the pull request instead of the merge commit.
    - run: git checkout HEAD^2
      if: ${{ github.event_name == 'pull_request' }}

    - name: Run CI
      env:
        FROM: ${{ matrix.FROM }}
      run: script/cibuild

Bash script script/cibuild:
#!/bin/bash

set -e

docker run --name my-docker-container $FROM script/custom-script.sh
docker cp my-docker-container:/usr/src/my-workdir/my-outputs .
docker rm my-docker-container

echo "cibuild Done!"

Put your custom commands in script/custom-script.sh.


text:
Q: How can I convert to size_t from int safely? Assigning an int to a size_t (or using it in malloc) in GCC produces the following warning:

warning: conversion to 'size_t' from 'int' may change the sign of the result [-Wsign-conversion]

To solve this, I would like to wrap the conversion in a function that first checks if the conversion is valid, then does the cast.
This is what I have so far:
/* Convert int src to size_t dst. */
/* Assumes dst points to valid size_t address. */
int safe_size_t_from_int(size_t *dst, int src) {
    if(src < 0) return SAFE_ERROR_NEGATIVE;
    if(SIZE_MAX < INT_MAX) {
        if(src > (int)SIZE_MAX) return SAFE_ERROR_OVERFLOW;
    }
    *dst = (size_t)src;
    return SAFE_SUCCESS;
}

Am I missing anything? Is there a library with safe conversions that already exists?
The closest thing I can find is Microsoft Intsafe.h, but it appears to be for Win32 types only.
EDIT Modified as per chux' comment.

A: To avoid compiler warnings in GCC, limit the action performed by a single cast operation to one of the following:

*

*truncation or extension

*cast away signed-ness or unsigned-ness

*cast away const-ness or non-const-ness

size_t is always an unsigned type large enough to hold a void pointer. Casting from
int to size_t involves two cast operations: extend, then cast away signed-ness.
Here's two functions that produce no compiler warnings (with '-Wall -Werror -Wextra') on GCC 4.8.3. They return failure inline (via sentinel values), rather than in an extra return parameter.
int size_t2int(size_t val) {
    return (val <= INT_MAX) ? (int)((ssize_t)val) : -1;
}

size_t int2size_t(int val) {
    return (val < 0) ? __SIZE_MAX__ : (size_t)((unsigned)val);
}


text:
Q: How to publish Facebook custom graph stories? Though I successfully published the action as test user from development mode of Android App, Facebook is still showing the below message when I am trying to submit this action for review.

*

*Image of Shared in Facebook

*Image of Alert while submitting App action for review to Facebook
This is the code sample for share the action.
 ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
            .putString("og:type", "game")
            .putString("og:title", "Janoki Tiger English Competition!")
            .putString("og:description", "I got " + ans + " score in Janoki Tiger English Competition! I'm ranked " + rank + "th out of " + participants + " participants!")
                    //give a image url here
            .putString("og:image", "")
            .putString("og:url", "https://play.google.com/store/apps/details?id=venturas.bd.janoki")
            .putString("fb:app_id","")

            .build();

    // Create an action
    ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
            .setActionType("venturas-bd-janoki:game")
            .putObject("game", object)
            .build();

    // Create the content
    ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
            .setPreviewPropertyName("game")
            .setAction(action)
            .build();
ShareDialog.show(this, content);


text:
Q: Two rows with different sizes in Bootstrap Navbar I would like to have a Navbar in Bootstrap that looks like
+---------------------------------------------------+
|                               press | login | ... | <-second nav with smaller
+---------------------------------------------------+   height, text, ...
|   LO   |       |     |     |                      |
|   GO   |  HOME | FOO | BAR |                      | <-main menu with normal
+---------------------------------------------------+   height and text

Is there something like navbar-small in Bootstrap? Has someone any other hints how to do this with Bootstrap?
Here is my HTML markup:

press

login

...

            Brand

HOME(current)

FOO

BAR

I want to have #second-nav smaller.

A: Here is what I have in one of my application to adjust both the size of the font and the height of the navbar
.navbar-nav {
font-size: 15px;
line-height: 1.428;
}

You can adjust depending on what you mean by "small" and "normal"
Depending on how you structured the nav bar in your template/views you just call the class in the appropriate tag. This is an example with a ul list tag

A: In your top navbar, the padding on the anchor elements is increasing the height. You can remove it using the following code. Output in Full screen.

@media (min-width: 768px) {
  #second-nav li a {
    padding: 0 15px;
  }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet" />

press

login

...

      Brand

Beratungsansatz(current)

HOME

FOO

BAR

A: This is what you need dude

#second-nav li a {
  padding: 0 15px;
}
#second-nav ul li {
    display: inline;
    list-style: none;
    float: left;
}
div#second-nav {
    float: right;
}

press

login

...

      Brand

Beratungsansatz(current)

HOME

FOO

BAR

DEMO

A: I know you have an answer but this might be helpful anyways and takes the mobile viewport into consideration.

.navbar-default.nav-top ul {
  display: inline-block;
  float: right;
}
.navbar-default ul.navbar-top li {
  float: left;
  font-size: 11px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

press

login

.....

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> Toggle navigation

      </button>

Home (current)

Foo

Bar