text:
Q: Excel INDEX/MATCH not matching 3rd criteria I have 5 columns of data and I'm using an INDEX/MATCH function to pull data from column 5 based on exact criteria matches from columns 1, 3 & 4. So basically the user chooses 3 different criteria (from dropdowns) and if all three match columns 1, 3 & 4 exactly then the result(s) comes from column 5.
Here's the function I'm using...
{=IFERROR(INDEX(F5:F500,MATCH(1,(E5:E500=Production!B4)*(G5:G500=Production!B8)*(H5:H500=Production!B6),0)),"")}

Issue I had was depending on the criteria chosen there could be anywhere from 4 to 10 results so I used the following to pull the next results...
{=IFERROR(INDEX(F5:F500,MATCH(1,(E5:E500=Production!B4)*(G5:G500=Production!B8)*(H5:H500=Production!B6),0)+1),"")}

For each line I just added another number on the end of the function (ie. "+2" "+3", and so on) to get the desired results. As I mentioned above some criteria will have less results and this is where my problem is... once I have all available results (for example 3 results) the next line ("+3") should spit out an error because there are no more results that match the criteria exactly but instead the function just gives me the next result that matches the first two criteria but not the third. I apologize if this seems confusing, a little hard to explain which is probably why I couldn't anything in the forums that helped.
Any advice would be very much appreciated. (Note: I removed the "$" from the above functions so they are easier to read)
Thanks!

A: So in your example formula you would put this in M2:
=IFERROR(INDEX($F$5:$F$500,MATCH(1,($E$5:$E$500=Production!B4)*($G$5:$G$500=Production!B8)*($H$5:$H$500=Production!B6)*(COUNTIF($M$1:$M1,$F$5:$F$500)=0),0)),"")

Hit Ctrl-Shift-Enter as it is an array formula.  Then copy down.
Note as I did not have test data this is untested.
I put the $ back in as the relative/absolute of my addition is very important.


text:
Q: Monty Hall Problem. If contestant choose door with goat and host reveal it.... I need to confirm this scenario.
1 - The contestant picks a door with a goat behind it.
2 - The host opens this door and reveals the goat.
3 - The host gives the contestant the chance to pick a new door from the two remaining ones.
4 - contestant picks a new door.
5 - The classic scenario. Do you change the door or stay in the same door?
The probability is the same as the original problem (2/3)?
Cheers.

A: If I understand this correctly, the host opens the door that the contestant had chosen initially and reveals it to contain a goat ... after which the contestant picks one of the other two doors ... after which the contestant is given a chance to switch?
If so, it's just 50-50: what we know about the two remaining doors is completely symmetrical, and the prize has to be behind one of them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why are people using magic values instead of null in their code? I have seen this in legacy code and in some .NET open source projects.
I can't imagine a reason to do this. Just using "null" seems so much easier to me.
Example:
public class Category
{
   int parentID;

   bool HasParent
   {
      get
      {
          return parentID != -1;
      }
   }
}

versus
public class Category
{
   int parentID;

   bool HasParent
   {
      get
      {
          return parentID != null;
      }
   }
}

A: These are often habits developed when programming in C.  Many a C programmer would be horified at the waste of nullable ints, which at the very least require an entire extra bit, and possibly even a pointer.  This is especially bad when you know the value is going to be positive and you have the entire space of negative values to use for flags.  -1 can mean not set, -2 can mean that parentId doesn't even make sense in the context of this node, -3 can mean that the node had a parent that couldn't handle the work and left on a drinking binge and was never seen again, etc...
In the C# world the cleaness of nullable ints (and their easy integration with RDMS's) along with computers with 2GB+ of RAM means that the old C habits are slowly dying, but old habits die hard.

A: Having a null object can cause exceptions to be thrown, whereas error codes (like a "-1" failure case) would not throw an exception.
This can be critical in languages or applications which do not handle exceptions well.

A: Working on big datawarehouses, i sometimes uses the 0 value instead if null, to insert a non null value in my cube.
i always have a  0 id corresponding to 'Unknown' value in all dimensions, so i have a cube with no null values.
the main interest in it is to have simplier and more efficient queries

A: Because to have a "null" value, the type must be nullable. This works fine for reference types (any class you define and the standard library), and if you look you'll see that people do use null whenever they have a reference object with no value
Employee employee = Employees.Find("John Smith");
if(employee == null) throw new Exception("Employee not found");

The issue comes when you use the value types like int, char or float. Unlike reference types, which point to a block of data somewhere else in memory, these values are stored and manipulated inline (there is no pointer/reference).
Because of this, by default, the value types do not have a null value. In the code you provided, it is impossible for parentID to be null (I'm actually surprised this even got by your compiler - Visual Studio 2008 and probably 2005 will draw a green underline and tell you that the statement is always false).
In order for an int to have a null value, you need to declare it as nullable
int? parentID;

Now parentID can contain a null value, because it is now a pointer (well "reference") to a 32 bit integer, instead of just a 32bit integer.
So hopefully you understand why "magic values" are often used to represent null with the basic types (value types). It is simply a lot of trouble, and often a large performance hit (lookup what boxing/unboxing is), to store these value types as a reference to the value in order to allow them to be null.
Edit: For further reference about boxing/unboxing (what you need to have an int==null), see the article at MSDN:

Boxing and Unboxing (C# Programming Guide)
Performance
In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally. For more information, see Performance.

A: Nullable value types are not available in every language/environment; They were added to .Net 2.0.  If your legacy code is .Net based and was started using the 1.1 framework, then your answer is that null wasn't an option at the time.

A: Have you really looked into the application to see?  As long as the magic number is held in a single place with a descriptive name it can be quite useful.


text:
Q: Removing my Lenovo computer from the dock re-sizes my windows I am experiencing a strange problem that seems to be specific to the Lenovo that I and my work colleagues have. It is a W540 Thinkpad, and the issue is that when you undock the computer from a Lenovo dock, the windows all re-size to slightly smaller than the desktop. The windows all think they are maximized but you can click above the top which is super annoying.
I had a quick look for a solution but I cant seem to find any. Has anyone encountered this before or know of a solution?


text:
Q: access custom group I have my Access 2007 database configured to use "Custom" groups in the navigation pane.  I've grouped all my tables in a way that makes sense.  However, whenever I update a link table, it loses its grouping.
I have not been able to find a way to avoid this.  Since it seems to be unavoidable, I'd like to simply have a macro that adds the table back to the right group programatically.  I have not found any examples on how to do this. Any suggestions?

A: Old thread, I know, but I just had to deal with this problem, and thought I'd share my solution: a function that will move an object to a group.
Public Function SetNavPaneGroup(strObjName, strGroupName)
    Dim strSql, idObj, idGrp, db
    Set db = CurrentDb
    idObj = DLookup("Id", "MSysNavPaneObjectIDs", "Name='" & strObjName & "'")
    idGrp = DLookup("Id", "MSysNavPaneGroups", "Name='" & strGroupName & "'")

    If DCount("*", "MSysNavPaneGroupToObjects", "GroupID = " & idGrp & " AND ObjectID = " & idObj) > 0 Then
        strSql = "UPDATE MSysNavPaneGroupToObjects SET GroupID = " & idGrp & ", Name='" & strObjName & "' WHERE ObjectID = " & idObj
        db.Execute strSql, dbFailOnError
    Else
        strSql = "INSERT INTO MSysNavPaneGroupToObjects ( GroupID, ObjectID, Name ) " & vbCrLf & _
        "VALUES (" & idGrp & "," & idObj & ",'" & strObjName & "');"
        db.Execute strSql, dbFailOnError
    End If
    RefreshDatabaseWindow
    Set db = Nothing
End Function

Enjoy.

A: You should be able to do this by editing the system table MSysNavPaneGroupToObjects.  You'll need your table's ID from MSysNavPaneObjectIDs and the group ID from MSysNavPaneGroups (right click the navigation pane to access "Navigation Options" and check "Show System Objects).  Then you can use a query like the following to change the table's group.
UPDATE MSysNavPaneGroupToObjects SET GroupID = 9 WHERE ObjectID = 268

Because your working with system files, backup your .accdb file before starting.

A: Similar problem and although mjoshawa's suggestion didn't quite work for me, I got it working by inserting a new row into the MsSystemNavPaneGroupToObjects table.
INSERT INTO MSysNavPaneGroupToObjects ( GroupID, ObjectID, Name )
VALUES ( 55, 418, 'TableName' )

This worked as part of a UI macro right after the tables were created.

A: put_into_group(obj_name, group_name) moves an object to a specified group by appending/updating record in MSysNavPaneGroupToObjects.
Function DLookupArr(Expr, Domain, Criteria)
' https://stackoverflow.com/questions/5864160
    Dim arr
    Set rs = CurrentDb.OpenRecordset("SELECT " & Expr & " FROM " & Domain & " WHERE " & Criteria)
    If rs.EOF Then
        DLookupArr = Array()
        Exit Function
    End If
    rs.MoveFirst
    Do While Not rs.EOF
        If IsEmpty(arr) Then ReDim arr(0) Else ReDim Preserve arr(UBound(arr) + 1)
        arr(UBound(arr)) = rs(Expr)
        rs.MoveNext
    Loop
    DLookupArr = arr
End Function

Function in_arr(v, arr) As Boolean
    For Each i In arr
        If i = v Then
            in_arr = True
            Exit Function
        End If
    Next i
End Function

Function get_object_group_id(obj_id) As Long
    obj_group_ids = DLookupArr("GroupID", "MSysNavPaneGroupToObjects", "ObjectID=" & obj_id) ' All object's groups
    groups_ids = DLookupArr("Id", "MSysNavPaneGroups", "GroupCategoryID=3") ' All groups IDs
    For Each i In obj_group_ids
        If in_arr(i, groups_ids) Then 'if it's a user-defined group then move from it to `group_name`
            get_object_group_id = i
            Exit For
        End If
    Next i
End Function

Function put_into_group(obj_name, group_name) As Boolean
    obj_id = DLookup("Id", "MSysObjects", "Name='" & obj_name & "'") ' Object-to-move ID
    If IsNull(obj_id) Then Exit Function
    obj_group_id = get_object_group_id(obj_id)
    group_id = DLookup("Id", "MSysNavPaneGroups", "Name='" & group_name & "' And GroupCategoryID=3") ' Target group ID
    If IsNull(group_id) Then Exit Function
    If obj_group_id = group_id Then ' already in group `group_name`
        put_into_group = True
        Exit Function
    End If
    If obj_group_id <> 0 Then ' if it's a user-defined group then move from it to `group_name`
        sql_s = "UPDATE MSysNavPaneGroupToObjects SET GroupID = " & group_id & _
                " WHERE ObjectID=" & obj_id & " And GroupID=" & obj_group_id
    Else ' if object was not in any user-defined groups then add new entry
        sql_s = "INSERT INTO MSysNavPaneGroupToObjects (GroupID, ObjectID, Name) " & _
                "VALUES (" & group_id & "," & obj_id & ",'" & obj_name & "')"
    End If
    CurrentDb.Execute sql_s, dbFailOnError
    RefreshDatabaseWindow
    put_into_group = True
End Function


text:
Q: Users required to reset their password even after System admin has set the password I have set passwords (from Dev Console) for around 50 users in my org, however when they login they are being redirected to reset password page. I want them to be able to directly login into SFDC with the new password i set, how can i make them bypass the reset password page?

A: This is by design in Salesforce - the System Administrator is not meant to know user passwords so even if you set the password for the user using the Developer Console it will still prompt them to change that password that has been entered.
So you will not be able to avoid the users being sent to the change password page.

This is Working as Designed (WAD) in salesforce. If you hit enter you are actually hitting the 'cancel' button. The "Save" button doesn't get enabled until the requirements for the page are met (value entered for current password, matching & valid new & confirm passwords and/or a value for the security answer). The password of the user has not been changed.

Salesforce Help


text:
Q: Get Resource Id For Google Drive API Android I am using the drive api to create a file in the hidden app folder on google drive. I want to get the resource id of that file but it keeps on returning null. Here is the code. Once it creates the file it is supposed to get the file resource id in the call back but it returns null. It gets the normal drive it ok but that does not help at all since the fetch drive id need the resource id. any idea on how to get the resource id. I have checked multiple different links about this and all of them are no help.
//<editor-fold desc="Variables">

// Define Variable Int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE//
public static int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 0;

// Define Variable int RESOLVE_CONNECTION_REQUEST_CODE//
public static final int RESOLVE_CONNECTION_REQUEST_CODE = 3;

// Define Variable GoogleApiClient googleApiClient//
public GoogleApiClient googleApiClient;

// Define Variable String title//
String title = "Notes.db";

// Define Variable String mime//
String mime = "application/x-sqlite3";

// Define Variable String currentDBPath//
String dBPath = "/School Binder/Note Backups/Notes.db";

// Define Variable File data//
File data = Environment.getExternalStorageDirectory();

// Define Variable File dbFile//
File dbFile = new File(data, dBPath);

// Create Metadata For Database Files//
MetadataChangeSet meta = new MetadataChangeSet.Builder().setTitle(title).setMimeType(mime).build();

String EXISTING_FILE_ID = "CAESABjaBSCMicnCsFQoAA";

//</editor-fold>

// Method That Runs When Activity Starts//
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initiate allowWriteExternalStorage Method//
    allowWriteExternalStorage();

    // Initiate connectToGoogleDrive Method//
    connectToGoogleDrive();
}

// Method That Runs When App Is Resumed//
protected void onResume() {
    super.onResume();

    // Checks If Api Client Is Null//
    if (googleApiClient == null) {

        // Create Api Client//
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    // Attempt To Connect To Google drive//
    googleApiClient.connect();
}

// Method That Runs When App is paused//
@Override
protected void onPause() {

    // Checks If Api Was Used//
    if (googleApiClient != null) {

        // Disconnect From Google Drive//
        googleApiClient.disconnect();
    }
    super.onPause();
}

// Method That Runs When App Is Successfully Connected To Users Google Drive//
@Override
public void onConnected(@Nullable Bundle bundle) {

    // Add New File To Drive//
    Drive.DriveApi.newDriveContents(googleApiClient).setResultCallback(contentsCallback);

}

// Method That Runs When Connection Is Suspended//
@Override
public void onConnectionSuspended(int i) {

}

// Method That Runs When App Failed To Connect To Google Drive//
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    // Checks If Connection Failure Can Be Resolved//
    if (connectionResult.hasResolution()) {

        // If Above Statement Is True, Try To Fix Connection//
        try {

            // Resolve The Connection//
            connectionResult.startResolutionForResult(this, RESOLVE_CONNECTION_REQUEST_CODE);

        } catch (IntentSender.SendIntentException ignored) {
        }

    } else {

        // Show Connection Error//
        GoogleApiAvailability.getInstance().getErrorDialog(this, connectionResult.getErrorCode(), 0).show();
    }
}

// Method That Gives App Permission To Access System Storage//
public void allowWriteExternalStorage() {

    // Allow Or Un - Allow Write To Storage//
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Request To Write To External Storage//
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);

    }
}

// Method That Connects To Google Drive//
public void connectToGoogleDrive() {

    // Create Api Client//
    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Drive.API)
            .addScope(Drive.SCOPE_FILE)
            .addScope(Drive.SCOPE_APPFOLDER)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    // Attempt To Connect To Google drive//
    googleApiClient.connect();
}

//<editor-fold desc="Contents Callback">

// What Happens When App Is Trying To Make A New File Or Folder//
final private ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {

    @Override
    public void onResult(@NonNull DriveApi.DriveContentsResult result) {

        // Runs When File Failed To Create//
        if (!result.getStatus().isSuccess()) {

            // Log That File Failed To Create//
            Log.d("log", "Error while trying to create new file contents");

            return;
        }

        // Checks If Creating File Was Successful//
        DriveContents cont = result.getStatus().isSuccess() ? result.getDriveContents() : null;

        // Write File//
        if (cont != null) try {
            OutputStream oos = cont.getOutputStream();
            if (oos != null) try {
                InputStream is = new FileInputStream(dbFile);
                byte[] buf = new byte[5000];
                int c;
                while ((c = is.read(buf, 0, buf.length)) > 0) {
                    oos.write(buf, 0, c);
                    oos.flush();
                }
            } finally {

                oos.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        // Put File In User Hidden App Folder//
        Drive.DriveApi.getAppFolder(googleApiClient).createFile(googleApiClient, meta, cont).setResultCallback(fileCallback);
    }
};

//</editor-fold>

//<editor-fold desc="File Callback">

// What Happens If File IS mAde Correctly Or In-Correctly//
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new ResultCallback<DriveFolder.DriveFileResult>() {

    @Override
    public void onResult(@NonNull DriveFolder.DriveFileResult result) {

        // Checks If It Failed//
        if (!result.getStatus().isSuccess()) {

            Log.d("log", "Error while trying to create the file");
            return;
        }

        Drive.DriveApi.requestSync(googleApiClient);

        Log.d("log", "Created a file in App Folder: " + result.getDriveFile().getDriveId());

        String File_ID = String.valueOf(result.getDriveFile().getDriveId().getResourceId());

        Drive.DriveApi.fetchDriveId(googleApiClient, File_ID).setResultCallback(idCallback);
    }
};

//</editor-fold>

//<editor-fold desc="Id Callback">

final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
    @Override
    public void onResult(DriveApi.DriveIdResult result) {
        if (!result.getStatus().isSuccess()) {

            Log.d("Message", "Cannot find DriveId. Are you authorized to view this file?");

            return;
        }
        DriveId driveId = result.getDriveId();
        DriveFile file = driveId.asDriveFile();
        file.getMetadata(googleApiClient)
                .setResultCallback(metadataCallback);
    }
};

//</editor-fold>

//<editor-fold desc="metadata Callback">

final private ResultCallback<DriveResource.MetadataResult> metadataCallback = new
        ResultCallback<DriveResource.MetadataResult>() {
            @Override
            public void onResult(DriveResource.MetadataResult result) {
                if (!result.getStatus().isSuccess()) {

                    Log.d("Message", "Problem while trying to fetch metadata");
                    return;
                }
                Metadata metadata = result.getMetadata();

                Log.d("Message", "Metadata successfully fetched. Title: " + metadata.getTitle());
            }
        };

//</editor-fold>
}

A: Don't do like that, let extends DriveEventService to handle that task:
public class GoogleDriveEventService extends DriveEventService {
    private static final String TAG = "GoogleDriveEventService";

    @Override
    public void onCompletion(CompletionEvent event) {
        super.onCompletion(event);
        DriveId driveId = event.getDriveId();
        String resourceId = driveId.getResourceId();

    }
}

UPDATE AndroidManifest.xml
<service
    android:name="training.com.services.GoogleDriveEventService" android:exported="true">
    <intent-filter>
        <action android:name="com.google.android.gms.drive.events.HANDLE_EVENT"/>
    </intent-filter>
</service>


text:
Q: Add hyperlinks to data validation list (drop-down menu) Google Sheets:
I have data validation list in cell A1.The drop down menu has values a,b,c.
I want links to each of them to a specific cell, like user selects "a" from the drop-down and it goes to cell a5, b goes to cell c44 and so on...
What I need:
**Scripts that can very fast.
Please please help.

A: It could be something like this:
function onEdit(e) {
  var ss = e.source;
  var name = ss.getActiveSheet().getName();
  if (name != 'Sheet1') return;

  var col = e.range.columnStart;
  var row = e.range.rowStart;
  if (col != 1 && row != 1) return;

  var sheet = ss.getSheetByName('Sheet1');
  var value = e.value;

  switch (value) {
    case ('Place 1'): sheet.getRange('c1').activate(); break;
    case ('Place 2'): sheet.getRange('c2').activate(); break;
    case ('Place 3'): sheet.getRange('c3').activate(); break;
  }
}

Here is the sheet

A: Make a table with choices and cells
try with
=iferror(hyperlink("#gid=12345678range="&vlookup(A1,table,2,0), "link to "&vlookup(A1,table,2,0)))

where 12345678 is the gid of the sheet and table the list of choices/cells
You will have to click twice but it will go faster to the cell


text:
Q: If (X,T) is perfect and A is a dense subset of X, then A has no isolated points. If $(X,T)$ is perfect and $A \subseteq X$ is a dense subset of X, then A has no isolated points.
Since $A$ is dense $\Rightarrow (\forall U \in T)(A \cap U \neq \emptyset)$ and
since $(X,T)$ is perfect $\Rightarrow$ $(\forall x \in X)(\{x\} \notin T)$ but  I can't figure a way to show that $(\forall x \in A) (\forall V \in T)(A \cap V \neq \{x\}) $.  It seems from that that all I can do is show that $A \cap U$ is nonempty.  I can't see how I'd show that it's $\neq \{x\}$.

A: This is true if $X$ is $T_1$. Otherwise it need not be true: $X = \{0,1,2,3\}$, with topology $\left\{\emptyset, X, \{0,1\},\{2,3\}\right\}$ is perfect but $A = \{0,2\}$ is dense and consists of two isolated points. For a $T_0$ example, consider $X = [0,\infty)$ in the topology generated by all sets $[0,a) ,a > 0$. Here $X$ is perfect but $\{0\}$ is dense and trivially isolated. So I'll assume $X$ is $T_1$.
Suppose $x$ were an isolated point of $A$. So there is an open $U$ in $X$ such that $U \cap A = \{x\}$. But $\{x\}$ is not isolated in $X$, as $X$ is perfect. So pick $y \neq x$ with $y \in U$. As $X$ is $T_1$, we find an open set $V$ that contains $y$ but not $x$. But then $U \cap V$ is non-empty (it contains $y$), open, and it does not intersect $A$, as $(U \cap V) \cap A) = V \cap (U \cap A) = V \cap \{x\} = \emptyset$. This contradicts $A$ being dense. So $A$ has no isolated points.

A: $A$ is dense, suppose that $A$ has an isolated point $x$, this is equivalent to saying that $\{x\}$ is an open subset of $A$, $\{x\}=A\cap U$ where $U$ is an open subset of $X$. Remark that $U$ contains an element distinct of $x$ since $X$ is perfect.
You also have $\{x\}$ is closed since it is isolated, thus $\{x\}=F\cap A$ where $F$ is a closed subset of $X$, $U-F$ is a non empty closed subset, but $(U-F)\cap A$ is empty contradiction.


text:
Q: How do I have user input Python? I want to have a program that can take user input (such as the input(__prompt__) code) and execute it as if it were part of the actual code.
Example:
Python: What code would you like to run?
User: print('Hello world')
Python: Hello world
I don't even know if this is possible or not but it would really be nice.

A: Use exec(). However, if this project is using sensitive information, be warned that a user can access anything with this script.
exec(input(">>> "))


text:
Q: Does solid melt on the surface when the temperature is below its freezing point? I have learnt at school that evaporation and condensation are always taking place (on the suface of a liquid) and that the vapor and liquid are in equilibrium. Does something similar happen on the surface of a solid? If not, why?
I have googled this question but I havent faound any answers.


text:
Q: Append data to an existing JSON array with SwiftyJSON I have an array of SwiftyJSONthat I have declared and added data to it.
The JSON data gets filtered with a logic in cellForRowAt closure.
I would want to append data to another existing SwiftyJSON variable.
var jsonObj: JSON = JSON() // With JSON DATA
var filteredJSON: JSON = JSON() // Data to be added after filtration

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //..... Used jsonObj data and created a value for 'obj'

    if obj.altitude.wrappedValue > 0 {
        var filtr = JSON(jsonObj[indexPath.row].object)
        filteredJSON.arrayObject?.append(filtr)
    }
    print("filteredJSON:", filteredJSON) // null
}

In the end filteredJSON always return null


text:
Q: tf.compat.v1.train.exponential_decay: global step = 0 To find out how to implement both a ANN with exponential decay as well as a with a constant learning rate I looked it up here: https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/exponential_decay
I have some questions:
...
global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.1
learning_rate = tf.compat.v1.train.exponential_decay(starter_learning_rate,
global_step,
                                           100000, 0.96, staircase=True)
# Passing global_step to minimize() will increment it at each step.
learning_step = (
    tf.compat.v1.train.GradientDescentOptimizer(learning_rate)
    .minimize(...my loss..., global_step=global_step)
)

When the global_step is set equal to a variable with the value 0 doesn't that mean that we will have no decay, since
decayed_learning_rate = learning_rate *
                        decay_rate ^ (global_step / decay_steps)

Therefore if global_step= 0 follows decayed_learning_rate = learning_rate, is this right or am I making a mistake here?
Furthermore, I am a bit confused as to what exactly the 100,000 steps refer to. What exactly is one step? Is it every time an input has been fully fed through the network and backpropagated?

A: I hope this example clears your doubt.
epochs = 10
global_step = tf.Variable(0, trainable=False, dtype= tf.int32)
starter_learning_rate = 1.0

for epoch in range(epochs):
    print("Starting Epoch {}/{}".format(epoch+1,epochs))
    for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):

        with tf.GradientTape() as tape:
            logits = model(x_batch_train, training=True)
            loss_value = loss_fn(y_batch_train, logits)

        grads = tape.gradient(loss_value, model.trainable_weights)

        learning_rate = tf.compat.v1.train.exponential_decay(
                    starter_learning_rate,
                    global_step,
                    100000,
                    0.96
        )

        optimizer(learning_rate=learning_rate).apply_gradients(zip(grads, model.trainable_weights))
        print("Global Step: {}  Learning Rate: {}  Examples Processed: {}".format(global_step.numpy(), learning_rate(), (step + 1) * 100))
        global_step.assign_add(1)

Output:
Starting Epoch 1/10
Global Step: 0  Learning Rate: 1.0  Examples Processed: 100
Global Step: 1  Learning Rate: 0.9999996423721313  Examples Processed: 200
Global Step: 2  Learning Rate: 0.9999992251396179  Examples Processed: 300
Global Step: 3  Learning Rate: 0.9999988079071045  Examples Processed: 400
Global Step: 4  Learning Rate: 0.9999983906745911  Examples Processed: 500
Global Step: 5  Learning Rate: 0.9999979734420776  Examples Processed: 600
Global Step: 6  Learning Rate: 0.9999975562095642  Examples Processed: 700
Global Step: 7  Learning Rate: 0.9999971389770508  Examples Processed: 800
Global Step: 8  Learning Rate: 0.9999967217445374  Examples Processed: 900
Global Step: 9  Learning Rate: 0.9999963045120239  Examples Processed: 1000
Global Step: 10  Learning Rate: 0.9999958872795105  Examples Processed: 1100
Global Step: 11  Learning Rate: 0.9999954700469971  Examples Processed: 1200
Starting Epoch 2/10
Global Step: 12  Learning Rate: 0.9999950528144836  Examples Processed: 100
Global Step: 13  Learning Rate: 0.9999946355819702  Examples Processed: 200
Global Step: 14  Learning Rate: 0.9999942183494568  Examples Processed: 300
Global Step: 15  Learning Rate: 0.9999938607215881  Examples Processed: 400
Global Step: 16  Learning Rate: 0.9999934434890747  Examples Processed: 500
Global Step: 17  Learning Rate: 0.999993085861206  Examples Processed: 600
Global Step: 18  Learning Rate: 0.9999926686286926  Examples Processed: 700
Global Step: 19  Learning Rate: 0.9999922513961792  Examples Processed: 800
Global Step: 20  Learning Rate: 0.9999918341636658  Examples Processed: 900
Global Step: 21  Learning Rate: 0.9999914169311523  Examples Processed: 1000
Global Step: 22  Learning Rate: 0.9999909996986389  Examples Processed: 1100
Global Step: 23  Learning Rate: 0.9999905824661255  Examples Processed: 1200

Now if you keep your Global step as 0. ie Remove the increment operation from above code.
Output:
Starting Epoch 1/10
Global Step: 0  Learning Rate: 1.0  Examples Processed: 100
Global Step: 0  Learning Rate: 1.0  Examples Processed: 200
Global Step: 0  Learning Rate: 1.0  Examples Processed: 300
Global Step: 0  Learning Rate: 1.0  Examples Processed: 400
Global Step: 0  Learning Rate: 1.0  Examples Processed: 500
Global Step: 0  Learning Rate: 1.0  Examples Processed: 600
Global Step: 0  Learning Rate: 1.0  Examples Processed: 700
Global Step: 0  Learning Rate: 1.0  Examples Processed: 800
Global Step: 0  Learning Rate: 1.0  Examples Processed: 900
Global Step: 0  Learning Rate: 1.0  Examples Processed: 1000
Global Step: 0  Learning Rate: 1.0  Examples Processed: 1100
Global Step: 0  Learning Rate: 1.0  Examples Processed: 1200
Starting Epoch 2/10
Global Step: 0  Learning Rate: 1.0  Examples Processed: 100
Global Step: 0  Learning Rate: 1.0  Examples Processed: 200
Global Step: 0  Learning Rate: 1.0  Examples Processed: 300
Global Step: 0  Learning Rate: 1.0  Examples Processed: 400
Global Step: 0  Learning Rate: 1.0  Examples Processed: 500
Global Step: 0  Learning Rate: 1.0  Examples Processed: 600
Global Step: 0  Learning Rate: 1.0  Examples Processed: 700
Global Step: 0  Learning Rate: 1.0  Examples Processed: 800
Global Step: 0  Learning Rate: 1.0  Examples Processed: 900
Global Step: 0  Learning Rate: 1.0  Examples Processed: 1000
Global Step: 0  Learning Rate: 1.0  Examples Processed: 1100
Global Step: 0  Learning Rate: 1.0  Examples Processed: 1200

Suggestion - Instead of using tf.compat.v1.train.exponential_decay use tf.keras.optimizers.schedules.ExponentialDecay.
This is how the simplest example would look like.
def create_model1():
    initial_learning_rate = 0.01
    lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
        initial_learning_rate,
        decay_steps=100000,
        decay_rate=0.96,
        staircase=True)
    model = tf.keras.Sequential()
    model.add(tf.keras.Input(shape=(5,)))
    model.add(tf.keras.layers.Dense(units = 6,
                                    activation='relu',
                                    name = 'd1'))
    model.add(tf.keras.layers.Dense(units = 2, activation='softmax', name = 'O2'))

    model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=lr_schedule),
                loss='sparse_categorical_crossentropy',
                metrics=['accuracy'])

    return model

model = create_model1()
model.fit(x, y, batch_size = 100, epochs = 100)

You can also use Callback like tf.keras.callbacks.LearningRateScheduler to implement your decay.


text:
Q: PHP custom sort on an object array Laravel-5 I need to build a custom sort on an object array but i'm not sure where to start.  I've seen the functions usort() etc but I can't see how i'd implement these functions for what I require.
My application is returning the below object array.  I need to order it by the "slot" field in the following order: All Day, Morning, Afternoon.
Illuminate\Database\Eloquent\Collection Object
(
    [items:protected] => Array
        (
            [0] => App\BookingDates Object
                (
                    [connection:protected] =>
                    [table:protected] =>
                    [primaryKey:protected] => id
                    [perPage:protected] => 15
                    [incrementing] => 1
                    [timestamps] => 1
                    [attributes:protected] => Array
                        (
                            [id] => 265
                            [slot] => Morning
                        )

                    [original:protected] => Array
                        (
                            [id] => 265
                            [slot] => Morning
              )

                    [relations:protected] => Array
                        (
                        )

                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [appends:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [dates:protected] => Array
                        (
                        )

                    [casts:protected] => Array
                        (
                        )

                    [touches:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [with:protected] => Array
                        (
                        )

                    [morphClass:protected] =>
                    [exists] => 1
                )

            [1] => App\BookingDates Object
                (
                    [connection:protected] =>
                    [table:protected] =>
                    [primaryKey:protected] => id
                    [perPage:protected] => 15
                    [incrementing] => 1
                    [timestamps] => 1
                    [attributes:protected] => Array
                        (
                            [id] => 266
                            [slot] => Afternoon
                      )

                    [original:protected] => Array
                        (
                            [id] => 266
                            [slot] => Afternoon
                      )

                    [relations:protected] => Array
                        (
                        )

                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [appends:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [dates:protected] => Array
                        (
                        )

                    [casts:protected] => Array
                        (
                        )

                    [touches:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [with:protected] => Array
                        (
                        )

                    [morphClass:protected] =>
                    [exists] => 1
                )

            [2] => App\BookingDates Object
                (
                    [connection:protected] =>
                    [table:protected] =>
                    [primaryKey:protected] => id
                    [perPage:protected] => 15
                    [incrementing] => 1
                    [timestamps] => 1
                    [attributes:protected] => Array
                        (
                            [id] => 267
                            [slot] => All Day
                       )

                    [original:protected] => Array
                        (
                            [id] => 267
                            [slot] => All Day
                        )

                    [relations:protected] => Array
                        (
                        )

                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [appends:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [dates:protected] => Array
                        (
                        )

                    [casts:protected] => Array
                        (
                        )

                    [touches:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [with:protected] => Array
                        (
                        )

                    [morphClass:protected] =>
                    [exists] => 1
                )

        )

)

The result i'm looking for is this:
Illuminate\Database\Eloquent\Collection Object
(
    [items:protected] => Array
        (
            [0] => App\BookingDates Object
                (
                    [connection:protected] =>
                    [table:protected] =>
                    [primaryKey:protected] => id
                    [perPage:protected] => 15
                    [incrementing] => 1
                    [timestamps] => 1
                    [attributes:protected] => Array
                        (
                            [id] => 267
                            [slot] => All Day
                       )

                    [original:protected] => Array
                        (
                            [id] => 267
                            [slot] => All Day
                        )

                    [relations:protected] => Array
                        (
                        )

                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [appends:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [dates:protected] => Array
                        (
                        )

                    [casts:protected] => Array
                        (
                        )

                    [touches:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [with:protected] => Array
                        (
                        )

                    [morphClass:protected] =>
                    [exists] => 1
                )

            [1] => App\BookingDates Object
                (
                    [connection:protected] =>
                    [table:protected] =>
                    [primaryKey:protected] => id
                    [perPage:protected] => 15
                    [incrementing] => 1
                    [timestamps] => 1
                    [attributes:protected] => Array
                        (
                            [id] => 265
                            [slot] => Morning
                      )

                    [original:protected] => Array
                        (
                            [id] => 265
                            [slot] => Morning
                      )

                    [relations:protected] => Array
                        (
                        )

                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [appends:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [dates:protected] => Array
                        (
                        )

                    [casts:protected] => Array
                        (
                        )

                    [touches:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [with:protected] => Array
                        (
                        )

                    [morphClass:protected] =>
                    [exists] => 1
                )

            [2] => App\BookingDates Object
                (
                    [connection:protected] =>
                    [table:protected] =>
                    [primaryKey:protected] => id
                    [perPage:protected] => 15
                    [incrementing] => 1
                    [timestamps] => 1
                    [attributes:protected] => Array
                        (
                            [id] => 266
                            [slot] => Afternoon
                       )

                    [original:protected] => Array
                        (
                            [id] => 266
                            [slot] => Afternoon
                        )

                    [relations:protected] => Array
                        (
                        )

                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [appends:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [dates:protected] => Array
                        (
                        )

                    [casts:protected] => Array
                        (
                        )

                    [touches:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [with:protected] => Array
                        (
                        )

                    [morphClass:protected] =>
                    [exists] => 1
                )

        )

)

A: You can try something like this
public function index()
{
  $bookingsDate = BookingDate::all() // Your actual collection
  $this->sortCollection($bookingDate);
}
public function sortCollection(\Collection &$bookingDate)
{
   $bookingDate->sortBy(function($date)
   {
     $slots = [
        'Afternoon' => 1,
        'Morning'   => 2,
        'All day'   => 3,
     ];

     $slot = $slots[$date['slot']];

     return $slot;
   });
}

The sortBy method will do an ascending sort, for descending sort, try sortByDesc
See : http://laravel.com/docs/5.1/collections#method-sortby


text:
Q: How to build specific resource routes in routes.rb I have an app where I want to never be able to delete a Foo.  How can I configure resources :foos to not create the delete route?
Also, foos belong to bars and should only be shown on the bars show page.  I've tried the following get routes but I get the associated errors:
get "/foos/:id"

ArgumentError at /bars/1220
missing :controller

--
get "/foos"

ArgumentError at /bars/1220
missing :action

--
get "foos/show"

No route matches [GET] "/bars/1220"

(There is most definitely a route for this, and it works if I leave resources :foos in the routes.rb file.)
I've read routing from the outside in a couple times but I guess I'm not getting it.  Any help would be appreciated.

A: You can specify which of the standard routes to include when you use the resources command, with the except and only options:
resources :foo, :except => [:destroy] do
end

or
resources :foo, :only => [:index, :create, :show] do
end

A: To prevent a delete route from being created do this:
resources :foos, :except => :destroy

With respect to your second question (if I understand it correctly), you have to use nested resources:
resources :bars do
  resources :foos, :except => :destroy
end

This will create many routes including:
/bars/:bar_id/foos/:id


text:
Q: Is there any way to generate sequential Revision IDs in Alembic? I'm using Alembic as a database migration tool for a Python project. When I run a command like this:
alembic revision -m "adding a column"

...it will add a new file called alembic/versions/xxxxxxxxxxxx_adding_a_column.py where xxxxxxxxxxxx is a randomly generated, 12-digit hash.
From the perspective of making things human-readable, this is a little bit problematic, because it means that when looking at the alembic/versions directory, all the files will appear in random order, rather than in sequential / chronological order.
Are there any options in Alembic to ensure these prefix revision IDs are sequential? I suppose I could rename the files manually and then update the references, but I'm wondering if there's already a feature like that baked in.

A: I found how to do it in my case without additional bash scripts, just some mutation magic in env.py. Maybe it will help somebody.
Alembic has a powerful feature with customizing generated revisions so we can write override at this level:
# env.py
def process_revision_directives(context, revision, directives):
    # extract Migration
    migration_script = directives[0]
    # extract current head revision
    head_revision = ScriptDirectory.from_config(context.config).get_current_head()

    if head_revision is None:
        # edge case with first migration
        new_rev_id = 1
    else:
        # default branch with incrementation
        last_rev_id = int(head_revision.lstrip('0'))
        new_rev_id = last_rev_id + 1
    # fill zeros up to 4 digits: 1 -> 0001
    migration_script.rev_id = '{0:04}'.format(new_rev_id)

...
# then use it context.configure
context.configure(
  ...
  process_revision_directives=process_revision_directives,
)

If you also want to use it for revisions created without --autogenerate you should set revision_environment to true in alembic.ini

A: By the sounds of it, you are more interested in sequentially listed revision files rather than sequentially ordered revision ids. The former can be achieved without any change to how the revision ids are generated.
The alembic.ini file that is generated when you run alembic init alembic has a section that configures the naming of the revision files:
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

And here is the explanation from the docs:

file_template - this is the naming scheme used to generate new
  migration files. The value present is the default, so is commented
  out. Tokens available include:

*

*%%(rev)s - revision id

*%%(slug)s - a truncated string derived from the revision message

*%%(year)d, %%(month).2d, %%(day).2d, %%(hour).2d, %%(minute).2d, %%(second).2d - components of the create date, by default datetime.datetime.now() unless the timezone configuration option is also used.

So adding file_template = %%(year)d-%%(month).2d-%%(day).2d_%%(rev)s_%%(slug)s to alembic.ini would name your revision like 2018-11-15_xxxxxxxxxxxx_adding_a_column.py.
I found this issue: https://bitbucket.org/zzzeek/alembic/issues/371/add-unixtime-stamp-to-start-of-versions which pointed me in the right direction.
A comment from from that issue:

timestamps don't necessarily tell you which file is the most "recent",
  since branching is allowed. "alembic history" is meant to be the best
  source of truth on this.

So, the file naming solution will not guarantee that migrations are ordered logically in the directory (but will help IMO). The same argument could be made against having sequential ids.
If you do want to specify your own revision identifier, use the --rev-id flag on the command line.
E.g.:
alembic revision -m 'a message' --rev-id=1
Generated a file called 1_a_message.py:
"""a message

Revision ID: 1
Revises:
Create Date: 2018-11-15 13:40:31.228888

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '1'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    pass

def downgrade():
    pass

So you can definitely manage the revision identifiers yourself. It would be trivial to write a bash script to trigger your revision generation, automatically passing a datetime based rev_id, e.g. --rev-id=<current datetime> to govern order listed in the directory.
If the revision id isn't specified, the function rev_id() found at alembic.util.langhelpers is called:
def rev_id():
    return uuid.uuid4().hex[-12:]

Function calls to rev_id() are hard-coded in the alembic source, so short of monkey-patching the function, it will be difficult to override the behavior. You could create a fork of the library and redefine that function or make the function that it calls for id generation configurable.

A: I made a script to autoincrement the revision number based off of how many migrations already exist maching the ####_ pattern. Here's a TLDR version. I you save this as migrations.sh and change the path in line 2
#!/usr/bin/env bash
NEXT_ID=`ls kennel/db/versions/* | grep -P '/\d{4}_.*\.py$' | wc -l`
alembic revision -m $@ --rev-id=`printf "%04d" ${NEXT_ID}`

Then you can use it like:
./migrations.sh migration_name
# or
./migrations.sh migration_name --autogenerate

The full script has documentation and uses defaults to --autogenerate which can be disabled using an --empty flag.
https://gist.github.com/chriscauley/cf0b038d055076a2a30de43526d4150e

A: while i don't need migration branching i use this
@writer.rewrites(ops.MigrationScript)
def revid_increment(ctx: migration.MigrationContext, revisions: tuple, op: ops.MigrationScript):
    op.rev_id = '{0:04}'.format(len(tuple(ctx.script.walk_revisions())) + 1)
    return op

it makes it easy to replace the current rev_id naming scheme, add timestamp, date, whatever ...

A: Yeah but by using date and time
Below are the dynamic variables that are available in alembic
file_template - this is the naming scheme used to generate new migration files. The value present is the default, so is commented out.
Tokens available include:

%%(rev)s - revision id
%%(slug)s - a truncated string derived from the revision message
%%(year)d, %%(month).2d, %%(day).2d, %%(hour).2d, %%(minute).2d, %%(second).2d - components of the create date as returned by datetime.datetime.now()

So for example you can use the below configuration for sequential filenames
# template used to generate migration files
file_template = %%(year)d-%%(month).2d-%%(day).2d-%%(hour).2d-%%(minute).2d-%%(second).2d_%%(rev)s_%%(slug)s

This will generate the following output
YYYY-mm-dd-HH-MM-SS_<rev>_<message_slug>


text:
Q: Top bar/Panel customization orange line I've been trying to customize the panel to my liking but I can't figure out how to remove or at least shorten the orange line that you see in the screenshot.
enter image description here
This is the code that I've got so far:
#panel {
background-color: rgba(238, 238, 238, 0.25);
border-radius: 2em;
margin-top: 5px;
margin-right:5px;
margin-left: 5px;
margin-bottom: 5px;
}
#panel .panel-button {
color: rgba(50, 50, 50, 1);
}
#panel .panel-button:hover {
background-color: rgba(238, 238, 238, 0.25);
color: rgba(50, 50, 50, 1);
border-radius: 2em;
}
#panel .panel-button:active {
background-color: rgba(233, 84, 32, 1);
border-radius: 2em;
color: rgba(50, 50, 50, 1);
}
Thanks in advance!


text:
Q: Particular 6-regular graph on 42 vertices. Does anybody know of the existence of any known graphs that are 6-regular on 42 vertices?

A: Let us consider the $42$ vertices arranged in a circle.  Let each vertex be connected to the three consecutive vertices preceding it and to the three consecutive vertices following it.
Since there are enough vertices to prevent these edges from "wrapping around" the circle, the edges are well-defined.  The graph is $6$-regular.
Added: To make the problem more interesting, I'll describe two solutions that potentially are different from the one above.
First consider six disjoint copies of $K_7$, the complete graph on seven vertices.  Clearly this has $42$ nodes in all, and each node has degree six.
Second consider a periodic triangulation of the plane:

Make the graph finite by lattice periodicity, identifying every seventh node along the direction indicated by right pointing arrow and every sixth node along the direction of the arrow going up.  Again we have $42$ vertices in all, each with degree six.
The challenge for the interested Reader is to determine whether the three solutions are different (not graph isomorphic).
Hint:

 Consider the six neighbors of a fixed vertex, and count the edges between them.


text:
Q: Remove selected value from list in shiny SelectInput I have one input:
selectInput(
        "Linie_D",
        label = "Linie",
        choices = Liste_Linie_D,
        selected = "all" ,
        multiple = TRUE
      )

The default here is "all". If I now select another input, it will be appended to the list. My question: Is it possible to delete the default when entering a new value?
The deletion of "all" should be done when another value is entered.

A: Try adding this plugin to the selectInput:
selectInput(
        "Linie_D",
        label = "Linie",
        choices = Liste_Linie_D,
        selected = "all" ,
        multiple = TRUE,
        options = list('plugins' = list('remove_button'), 'create' = TRUE, 'persist'
        = FALSE)
      )

I try this code:
 selectInput(
      "Gebäude_ZDIM_A",
      label = "Gebäude SAP",
      choices = Liste_Gebaeude_ZDIM_A,
      selected = "all" ,
      multiple = TRUE,
      options = list('plugins' = list('remove_button'), 'create' = TRUE, 'persist'
                     = FALSE)
    )

and get the error:
Error in selectInput("Gebäude_ZDIM_A", label = "Gebäude SAP", choices = Liste_Gebaeude_ZDIM_A, : unused argument (options = list(plugins = list("remove_button"), create = TRUE, persist = FALSE))
What goes wrong?
Sorry, I think that you might need to load the shinyjs package for this to work correctly. I'm looking at code where I've used this before and I'm using selectizeInput instead of selectInput, so this option might not be available for selectInput. For more information, see here and here.
Also, since you're using selected = "all" and calling names from a data frame column, you might also have to modify your choices to be:
choices = c("all", unique(df$Liste_Gebaeude_ZDIM_A)
Where the unique function pulls all of the different names from the data frame column called Liste_Gebaeude_ZDIM_A. Hopefully this helps!


text:
Q: Is sending a signal over 433.92 MHz blocked by plastic? to be honoust: I never understood radiowaves; how I can receive radio in my house? Transferring a complete video through air from laptop to router? Never a clue.
So with that (lack of) knowledge my question: I am sending data with a little sending device which runs at 433,92 MHz (something like this http://nl.aliexpress.com/item/wholesale-Free-Shipping-1pcs-lot-315MHz-433-92MHz-Wireless-Remote-Control-Transmitter-Board-Module-TDL-9912/359001088.html).
(it's attached to my raspberry pi)
Now I want to finalize the project, so I thought to wrap it up in a nice plastic box (the led lights will be popping out of the plastic box, but as I don't think the sending device is pretty, it will be INside the box). And now the question: will the signal be influenced?
I guess it probably is in some way, but are we speaking in the terms of 1 or 2 percent, or does plastic (like a drink cup plastic) always take 50% of the signal or....

A: I read a great tip for this.  Put your case in the microwave.  If it gets hot, it is probably absorbing microwaves and will absorb various other similar radio waves.
Use this method at your own risk.

A: As long as the plastic is non-conductive — e.g., not filled or coated with anything containing carbon or metal — you should be fine.
The plastic functions as a dielectric, which passes electromagnetic fields with minimal loss, similar to how a piece of glass passes light.


text:
Q: Sendmail doesn't messages correctly or they never arrived to destiny. Why? I am trying to send a mail via sendmail command in ubuntu terminal like this:
sendmail EMAILADDRESS
FROM: FROMADDRESS
SUBJECT: hello world
this is a test email
.

I don't get any error in console, but in the logs I get the next line:
localhost [127.0.0.1] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA-v4

What could I do? I don't know how to do...
Thank for helping!


text:
Q: Call a method provided by future API I want to extend my previous question.
If in my code there is a method provided by future API, also if I check the version I have the following warning in LogCat
04-24 09:30:12.565: I/dalvikvm(471): Could not find method android.view.ViewTreeObserver.removeOnGlobalLayoutListener, referenced from method com.my.project.ActivityHome.removeLayoutListenerPost16
04-24 09:30:12.565: W/dalvikvm(471): VFY: unable to resolve virtual method 2950: Landroid/view/ViewTreeObserver;.removeOnGlobalLayoutListener (Landroid/view/ViewTreeObserver$OnGlobalLayoutListener;)V

In my case (see linked question) I can resolve using reflection
try {
    Method m = ViewTreeObserver.class.getMethod("removeOnGlobalLayoutListener", OnGlobalLayoutListener.class);
    m.invoke(observer, listener);
} catch (NoSuchMethodException e) {
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
}

My question is: it is better to use reflection and avoid warning or I it is better to ignore warning avoiding reflection?
My reflection code doesn't catch exceptions, but I am not sure it is correct, is it?

A: The warning is just a warning, it does not cause any problem during the execution.
Testing the presence of a method using reflection and exception handling is costly and should be avoided when possible.
You should the Build.VERSION.SDK_INT constant to check on which platform you are actually running
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
   // Do something using Gingerbread API
else {
   // Workaround for earlier version of android
}


text:
Q: Ubuntu 8.04LTS Folder name encoding issue I will explain my problem from the beginning, I have an Ubuntu server 8.04LTS and I use a Java application with Tomcat 6.0.18 and JRE 1.6.  The problem is that the display of characters such as (é è ç û) is replaced by other strange characters.  I know this is a problem of character encoding so I try to add the encoding fr_FR.ISO-8859-1 in the bashrc file and /etc/default/locale and I added LANG="fr_FR.ISO-8859-1".  I successfully display the good characters from a remote console (PuTTY) but the same problem still occurs when typing directly on the shell server.
For example, when I mkdir a folder called "Août" I receive "Ao♦t".
I think this may be due to the encoding used by the system partition, but I do not know how I can verify this.
Does anyone have an idea how I can fix this?

A: UPDATE: perhaps this is stating the obvious, but you must use either ISO-8859-1 or UTF-8 consistently everywhere, in both the system-wide settings (/etc/default/locale) and (if required) in the application's Java settings.
You need to change the system-wide locale to use ISO-8859-1 - however it would be much cleaner, if the application supports UTF-8, to simply have it use that (via -Dfile.encoding=utf8 on the JVM), as Ubuntu now works by default in UTF-8.
Check your application's documentation to see how to set the locale and encoding (e.g. ISO-8859-1) - if this isn't covered, setting the JAVA_TOOL_OPTIONS environment variable may be useful- this could be in the application's startup script.
To set Ubuntu to use ISO-8859-1:

*

*Generate the required Linux locale in case it doesn't exist already, and update /etc/default/locale via update-locale:

sudo locale-gen fr_FR
sudo update-locale LANG=fr_FR.ISO-8859-1

*

*UPDATE: Make similar edit to /etc/environment

*

*not sure why Ubuntu requires this but it's on my 8.04 system which was clean install not upgrade

*Close all applications and shell sessions, and restart them.

Unlike Windows and Mac, file systems on Linux have no concept of character encoding, so the application can generate files with ISO-8859-1 or UTF-8 pathnames at will, and even mix them in the same directory.  That's why you can create a directory as "Août" and have it display wrongly in another shell.
Using env | egrep "^(LC|LANG)" can be useful to check the locale variable settings - it sounds like those for your local shell (xterm, GNOME Terminal, etc) are wrong.  Once you have the right settings, put them into your ~/.bashrc file for the shell.
If you have folders created that have the wrong encodings in the pathnames, have a look at convmv - it's in the Ubuntu repositories.
Some general info on setting up locales and character encodings in this Gentoo UTF-8 HOWTO - although this is not for Ubuntu so some commands differ, the locale command is the same and the ideas are explained quite well.

A: Try defining LC_ALL the same way.
Also if you're using an xterm when seeing this locally try starting it with the -U parameter.
If you're having problems on Tomcat, though, you should probably be setting -Dfile.encoding=utf8 or -Dfile.encoding=iso8859-1 as JVM parameters instead. Perhaps you also need -Duser.region=fr?


text:
Q: Como usar uma váriavel de uma função async fora dela? Eu quero usar a variável data fora da função getData.
Mesmo definindo a data em escopo global quando eu dou o console.log retorna undefined
const apiURL = 'https://the-trivia-api.com/api/questions'; // Poderia ser qualquer uma
var data;

async function getData(url) {
    const response = await fetch(url);
    data = await response.json();
    console.log('Dentro da função:', data); // Retorna a resposta da API
}

getData(apiURL);
console.log('Fora da função:', data); // Retorna undefined

A: Voce tem que retornar um valor da função, e depois chamar a função externamente segue a correção.
const apiURL = 'https://the-trivia-api.com/api/questions'; // Poderia ser qualquer uma
var data;

async function getData(url) {
    const response = await fetch(url);
    data = await response.json();
    return data
}

const variavel = await getData(apiURL);
console.log('Fora da função:', variavel);

Resumindo a aplicação aguarda o termino da função getData, e encaminha para a variavel receber o valor do resultado.
assim podendo usar em qualquer instancia dora do função original.
nota que a função tem que retornar um valor, pode ser melhorada.


text:
Q: Not all views being displayed in my web part Issue: Not all views being displayed in my web part. When selecting a view in my web part it only shows 30 views. How do I get it to show all views created for a list if there is more then 30?

A: There was a not so documented limit of 50 views in WSS3/2007 that would be displayed in the list drop down on the list view web parts. This might still be the case (and still not entirely documented). I've never run into circumstances that needed that many views on a list. I believe you can rename the views to start with 1 or A so that these bubble to the top in the web part drop down.

A: Renaming the views will not help move them to the top.  The problem appears to be a unique ID number assigned to each view as it is created.  Once you hit the max, no new views appear in the dropdown view selector.  I have tried to use designer to modify the view ID number, but that did not work or I did not find it in all places.  My work around for this bug is to re-use one of the first views created.  You can modify the parameters, rename it, add it to the webpart using the selector.  Once it is saved in your webpart, reuse it again and again to update all webparts/pages where you display those views.  In the end, I always put the view back to its original state.  Hope this helps!


text:
Q: How to excute a looping hi i'm currently working a project i want to display image on a table instead of declaring one-by-one how can i excute a while loop method in  CSS thanks :)
or how i excute a loop by accessing my database.
my codes:
</style>
<form>

          <input type="text" placeholder="Search Equipment.." required/>
          <input type="button" value="Reserve" />
          <input type="button" value="Cancel" />

A: use css property
 background-repeat: repeat;

to repeat only horizontally , use background-repeat: repeat-x
to repeat only vertically, use background-repeat: repeat-y
source : here


text:
Q: Image with multiple axes of symmetry What is it called to mirror a 2D object / image both vertically and horizontally? Or is this still just referred to as being symmetric?
See the following game map; the engine only needs to generate 1/4 of the map and will then mirror it to make the game fair for all 4 players.

Is there a specific name for this kind of symmetry which is along more then a single axis?
The map is [symmetric] meaning that it is equal for all 4 players.

A: In two dimentions there are, effectively, two types of symmetry, reflectional and rotational.
In reflectional symmetry you imagine a flat mirror being placed on a line through the middle of the graphic and the half of the original combined with the reflection being indistinguisable from the entire original. If you could place the mirror on more than one line the image has multiple axes of reflextional symmetry.
Some graphics do not have reflectional symmetry but do have rotational symmetry. In this case if the image is rotated around its centre and there is at least one partial rotation following which the graphic is indistinguishable from its original position the graphic has rotational symmetry. The size of the angle through which the graphic needs to be turned, and therefore the more times in one rotation it displays rotational symmetry, determines the order of its rotational symmetry. If you can only turn it through 180° then it has rotational symmetry of order 2, through 90° has order 4 and so on.
Your graphic has 2 axes of reflectional symmetry (vertical and horizontal) but has only rotational symmetry of order 2 because of the long feature in the centre, the spaces at top and bottom and other features. Some graphics have reflectional symmetry but not rotational symmetry (the upper case letter T for example) while others have rotational symmetry but not reflectional symmetry (the letters S and Z for example).
The reason you only have to create a quarter of the graphic is that a vertical or horizontal reflection creates half of the full graphic and the other relection creates the othrr half.

A: It is of course, still symmetric. Only that it's symmetrical about more than one plane.
Technically, it may be said to be polysymmetrical, or symmetrical about n planes/axes.
Flowers often have a polysymmetrical arrangement.
Crystals too exhibit polysymmetry.
Polysymmetry is an important aspect in mathematics.


text:
Q: The Lie derivative of the metric $g_{ab}$ and index notation I don't quite know where to start this question. I'm essentially not understanding how to compute the Lie derivative of a given metric and vector.
So I have the following definition:
$$
\left(\mathcal{L}_{\xi}g\right)_{ab}=\xi^{c}\partial_{c}g_{ab}+g_{cb}\partial_{a}\xi^{c}+g_{ac}\partial_{b}\xi^{c}
$$
And say, as an example, I have the following vector (as an example):
$$
\xi^{a}=(\alpha(t,r),\beta(t,r),0,0)
$$
So the vector is superscript $a$? This has instantly confused me! My metric is of the form $g_{ab}$, which is consistent with the expression given.
So assuming that I can re-write the above expression as $\xi^{c}$, I'm still lost as to how I proceed with this calculation. What does $\xi^{c}$ correspond to when we have multiple components?
Could anyone give a generalised introduction to how this is computed, where to go with it, and perhaps an example to get me going. (I understand much better with a few examples under my belt).
Maybe if someone could give me the example using the basic FRLW metric $$g_{ab}=diag(1,-a^{2},-a^{2},-a^{2})$$ with the same vector? My actual metric is the following:
$$
g_{ab}=diag(-e^{\Phi(r)},(1-b(r)/r)^{-1},r^{2},r^{2}\sin^{2}\theta)
$$
But hopefully with the example given I should be able to make a start on this metric.
I am currently at this stage:
$$\left(\mathcal{L}_{\xi}g\right)_{ab}=\xi^{1}(\partial_{1}g_{00}+\partial_{1}g_{11})+2(g_{00}\partial_{0}\xi^{0}+g_{11}\partial_{1}\xi^{1})$$

A: Writing out all the contracted indices often helps and is a good starting point... The only non-zero components of $\xi^c$ is $0$ and $1$, so
$
\xi^c\partial_c g_{ab}+g_{cb}\partial_a\xi^c+g_{ac}\partial_b\xi^c
=\xi^0\partial_0 g_{ab}+\xi^1\partial_1 g_{ab}+g_{0b}\partial_a\xi^0+g_{1b}\partial_a\xi^1++g_{a0}\partial_b\xi^0++g_{a1}\partial_b\xi^1
$
Then use that the first two components of $\xi$ are functions of $t$ and $r$, and that your metric is diagonal (only $g_{00}=-e^{\Phi(r)}$, $g_{11}=(1-b(r)/r)^{-1}$ etc. contributes) and its components are functions of $r$. By computing the different derivatives properly and plugging them back into the equation above you should obtain the correct result.


text:
Q: LibGDX scaling fonts when not using pixels as device units So, LibGDX rants in a bunch of tutorials about how it is not recommended to use device pixels as coordinates in your world. I can understand the logic and it seems reasonable, so I am updating my camera code to do this:
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    aspect = h / w;

    camera = new OrthographicCamera(1.0f, aspect);
    camera.setToOrtho(true, 1.0f, aspect);

However a large part of what I do is working with fonts. Currently my font loader looks like this:
    glyphLayout = new GlyphLayout();

    FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("myfont.ttf"));
    FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();

    parameter.size = 100;
    parameter.characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.!'()>?:";
    parameter.flip = true;
    font = generator.generateFont(parameter);

This results in huge sized fonts. I am confused by the apparently conflicting coordinates systems in LibGDX - why do they not recommend using pixels, and yet all font functions deal with pixels?
How can I update this font loading code, so I get fonts which are approximately 20% of the screen size?

A: You can develop for one resolution (using viewports) and set your preferred font size.
At runtime, you can scale your font size based on the new screen width.
1920x1080, parameter.size = 16 => 1280x720, parameter.size = 16 / 1920 * 1280

Also, with distance field fonts, you can render smooth fonts without using the font ganerator at runtime.


text:
Q: Perfect Width To Fit Div Exactly I have boxes floated inside a div sort of like the SO Chat except i am making a box for my own website where users can make their own chat room, these boxes on the page represent chatrooms and i want to make a perfect width for them so they will fit exactly on the page without any excess space in the margins. the main div they are positioned in is 965px with a padding of 15px on the left and right side of it making a 935px width i reduced the width from 965px to 935px to keep a total width of 965px.
To get an idea of my scenario check out A Fiddle
As you can see there is some space left at the end right side of the div and i dont want that, i want the chat boxes to fit pixel perfectly the full width and remember to take into account that borders count as widths too. If someone could help me that would be great!
CSS Styles
body {
    width:1000px;
}

#Body {
    width:935px;
    padding:15px;
    height:500px;
    background-color:#F1F1F1;
    margin:0 auto;
}
.ChatRoom {
    float:left;
    width:223px;
    height:200px;
    border:1px solid #666;
    cursor:pointer;
    margin-right:8.75px;
    background-color:#FFF;
}
.ChatTitle {
    width:100%;
    height:30px;
    line-height:30px;
    font-size:13px;
    font-weight:bold;
    text-align:center;
    background-color:#C6D6D9;
    border-bottom:2px solid #9C0;
}

A: You can accomplish this using box-sizing:border-box. What it does is includes the padding and border sizes from the width, as opposed to its normal behaviour of adding to it (which makes the
 overflow to the next line). I've added a div.Inner here which will have the border and white background while the .ChatRoom is used to provide space using padding.
jsFiddle
HTML

My Chat Room

CSS
.ChatRoom {
    float:left;
    width:25%;
    height:200px;
    padding:8px;
    box-sizing:border-box;
}
.ChatRoom .Inner {
    border:1px solid #666;
    box-sizing:border-box;
    background-color:#FFF;
    cursor:pointer;
    height:100%;
}

Without border-box
Turns out it's pretty easy without border-box too, utilising margin on .Inner.
jsFiddle
.ChatRoom {
    float:left;
    width:25%;
    height:200px;
}
.ChatRoom .Inner {
    border:1px solid #666;
    margin:8px;
    background-color:#FFF;
    cursor:pointer;
    height:100%;
}

A: http://jsfiddle.net/DyTT8/1/
The last div needs to have the margin reset if not it will  add to the 15px of padding. I did this by giving it class="last and making the .ChatRoom div 225px; This will give you the proper spacing.
You could also put the divs in an unordered list and target the last div with li:last-child and remove the margin that way.


text:
Q: Tedious Differential geodesic equation Suppose that you are given an autonomous second order non linear homogenious ODE thats the  only remaining equation of a system of ODEs, and it takes the form $$\frac{-2rr''}{r-r_s}=\frac{r_sr'^2}{(r-r_s)^2}+\frac{r_s\alpha_0}{r^2}$$, where $x'^n=\frac{d^nx}{dt^n}$. What would be the best way to solve this equation? Would this be solved as a normal autonomous differential equation?

A: Letting $r(t)'=v(r)$, we see by the chain rule that
\begin{align}
r(t)''=\frac{\mathrm d^2r}{\mathrm dt^2}=\frac{\mathrm dr}{\mathrm dt}\frac{\mathrm dv}{\mathrm dr}=v\frac{\mathrm dv}{\mathrm dr}=v(r)v(r)'.
\end{align}
Notice that the independent variable has been changed to $r$ as apposed to $t$ now. Your ODE then becomes
\begin{align}
2vv'+\frac{r_s}{r(r-r_s)^2}v^2+r_s\alpha_0\frac{r-r_s}{r^3}=0.
\end{align}
Now note that the derivative of $v^2$ is $2vv'$, so we this equation is exact with the use of an integrating factor. We'll look for some factor $\mu(r)$ such that our equation can be written as
\begin{align}
(\mu(r) v^2)'+r_s\alpha_0\frac{r-r_s}{r^3}\mu(r)=0,
\end{align}
which can be integrated. To find $\mu(r)$ we'll expand the first part and equate like terms:
\begin{align}
2\mu(r)vv'+\mu(r)'v^2+...=2\mu(r)vv'+\frac{r_s}{r(r-r_s)^2}\mu(r)v^2+...
\end{align}
so then
\begin{align}
\mu(r)'=\frac{r_s}{r(r-r_s)^2}\mu(r).
\end{align}
I'll leave it to you to solve this ODE.
Now your equation can be written as
\begin{align}
\left(\mu(r)v^2\right)'+r_s\alpha_0\frac{r-r_s}{r^3}\mu(r)=0,
\end{align}
integrating and undoing the substitution for $r(t)'$ yields
\begin{align}
\mu(r)v^2+\alpha_0r_s\int\frac{r-r_s}{r^3}\mu(r)\mathrm dr=c_1,\\
(r(t)')^2=\frac{1}{\mu(r)}\left(c_1-\alpha_0r_s\int\frac{r-r_s}{r^3}\mu(r)\mathrm dr\right).
\end{align}
Then the solution to your equation is given by the integral
\begin{align}
\int\left[\frac{1}{\mu(r)}\left(c_1-\alpha_0r_s\int\frac{r-r_s}{r^3}\mu(r)\mathrm dr\right)\right]^{-1/2}\mathrm dr=t+c_2.
\end{align}
I'd be surprised if this has a known solution, let me know if you find it!


text:
Q: Android's AssetManager from the Target Context uses assets stored under androidTest directory I'm seeing behavior I am not expecting during development of android library (AAR), was wondering if someone can explain it.
my library structure is :
src/
    androidTest/
        assets/
            my_assets/
        java/
            com/
                ...
    main/
        java/
            com/
                ...

my test is doing the following:
    final String assetsSubfolder = "my_assets";
    Context targetContext = InstrumentationRegistry.getTargetContext();
    String[] targetAssets = targetContext.getResources().getAssets().list("");
    Context testContext = InstrumentationRegistry.getContext();
    String[] testAssets = testContext.getResources().getAssets().list("");
    Assert.assertTrue("target should not have assets now", !Arrays.asList(targetAssets).contains(assetsSubfolder));
    Assert.assertTrue("test should have assets now", Arrays.asList(testAssets).contains(assetsSubfolder));

The test fails due to the target, which is the library production code, containing my testing assets folder. I thought that using getTargetContext I will see no assets folder, as there is no assets folder in my production code. Can someone explain this?


text:
Q: Find and modify JSF component in backing bean I have a <h:outputText> in the view.
In the controller, I would like to use below code to manipulate the value and style attributes. Is it possible?
private void updateMsgCreateRegistrationKey(String objectName, String msg, String msgType){
    UIComponent UIOutputText = getUIComponentOfId(FacesContext.getCurrentInstance().getViewRoot(), objectName);
    if (UIOutputText != null){
        UIOutputText.setRendered(true);
        if(msgType.equalsIgnoreCase("Info")){

        }else if(msgType.equalsIgnoreCase("Error")){

        }
    }
    RequestContext.getCurrentInstance().update(objectName);
    FacesContext.getCurrentInstance().renderResponse();
}

A: This is not the normal approach. You normally don't manipulate the view from the controller on. Instead, in MVC, you let the controller (the backing bean) manipulate the model (the backing bean properties) and let the view (the XHTML file) check the model (the backing bean properties).
private String value;
private String styleClass;
private boolean rendered;

public void someMethod() {
    value = "some value";
    styleClass = "someClass";
    rendered = true;
}

// +getters (no setters necessary)

<h:outputText value="#{bean.value}"
              styleClass="#{bean.styleClass}"
              rendered="#{bean.rendered}" />

Or even without rendered property:
<h:outputText value="#{bean.value}"
              styleClass="#{bean.styleClass}"
              rendered="#{not empty bean.value}" />

Every time you thought you need to grab an UIComponent from the view in the controller, stop immediately and think twice if you're really doing things the right way.
See also:

*

*How does the 'binding' attribute work in JSF? When and how should it be used?


text:
Q: No access to partner - Information could not be retrieved Here is my full error:
Information could not be retrieved. Please contact iandevice to verify that your account has been properly set up. You may need to add the developer email address as a home member in the Google Home app settings.
I have seen several similar questions, but their solution did not help me. I've followed this link to setup: https://developers.google.com/nest/device-access/get-started but got the error when authorizing my account.
My email address is a personal gmail account. I have checked that my email address in the device access console (Top Right) is the same account that is linked to my nest. I have tried several solutions like re-creating the whole GCM project, credentials, etc, or trying with another gmail account.
I have also ensured that my account is added in my Google Home App, tried adding another account and trying but it's the same. Completely lost here after trying everything, does anyone have a solution to this? Thank you.
Just to add on, I have also checked in the OAuth consent screen that I have the same email address listed under email and developer's email. Also tried deleting the whole home and creating a new one, and link my nest to that h ome


text:
Q: Tkinter Entry validatecommand not working as expected I'm new to Python and Tkinter so it is possible (likely) that I'm doing something silly. The following program works (the validation function returns True for valid entries and False for invalid ones) except for one thing: oldvalue == newvalue always. If I type 'xxx' it prints 'wrong!' but the value stays 'xxx'. Validation is supposed to take place before the change takes place and a False return should prevent the change from happening, right?
import Tkinter as tk

root = tk.Tk()

def makeEntries():
    wnames = []
    def f(name, newvalue, oldvalue):
        name = name[name.rfind('.')+1:]
        print 'validating', name, newvalue, oldvalue
        for i, wn in enumerate(wnames):
            if wn == name:
                if newvalue.isdigit():
                    return True
                else:
                    print 'wrong!'
                    return False
        else:
            raise RuntimeError('Kaput!')
    vcmd = root.register(f)

    frame = tk.Frame(root)
    for i in range(10):
        w = tk.Entry(frame, width=4, justify=tk.RIGHT,
                     validate='focusout',
                     validatecommand=(vcmd, '%W', '%P', '%s'))
        w.pack()
        name = w.winfo_name()
        print i, name
        wnames.append(name)

    return frame

e = makeEntries()
e.pack()

root.mainloop()

A: Validating on "focusout" can't prevent bad values -- the validation mechanism won't delete characters in the widget. It can only prevent characters from being entered at the time the user is typing.