text:
Q: Using iface.showAttributeTable() on QgsVectorLayer retrieved by getObject() I'm unsure if i'm properly using the processing.getObject() function. I'm creating a python processing script for QGIS 2.0 and 2.2, but can't seem to get an attribute table to open programmatically. The code below works fine in the Python Console, but causes QGIS to crash when I tried as a Processing Script. The only difference was that the layer is called by QgsVectorLayer() in the Python Console and processing.getObject() in the Processing script, thus my reasoning behind my question.
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from processing.core.VectorWriter import VectorWriter
import numpy
import processing
import csv
import qgis.utils

#Here we define the input and outputs
#====================================
##[Example scripts]=group
##Couche_compteurs_individuels=vector
##Couche_compteurs_generaux=vector
##Couche_canalisations_sur_compteur=vector

#And here is the body of the algorithm
#=======================================

#input layers values are always a string with its location.
#That string can be converted into a QGIS object (a QgsVectorLayer in this case))
#using the processing.getobject() method
indivLayer = processing.getobject(Couche_compteurs_individuels)
grosLayer = processing.getobject(Couche_compteurs_generaux)
resLayer = processing.getobject(Couche_canalisations_sur_compteur)

CG_IDlist = []

def AEPstats():
    Gros_Feat = grosLayer.getFeatures()
    grosIDselection = []
    grosidNull = False
    for feat in Gros_Feat:
        ID_idx = grosLayer.fieldNameIndex('ID_CG')
        #selection list of null values
        if feat.attributes()[ID_idx] == NULL:
            grosIDselection.append(feat.id())
            grosLayer.setSelectedFeatures(grosIDselection)
            grosidNull = True
        #Putting existing attributes in list
        else:
            CG_IDlist.append(feat.attributes()[ID_idx])
    #Open msg box, attribute table with selected items, and end function
    if grosidNull == True:
        QMessageBox.warning(
            None,
            'Probleme de saisie',
            "Completez identifiant(s) de reference ('CG_ID') de Compteurs Individuel")
        qgis.utils.iface.showAttributeTable(grosLayer)
        return

Thanks in advance


text:
Q: Bulk Updates and Transactions using Entity Framework When attempting to perform updates on multiple records, calling DbContext.SaveChanges() wraps them in a transaction. However, this seems to not allow other users to save their data on the table being updated and they receive timeout errors.
Using EntityFramework v6.2.0 I tried to understand the behavior behind the scenes by creating an application where I retrieve multiple rows (typically around 800) from the database, update their properties (up to 6 properties per row), and then call DbContext.SaveChanges(). I log the generated SQL to an output window and see that my update operations are all being wrapped in a single transaction. On saves where there have been a large amount of records updated other users cannot perform operations such as updating on the same table.
The results from my code are as expected, the updates are performed. However the issue has come when other users have attempted to update a row in the same table through DbContext.SaveChanges() while my update operations are currently being run. In this case, a single row is retrieved using Entity Framework and updated, and then finally DbContext.SaveChanges() is called. However they receive a SQLException because their execution timeout expired. I suspect this to be something to do with my updates and the transaction that my updates are wrapped in locking the table while my update operations are performed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting the count of xml elements under an XML Node I am looking to get the count of elements under a particular node in an XML file.
The file will look something like the following
<Return>
  <ReturnHeader>
  </ReturnHeader>
  <ReturnData documentCnt="8">
    <file1></file1>
    <file2></file2>
    <file3></file3>
    <file4></file4>
    <file5></file5>
    <file6></file6>
    <file7></file7>
    <file8></file8>
  </ReturnData>
<ParentReturn>
  <ReturnHeader>
  </ReturnHeader>
  <ReturnData documentCnt="6">
    <file1></file1>
    <file2></file2>
    <file3></file3>
    <file4></file4>
    <file5></file5>
    <file6></file6>
  </ReturnData>
</ParentReturn>
<SubsidiaryReturn>
  <ReturnHeader>
  </ReturnHeader>
  <ReturnData documentCnt="3">
    <file1></file1>
    <file2></file2>
    <file3></file3>
  </ReturnData>
</SubsidiaryReturn>
</Return>

I need to parse this xml file for the ReturnData node (which is located in multiple locations in the file as you can see) and get the count of the elements underneath it.
For example
- Under Return\ReturnData the count has to be 8
- Under Return\ParentReturn\ReturnData  the count has to be 6
- Under Return\SubsidiaryReturn\ReturnData  the count has to be 3
The attribute documentCnt should actually give me the right count but the xml document that gets created will have discrepancies and hence I will need to parse this xml file and check if the value in the documentCnt attribute matches the number of elements under the ReturnData node.

A: Using the problem description you gave of:

The attribute documentCnt should actually give me the right count but
  the xml document that gets created will have discrepancies and hence I
  will need to parse this xml file and check if the value in the
  documentCnt attribute matches the number of elements under the
  ReturnData node.

This could be solved in a single step if you were to use a simple select statement on the "ReturnData" element, as in:
public static void Main(params string[] args)
{
    // test.xml contains OPs example xml.
    var xDoc = XDocument.Load(@"c:\temp\test.xml");

    // this will return an anonymous object for each "ReturnData" node.
    var counts = xDoc.Descendants("ReturnData").Select((e, ndx) => new
    {
        // although xml does not have specified order this will generally
        // work when tracing back to the source.
        Index = ndx,

        // the expected number of child nodes.
        ExpectedCount = e.Attribute("documentCnt") != null ? int.Parse(e.Attribute("documentCnt").Value) : 0,

        // the actual child nodes.
        ActualCount = e.DescendantNodes().Count()
    });

    // now we can select the mismatches
    var mismatches = counts.Where(c => c.ExpectedCount != c.ActualCount).ToList();

    // and the others must therefore be the matches.
    var matches = counts.Except(mismatches).ToList();

    // we expect 3 matches and 0 mismatches for the sample xml.
    Console.WriteLine("{0} matches, {1} mismatches", matches.Count, mismatches.Count);
    Console.ReadLine();
}


text:
Q: LocationMatch rules with Apache I need to fix (with or without regex) so you can access "/admin.php?+" but not "/SUBSITE/admin.php?+" on a site. Anyone has a good idea of how to fix that?

A: Here is a regex which might fit your need (your original question was a bit vague):
^(?!www\.mysite\.com\/.*\/admin\.php).*$

I have tested this regex and it blocks "www.mysite.com/*/admin.php", but it allows the following:
www.mysite.com/*/guestbook.php
www.mysite.com/*.php

If you want additional restrictions in the regex, then let me know and I can refine this answer.
Regex101


text:
Q: How to automatically extract content from an Excel cell and paste a specific part of it into new cell In EXCEL, I'm trying to extract from this cell:
'
 4 text r
 $7000 - 8000

To turn it automatically into this in a new cell:
$7000 to $8000

This is the latest formula I have tried:

=MID(BC395,SEARCH(">",BC395)+1,SEARCH("0",BC395)-SEARCH(">",BC395)-2)

BC395 is the cell where I'm extracting from.
Any ideas on how to avoid the other irrelevant text info and numbers in the first cell? I need it to move clean into the new cell with the "dollar" sign and the word "to" in between the range.

A: If the format of the string will always include
$n - n<

where n is any number, but the relevant string is preceded by a $ and followed by a <
Then you can try this formula:
=SUBSTITUTE(LEFT(REPLACE(A1,1,FIND("$",A1)-1,""),FIND("<",REPLACE(A1,1,FIND("$",A1)-1,""))-1),"- ","to $")

Change A1 to BC395 or wherever you have your string.
If there is variability in the string, I would suggest a VBA User Defined Function, looking for the 7000 - 8000 portion.


text:
Q: Pure Applesauce: What does it mean and when/how was it created? I could find out what jiggery–pokery means (dishonest or suspicious activity), but what does "pure applesauce" mean? And when, where, by whom, and how was this expression created?
Context:

Otherwise, the Court says, there would be no qualified individuals on
  federal Exchanges, contradicting (for example) the provision requiring
  every Exchange to take the "'interests of qualified individuals'" into
  account when selecting health plans. Ante, at 11 (quoting
  §18031(e)(1)(b)). Pure applesauce.

It does seem that Scalia didn't just make the phrase up, since it existed since at least the 60's *.
* I'm assuming those references aren't all about apple sauce that's pure.

A: From Eric Partridge, A Dictionary of Slang and Unconventional English, fifth edition (1961):

apple-sauce. Impudence: mostly lower middle class: late C.19–20. An elaboration of sauce, n., 1 ...

The relevant definition of sauce in Partridge is as follows:

sauce. Impudence, impertinence: coll[oquial] and dial[ectal]: 1835, Marryat (OED); perhaps much earlier (see [more] sauce than pig [defined in its own entry as "(To be) very impudent, impertinent: coll[oquial]: late C 17–18. B[ritish] E[nglish]"]. Ex saucy ...

J.E. Lighter, The Random House Historical Dictionary of American Slang (1994) offers this more elaborate, two-definition entry:

applesauce n, 1. Theat[rical] silly trite comedy [Citations, starting in 1918, omitted.] 2. nonsense, flattery, insincerity; lies—also used as interj[ection]. [First two citations:] 1919 T.A. Dorgan, in Zwilling TAD Lexicon 15: They spill a lot of applesauce about big money, 1920 in Collier's (Jan 1, 1921) 18: That's all apple sauce!

So applesauce, as used at the end of the OP's quotation simply means "baloney!"

A Google Books search doesn't find the Dorgan/Zwilling example mentioned in Lighter, but it does find two instances (both by the same author) from Collier's Magazine in 1921. From H.C. Witwer, "Auto Intoxication," in Collier's (January 1, 1921):

"Gimme my money back, you burglar!" shrieked the newcomer, ignoring me entirely. "I'm gonna have you pinched. This old tomato can is nothin' but a mess of junk! When I cranked it up last Friday mornin' the rear end fell out in the street, and the repair man tells me the only reason it ever run a foot is because you went to work and doped the motor with ether! The bearin's is all shot, it needs—!"
"Ssh!" interrupted the dealer wearily, as one who hears an old story. "That's all apple sauce! I told you the job needed the touch of a monkey wrench here and there. You can't expect to git no factory pet for what you paid for this car. They's no use gittin' hysterical, you bought the car as is, and they i absolutely no comeback. If you don't want it, leave it here and I'll sell it for you some time to-day and git you what I can for it!"

And from H.C. Witwer, "The Shooting Stars," in Collier's (June 11, 1921):

"A thousand pardons, old man!" says my vis-a-vis, climbin' out into the road. Dug, he didn't look so particularly hugely when he was scrunched up behind the steerin' wheel, but when he stood up and unfolded his full length, it was different. "You were hitting it up so fast, I had no idea you intended turning off the road here," he goes on. "However, I'll—"
""That's all apple sauce!" I bellers, steppin' over to him, "A guy drivin' a can like yours should be prepared for anything, and they ain't nobody in the world goin' to run me down and get away with it. Put up your hands, you big stiff!"

These are the earliest two matches in Google Books search results, although the expression is quite common by the mid-1920s, it's euphemistic qualities making it a favorite choice in periodicals such as Boys' Life.

A: P.G. Wodehouse uses it several times in his fiction, which puts it in general use in England before WW2 at the least.  Most of his idioms come from 1920s or earlier.  My google unfortutately only finds his use in 'The Catnappers.'


text:
Q: Child theme after CSS modification Hi I used the Edin theme to build a wordpress website. I modified a big part of the CSS at the CSS editor, without having a clue what a child theme is. What should I do now? Create a child theme and delete the additional CSS of the parent theme? Any ideas?
Thank you very much!!

A: As Jacob Peattie mentioned, you've made custom CSS changes in a way that does not impact your theme. To expand a bit more, this is the only place you can make changes that will persist through a theme update or change. All other customizations get wiped.
So if you find you want to make further changes, you can create a child theme. You'll need access to the server/file system for this.
First create a new folder/directory in wp-content/themes/
You need to add two files to this directory: style.css and functions.php
In the style.css file add the following information:
/*
 Theme Name:   Edin Child
 Template:     edin
*/

Those are the only two required things in this file. Note that I have assumed that the "Template" is "edin"; make sure this is actually the parent theme directory name. More info.
Next is the functions.php file, which is a little more involved. Here is where tell your child theme to import information from its parent as well as importing its own style info.
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {

    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); // get_template_directory_uri() returns the URI of the current parent theme, set in "Template" in your style.css
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array( $parent_style ),
        wp_get_theme()->get('Version')
    ); // get_stylesheet_directory_uri() returns the child theme URI
}
?>

Then you'll have to zip your child theme directory up and upload it via the WP admin (or upload via ftp to /wp-content/, no zipping required), and finally activate the child theme. More info.
You can find more about creating child themes directly from the WordPress theme development docs.

A: If you've changed the original theme files, create a child theme and move your changes to the new style.css of the child. If you don't remember what your changes were, just copy the modified style.css from parent to child and reinstall the parent theme.
If you just added the CSS in the customizer then you don't have to do anything since the changes will remain even if the theme is update.


text:
Q: Most Efficient way to Get common records from two Arraylist I have 2 list
ArrayList<String> l1 = new ArrayList<String>();
    l1.add("ABCD");

    l1.add("DEF");
    l1.add("GHI");
    l1.add("JKL");
    l1.add("MNO");
    l1.add("PQR");
    l1.add("MNO");

    ArrayList<String> l2 = new ArrayList<String>();
    l2.add("ABC");
    l2.add("DEF");
    l2.add("GHI");
    l2.add("PQR");
    l2.add("STU");
    l2.add("ABC");

Data can be in millions as well, i just want to know which will be most efficient way to do the same..
1.Solution-1
public ArrayList getCommonWords(ArrayList list1,
            ArrayList list2)
{

    ArrayList<String> commonlist = new ArrayList<String>();
    int i = 0;
    while (i < list1.size()) {
        for (int j = 0; j < list2.size(); j++) {
            if (list1.get(i) == list2.get(j)) {
                commonlist.add(list1.get(i));
                break;
            }

        }
        i++;
    }
    return commonlist;

}

Solution 2 - using retain function
Is there any other solution to the same ..like hash etc..if the can be more efficient?

A: There are several ways. You just need to decide which one is more important: speed or memory.
Optimising for speed ( O(N) runtime complexity, O(N) memory complexity):
You would use a hash set for one of your arrays. The expected complexity for find / contains in a HashSet is O(1) and the average depends on the number of buckets (b) which is O(b/N).
{
   List <String> common = new ArrayList<>();
   HashSet<String> hs = new HashSet<>();
   hs.addAll(l1); // add all the items from l1 to the hashset
   for (String s : l2) {
     if hs.contains(s) {
       common.add(s);
     }
   }
}

If you want to optimise the memory, so you wouldn't have to allocate additional memory you could do it in O(N*M) (assuming l1 and l2 don't have the same size) and O(1) in memory.
List <String> common = new ArrayList<>();
for (String s : l1) {
  if l2.contains(s) {
    common.add(s);
  }
}

This solution you proposed is the same as my second solution.
When comparing objects in java, you shouldn't use ==. That checks if the object have the same reference. Use instead equals which will check if they have the same content.


text:
Q: Strang, Ch. 4.3 - Least Squares Approximation, Problem 29: Test to have exactly one plane in $\mathbb{R}^n$? The following problem is in Chapter 4 Section 4.3 entitled "Least Squares Approximations" from Gilbert Strang's Introduction to Linear Algebra.

*Usually there will be exactly one hyperplane in $R^n$ that contains the $n$ given points $x=0, a_1, a_{n-1}$. (Example for $n=3$:
There will be one plane containing $0,a_1,a_2$ unless $a_1$ and $a_2$
are dependent). That is the test to have exactly one plane in $R^n$?

The solution manual says

Only one plane contains $0, a_1, a_2$ unless $a_1, a_2$ are dependent.
Same test for $a_1, ..., a_{n-1}$. If they are dependent, there is a
vector $v$ perpendicular to all $a$'s. Then they all lie on the plane
$v^Tx=0$ going through the origin.

I'd like to understand why it is that if these $n-1$ vectors are dependent then there is a vector perpendicular to all of them.
Intuitively, it seems that the dimension of the subspace spanned by the vectors is $<n-1$. Therefore, since the vectors are in $\mathbb{R}^n$ then there is another subspace that is orthogonal (and has dimension $>1$; this subspace is the left nullspace of the matrix $A$ that has the initial $n-1$ vectors as columns). Any vector in this subspace is perpendicular to every vector in the subspace spanned by the initial $n-1$ vectors.
Is this the reason?
Even if the $n-1$ vectors were independent, however, the dimension of the orthogonal subspace would still be one. Ie, we could still affirm that there is a vector $v$ that is perpendicular to all the initial vectors.
My original answer was a bit wordy, but here it is
Consider $\mathbb{R}^3$ and three points $0,a_1,a_2$.
If these points are on a line, then there are infinite planes passing through all three points.
One way to see this is that to span a plane two independent vectors are required, and to span a line one independent vector (ie, not the zero vector) is required. In constructing a plane, we can choose as one basis vector a vector on the line, and the other basis vector can be any vector not one the line. The latter means we have infinite possibilities for different planes, one for each basis vector not on the line.
In $\mathbb{R}^4$ with four points, the points cannot all be on the same plane or line.
Intuitively, we have a similar story as before: two independent vectors span a plane, and three independent vectors span a three dimensional vector space. If we select two independent vectors from a specific plane (the one that our points are on), then we can choose any third independent vector to form a three-dimensional hyperplane. This means there are infinite 3d hyperplanes passing through the plane the points are on.
Note that this means that not even two of the three non-zero points can be on the same line passing through zero. If they were, then whatever the third non-zero point, all points would be on a plane passing through zero.
The four points need to span a hyperplane in $\mathbb{R}^4$. Such a hyperplane is a subspace with three dimensions. Thus, when we view the non-zero points as vectors, they need to be independent. Any hyperplane containing these three non-zero points will thus contain this basis, and will thus be the same subspace.
In $\mathbb{R}^n$ with $n$ points, the vectors represented by the $n-1$ nonzero points need to be independent.
Thus, if we form an $n$ by $n-1$ matrix with such $n-1$ vectors as the columns, then the rank must be $n-1$, ie full column rank.


text:
Q: Formulation of Random Variable Equation So I have a discrete distribution:$$Pr[X=k]=p B(n, a) + (1-p) B(n, b)$$
where $B(n, a)$ and $B(n, b)$ are binomial distributions. I wrote this mixture of distributions from two populations like this:
Let $X\sim B(n, a)$ and let $Y \sim B(n, b)\\$. Then:$$Z \sim p X+(1-p)Y$$
Where Z is my original discrete random variable. Is this notation correct?


text:
Q: firefox sdk: redefine content-script function I have firefox addon, which injects two content scripts to all pages.
var workers = [];

pageMod.PageMod({
  include: "*",
  contentScriptFile: [
       self.data.url("content/autofill/lib_generic.js"),
       self.data.url("content/autofill/lib.js"),
    ],
  // add worker to the list
  onAttach: function(worker)
      {
        workers.push(worker);

        var filename = getDomainSpecificFilename(worker.contentURL);

        worker.on("detach", function()
        {
          var index = workers.indexOf(worker);
          if (index >= 0)
            workers.splice(index, 1);
        });
      }
});

lib_generic.js contains one function named apply_forms(...) (its description is not important). The function is called from lib.js file. But this procedure doesn't work with several pages, so for each such page a I have a specific script - these file also contain only one function named apply_forms(...).
I have a function, which takes current domain as input and returns name of desired specific script or false if generic should be used.
What I need is - when neccessary - redefina generic apply_forms with specific apply_forms.
I've tried to use
tabs.activeTab.attach({
    contentScriptFile: [ filename ]
});

worker.port.emit("apply_forms_loaded");

and in one of content scripts:
var apply_forms_loaded = false;
self.port.on("apply_forms_loaded", function() {
    console.log("LOADED");
    apply_forms_loaded = true;
});

and the whole procedure is started like this:
var timer;

timer = setInterval(function(){

  if (apply_forms_loaded) {

    clearInterval(timer);
    start(); // apply_forms is called somewhere inside this call
  }
}, 10);

Unfortunately it seems that tabs.activeTab.attach injects content scripts in different context so generic function is called allways.
Is there anything I can do to convince activeTab to add content scripts in same context or should I do it different way? (which one then)
Or could problem be in - I don't know - that content script is not fully injected when I send apply_forms_loaded message?
I've been trying to redefine function definition also for Chrome and I've made it work (url to SO question)
Thanks for advice.

A: That's correct, scripts added via pagemod are in a different JS sandbox from those added by tabs.attach. What you could do is inject the functions into the actual window using the new exportFunction() function - this way the function is in the real window and will always get overwritten. You can then call it from unsafeWindow..


text:
Q: JS Will not refresh with caching disabled I have tried everything I can think of including appending .js files with ?ver=blah, and the browser still loads the old version of my script.
If I pull the script .js file up in the browser directly it is still the old file.
If I download it through FTP I get the new file.
I have tried both chrome and firefox browser(I installed FireFox fresh AFTER writing the new JS file, and somehow firefox is STILL loading the old file, which it had never even been exposed to...?)
I added this code at line 30 in the latest verson:
    if (lastRecipeBlockIndex == parent.children().size()) {
        //find tallest column and set parent div height to match
        var tallID = 0;
        for (var i = 0; i < columnHeights.length; i++){
            if (columnHeights[i] > columnHeights[tallID])
                tallID = i;
        }
        parent.height(columnHeights[tallID]);
        return;
    }

Line 31 used to be a return statement.
Url to this file: http://tmurraywellness.com/wp-content/plugins/TM%20Code/TM-script.js?ver=0.01j
What does anyone else see?
The server has to be sending the wrong file. Caching is impossible since I have changed the url. Caching as mentioned is disabled anyway with dev-tools open in both browsers(I manually ticked the box to make that happen)
Any suggestions? I am desperate. I have spent hours trying to get the ten lines of code below to execute in my browser(s)


text:
Q: Mongoose js create collection on start I have a MEAN js app. I need the collections to get created when it is started. Right now, it only gets created when I insert a document in it.
Can something be specified during schema creation?

A: One way to do it is to make sure you have at least one field indexed. Mongoose will create the collection when it creates the indexes.
For example, to index the name field, specify this in your schema: name: {type: String, index: true}.


text:
Q: Deleting a user account and all files / directories I am making a intranet customer manager in php and have put together the following to remove the customer account and the directory / files associated with that account. The problem I am having is when you click delete it is deleting the user from the MYSQL DB just fine, but for some reason isn't removing the directory, what makes it worse is it isn't displaying any errors either, its just working :-S .
    <?php
    $cfid = $_GET['token'];

    mysql_query("DELETE FROM rok5g_chronoforms_data_editcustomer WHERE cf_id = $cfid") or die(mysql_error());

    $dir = '/customer-files/$cfid/';

    //Delete folder function
    function deleteDirectory($dir) {
        if (!file_exists($dir)) return true;
        if (!is_dir($dir) || is_link($dir)) return unlink($dir);
            foreach (scandir($dir) as $item) {
                if ($item == '.' || $item == '..') continue;
                if (!deleteDirectory($dir . "/" . $item)) {
                    chmod($dir . "/" . $item, 0777);
                    if (!deleteDirectory($dir . "/" . $item)) return false;
                };
            }
            return rmdir($dir);
        }

    ?>

A: This won't work.
$dir = '/customer-files/$cfid/';

It has to be double quotes
$dir = "/customer-files/$cfid/";

Read more about it here - http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
Note - This is actually assuming that you call the method deleteDirectory($dir) at some point.
Also, I suggest you read up on SQL injection (if you haven't already). Your script can be broken and the DB harmed quite easily with the current setup.
And, use mysqli if not PDO. It is recommended that you do not use the old mysql library.

A: First check if you have error displaying turned on in php config.
Second check if your server has permissions to delete this folder and files inside it. If you can't execute rmdir($dir) because of missing permissions chmod($dir . "/" . $item, 0777); will probably also fail.

A: Ok, in the end I got it working using the following >>
    <?php
    $cfid = $_GET['token'];

    mysql_query("DELETE FROM rok5g_chronoforms_data_editcustomer WHERE cf_id = $cfid") or die(mysql_error());

    define('PATH', "./customer-files/$cfid/");

    function destroy($dir) {
        $mydir = opendir($dir);
        while(false !== ($file = readdir($mydir))) {
            if($file != "." && $file != "..") {
                chmod($dir.$file, 0777);
                if(is_dir($dir.$file)) {
                    chdir('.');
                    destroy($dir.$file.'/');
                    rmdir($dir.$file) or DIE("couldn't delete $dir$file
");
                }
                else
                    unlink($dir.$file) or DIE("couldn't delete $dir$file
");
            }
        }
        closedir($mydir);
    rmdir("$dir");
    }
    destroy(PATH);
    echo 'all done.';

    ?>


text:
Q: How can we save the widget that will be adding on run (on click of user) in Flutter?
*

*We are creating a noticeboard app and we are pinning widgets on board(Staggered Grid View).

*I tried initializing the list - pinnedWidgets in initState() of main.dart (Only thing I could think of) and that's not working.

*We want the items added in the list to be saved, even when we close the app.

*We have used Hive (local database) as database.

We are unable to save the state of board.
(state of the board: widget data that user will be adding on run)
    List<Widget> pinnedWidgets = []; //tried putting this in initState()
    pinnedWidgets!.add(
                                StaggeredGridTile.count(
                                  crossAxisCellCount: 2,
                                  mainAxisCellCount: 2,
                                  child: InkWell(
                                    onTap: (() {
                                      print('tap on video catched');
                                      print(localfile.path.toString());
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: ((context) => Video(
                                              localfile_path:
                                                  localfile.path)),
                                        ),
                                      );
                                    }),
                                    child: Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Stack(
                                        alignment: Alignment.topCenter,
                                        children: [
                                          Container(
                                            child: Text(
                                              'video link; ${videopath.toString()}',
                                              style: TextStyle(
                                                color: Colors.white,
                                              ),
                                            ),
                                            // child: Image.file(
                                            //     File(videopath.toString())),
                                            decoration:
                                                BoxDecoration(boxShadow: [
                                              BoxShadow(
                                                blurRadius: 3.0,
                                                spreadRadius: 0.5,
                                                offset: Offset(1, 1),
                                              ),
                                            ]),
                                          ),
                                          Image.asset(
                                            'assets/images/pin.png',
                                            width: 13,
                                            height: 13,
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                              );


text:
Q: Is the average force calculated from $F(x)$ the same as that calculated from $F(t)$? Say a force is doing work on an object in one dimension. I could calculate the average force over the distance with
$$\frac{1}{\Delta{x}}\int_{x_1}^{x_2} F(x) \text dx$$
If I also formulated force as a function of $t$, I could calculate the average force over the total time period with
$$ \frac{1}{\Delta{t}} \left| \int_{t_1}^{t_2} F(t) \text dt \right|$$
Obviously, the integrals themselves are not equal. One represents work, and the other represents impulse; $ \Delta{p} \neq \Delta{K} $.
However, if $x_1$ corresponds to $t_1$ and $x_2$ corresponds to $t_2$, could I set the above expressions equal to one another? Does averaging over the interval make them equal? Put another way, I've never seen texts differentiate between the $F_{ave}$ in $W = F_{ave} \cdot \Delta{x}$ and the $F_{ave}$ in $\Delta{p} = F_{ave} \Delta{t}$. Is there a difference? If not, I'm thinking they can relate work to $\Delta{t}$.

A: Before we start, let's assign a "name" to each integral (just for convenience):
$$I_1=\frac{1}{\Delta{x}}\int_{x_1}^{x_2} F(x) \mathrm dx \qquad \text{and} \qquad I_2=\frac{1}{\Delta{t}} \left| \int_{t_1}^{t_2} F(t) \mathrm dt \right|$$
Also, throughout the answer, I will consider the force $F$ to be the net force on the object. I will also be assuming that the mass of the body doesn't change throughout the motion. This way we lose a bit of generality but it becomes way simpler.
Intuition
As you already observed that the average $I_1$ represents the change in kinetic energy divided by the displacement ($\Delta K/\Delta x$). This quantity gives us the answer of the question: What constant force should I apply over the distance $\Delta x$ such that the body gains a kinetic energy $\Delta K$? In other words, it is the average force which would yield the same kinetic energy change (as the original) when applied during the same displacement.
Similarly, the second average, $I_2$, gives us the answer to the question: What constant force should I apply over a time $\Delta t$ so that the body's momenum changes by $\Delta p$ (or equivalently, the body's velocity chnges by $\Delta p/m$)?
Now, we can observe a few differences between both the averages. First, $I_1$ is a displacement average whereas $I_2$ is a time average. Secondly, the change in velocity (or momentum) cannot be independently used to find the change in kinetic energy, which implies both the averges are independent and can independently take different values. Thus there is no reason to believe that both of them are, in any way, equal. However, if the force is a constant, then both the averages will be equal to the constant force. Thus, in uniformly accelerated motion, both the averages will turn out to be equal.
Mathematical Analysis
Let's try to analyse both the averages. It is clear that:
$$I_1=\frac{\Delta K}{\Delta x}=\frac m 2 \frac{(v_{t_2}^2-v_{t_1}^2)}{\Delta x}$$
and
$$I_2=\frac{\Delta p}{\Delta t}=\frac{m(v_{t_2}-v_{t_1})}{\Delta t}$$
Now let's find the ratio of both these averages ($I_1/I_2$):
$$\frac{I_1}{I_2}=\frac{\Delta t}{\Delta x} \frac{(v_{t_2}+v_{t_1})}{2}\tag{1}$$
But $\Delta x/\Delta t$ is the time average of velocity over the time interval $\Delta t$, thus equation $(1)$ can be rewritten as
$$\frac{I_1}{I_2}=\frac{1}{v_{\text{average}}} \frac{(v_{t_2}+v_{t_1})}{2}\tag{2}$$
Thus as you can see, this ratio need not always equal one, which implies that $I_1=I_2$ is not necessarily true. However, in the special case of constant acceleration (where $F(t)$ is a constant, which implies that $a(t)$ is a constant), the time average of velocity comes out to be the average of initial and final velocities, i.e.
$$v_{\text{average}}=\frac{(v_{t_1}+v_{t_2})}{2}$$
Substituting this in equation $(2)$, we get
$$\frac{I_1}{I_2}=1\Longrightarrow I_1=I_2$$
Note: The above analysis, in no way implies that $I_1=I_2$ only when the motion is a uniformly accelerated one. There can be many other scenarios where $v_{\text{average}}=(v_{t_1}+v_{t_2})/2$ even if the acceleration isn't a constant.
In fact, when we divided $I_1$ by $I_2$, we implicitly assumed that $v_{t_1}\neq v_{t_2}$. If $v_{t_1}=v_{t_2}$, we would get a $0/0$ indeterminate form. Although, we can still compare the values of $I_1$ and $I_2$ under this condition, and these simply turn out to be $I_1=I_2=0$. Thus no matter how you change your velocity, if the initial and the final velocities are equal, then both the will become equal to $0$. This is intuitive as well, since in this case, both, the work done and the momentum change are $0$, thus yielding $I_1=I_2=0$.
Summary
Thus, both the averages, in general, aren't equal, but in the case of uniformly accelerated motion, both the averages turn out to be equal.

A: No. They aren't the same. To see why consider the displacement (1D) being parametrised by time in a way to give $x(t)=\alpha t^2$ where alpha is a constant to fix the dimensions. From Newton's second law this gives us $F(x)=2\alpha m$, then,
$$\frac{1}{\Delta x}\int F(x)dx= \frac{1}{\Delta x}\int_{x(t_1)}^{x(t_2)} 2\alpha m dx=2\alpha m\\
\frac{1}{\Delta t} \int F(x(t))dt= \frac{1}{\Delta t}\int_{t_1}^{t_2}\alpha t^2dt= \frac{\alpha}{3}\left(\frac{{t_2}^3-{t_1}^3}{t_2-t_1}\right) $$
Clearly the two are unequal. What gives? It's the measure of the integral that's different in the two cases. Clearly $F(x(t))=F(t)$ as $x$ is parametrised by $t$. However in general $dx\ne dt$ and isn't fixed by normalising the measure either as their rate can differ! And that makes all the difference.

A: The answer is no, they are not the same things.
There is a tacit assumption when texts say things like "the average force," about what the average is performed over. Averaging over position is not the same as averaging over time.
You can always construct simple examples in which it just so happens that they are the same, but that is of limited utility.

A: Your reasoning is valid with the important caveat that you yourself realized: this works if $x_1$ corresponds to $t_1$ and $x_2$ corresponds to $t_2$, and as long as the force over time and the force over distance both remain differentiable during that span of time and space.  You can't equate the two expressions in a general sense and expect that it will hold for all situations.
To draw a physical analogy, imagine a drag racer at the starting line.  If we measure $t_1$ at the moment when the light turns green and the force of his car's rocket begins to propel him forward, then the average force will be equivalent in the two expressions, because the force vector will be applied for the entire time and for the entire distance in a way that is equivalent and differentiable.
If you measure $t_1$ as being 10 seconds prior to the green light, however, then the force is zero for ten seconds, and that brings down the average in your time-based expression. It does not bring down the average in the distance-based expression because the car is in the same place.  You also won't be able to calculate the integral sum for your time-based expression without adding two separate integrals together: one expression for the zero-velocity force at the starting line, plus your integral above which applies to the race itself.   At the point when the green light flashes, the engines ignite and the force vector goes from zero to rocket.  At that moment, the force over time is not differentiable - it has undergone a transition from nothing into something.  This type of non-differentiable change in your system would invalidate the equivalence between your two expressions.

A: To show constructively that these quantities are not equal in general, let's consider an object undergoing simple harmonic motion over a quarter-cycle (i.e., from the equilibrium position to maximum displacement.)  In this case, we have
$$
F(x) = - k x, \qquad x(t) = A \sin \omega t, \qquad t \in [0, \pi/(2\omega)],
$$
with $\omega = k/m$ (though this won't matter in the end.)
The average over displacement is
$$
\langle F \rangle_x = \frac{1}{A} \int_0^A (-kx) \, dx = - \frac{1}{A} \left[ \frac{1}{2} kx^2\right]_0^A = - \frac{1}{2} k A,
$$
while the average over time is
$$
\langle F \rangle_t = \frac{2 \omega}{\pi} \int_0^{\pi/2\omega} (-k A \sin \omega t) \, dt = - \frac{2 k A \omega}{\pi} \left[ - \frac{\cos \omega t}{\omega} \right]_0^{\pi/2\omega} = -\frac{2}{\pi} k A.
$$
Since $\pi \neq 4$,[citation needed] these results are different.


text:
Q: How to implement this list with Android Material Design? I've found a screenshot on the Google Documentation of the Material Design for Android and like to implement this style in my own app. The problem here is, that I have no idea which font sizes and gaps between the elements have to be implemented.
Does anyone has some source code for this example or any hints on the dimensions?

A: Google design guidelines should help you out. I believe the following is relevant to your question:

*

*Lists

*Text fields

*Metrics & keylines
A similar question was asked before, the xml code should give you an idea.


text:
Q: Events not binding to elements in Angular Directives I'm working on an app in Angular and have hit a snag with ng-click not binding to the element when it's being brought in via a Directive. This is basically a goal planning app and this section deals with the obstacles that one has when working on their goal. This section has an obstacle, a solution and an action step(with a date and delegation field associated with this.) But each obstacle can have multiple solutions and each solution can have multiple action steps. So there are "plus" signs that the user can click to add a solution or action step, respectively.
Seems simple enough and I can do this in the controller with jQuery,  but from waht I'm reading about Angular all DOM manipulation should take place in the Directive.
So I created a directive for the Obstacle(with the thoughts that there will also be Solution and Action Step directives for what parts need to be duplicated).
So now it is set up so that when you click one of the pluses, it passes a string to be logged in the console, just to see if it's working. It's not.
The directive is pulling the template into the app and displaying in the DOM, but the ng-click events are not firing the test. My guess is that the event is not being attached to the element.
I've spent the past few days scouring the interweb trying to find a solution and everything I found on attaching events into a Directive has not solved this (and maybe I'm way off on what's happening....)
Anyway, here is the code:
Directive:
app.directive('newObstacle', [function(){

     return {
        // name: '',
        // priority: 1,
        // terminal: true,
        scope: {}, // {} = isolate, true = child, false/undefined = no change
        // controller: function($scope, $element, $attrs, $transclude) {},
        // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
        restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
        // template: '',
        templateUrl: 'views/obstacles-temp.html',
        // replace: true,
        // transclude: true,
        //compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
        //link: function($scope, iElm, iAttrs, controller) {
            //angular.element('.fa').bind('click', function(){});
        //}
    };
}]);

The Controller:
app.controller("newGoalCtrl",[ '$scope', function($scope){
    //this.myGoals = goals;
    $gp = jQuery;

    $scope.addNew = function(addEl){

        switch(addEl){

            case 'affirmation':
                var parent = '#gp_affirmations';
                 console.log(parent);
                break;

            case 'obstacle':
                var parent = '#gp_obstacles';
                 console.log(parent);

                break;

            case 'solution':
                var parent = '#gp_solutions';
                 console.log(parent);

                break;

            case 'action':
                var parent = '#gp_actions';
                 console.log(parent);
                break;

        }
        //$gp(parent).append(childEl);

    }

    $scope.saveGoal = function(goal){

        /*
            Goal Object schema
            Obstacle > Solution > Action
            goal = {
                    'name': '',
                    'description': '',
                    'rewards': '',
                    'consequenses': '',
                    'target-date': '',
                    'todays-date': today,
                    'obstacle' : [{
                        'obstacle-name' : '',
                        'solution'      : {
                            'solution-name' : '',
                            'actions'       : {
                                'action-name'   : '',
                                'target'        : '',
                                'delegate'      : ''
                            },

                        }//solutions
                    }]//obstacle
                };  //goals_meta
                */

        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();

        if(dd<10) {
            dd='0'+dd
        }

        if(mm<10) {
            mm='0'+mm
        }

        goal.today = mm+'/'+dd+'/'+yyyy;

            console.log(goal);

            //saveGoalToDB(newGoal);
        }

}]);

The Template File:

Obstacle: <input type="text" ng-model="goal.obstacle_0" placeholder="If I don't complete, I will..." required / >

 Obstacle Resolution

Obstacle Solution: <input type="text" ng-model="goal.obstacles_solution_0_0" class="obst1-sol" placeholder="If I don't complete, I will..." required / >

 Obstacle's  Action Steps

Step: <input type="text" ng-model="goal.obstacles_solution_actions_0_0_0" class="obst1-as" placeholder="One step I will do to complete this goal..." required / >

Target Date: <input type="date" ng-model="goal.obstacles_solution_target_0_0_0" required />

Delegate: <input type="text" ng-model="goal.obstacles_solution_delegate_0_0_0" placeholder="I will delegate this too..." required / >

Thanks in advance for any help!!

A: It doesn't seem that your controller is wired up to the directive:
 return {
    controller: 'newGoalCtrl',
    restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
    templateUrl: 'views/obstacles-temp.html',
};

Also you need to make sure that you have this declared as a controller in your ng-module
app.controller('newGoalCtrl', <your controller function or reference here>)


text:
Q: Why can Toast be instantiated without the new keyword? So for the Toast class, it can apparently be written like this :
Toast toastMessage = Toast.makeText(this, "Hello", Toast.LENGTH_SHORT)
toastMessage.show();

Why exactly is it possible for toastMessage to be instantiated and used as an object without the new keyword?
How can toastMessage be instantiated by a method?

A: There's nothing special about Toast here. You're just calling a static method which creates an instance (or could possibly reuse an existing one - it's an implementation detail). This is a pattern you'll see all over the place - Calendar.getInstance(), for example. Sometimes you can call the constructor instead, sometimes you can only create an instance via a static method.
Unless something craft is going on under the hood, it's likely that somewhere in the implementation there'll be a call to a constructor. Here's a trivial example:
public final class CreateViaMethod {
    private final String name;

    private CreateViaMethod(String name) {
        this.name = name;
    }

    public static CreateViaMethod newInstance(String name) {
        return new CreateViaMethod(name);
    }
}

There are various reasons why an API designer might want to do this. For example, there might be several "creation" methods with the same parameter types, but different names, e.g.
public static Duration fromSeconds(int seconds)
public static Duration fromMinutes(int minutes)
public static Duration fromHours(int hours)

... you couldn't have three overloaded constructors there, but you can give methods different names.

A: This is a beginner question, but quite a good one. Let me give you a general answer.
let's suppose you have MyClass, like this:
public class MyClass {

    public MyClass() {} //constructor

    public static MyClass generateMyClass() {
        return new MyClass();
    }

}

You can use MyClass.generateMyClass() which creates a MyClass instance and returns it:
MyClass myClassInstance = MyClass.generateMyClass();

The same goes with Toast.makeText. Read more here.

A: Because Toast.makeText() is a static method returning a Toast object.
Toast - Android Developers


text:
Q: Momentary Bosch-style relay with changeover I know this is probably really common electrical engineering knowledge, but I am not an electrical engineer so I am quite lost on this.
I have a 2004 BMW and the fog lights work something like this: They start off, and when I press the fog light button, it is a momentary switch that then turns them on. They then turn off when I press the switch again, or high beams come on, or the lights are turned off.
Here is a really crude diagram I found online. (Ignore rear fog lights as I have none)

Also then here is a link to the actual relay which also has a quite sort of diagram.
OK, now on to my question or a couple of questions. Am I right to assume that this is some sort of latching relay?  Essentially, when 12 V is applied between pins 85 and 86 it energizes, closes the switch from 30 to 87, and completes its circuit. But since the fog light switch is only momentary, it essentially latches the relay between the 30 and 87 pins until 12 V is again applied between pins 85 and 86 OR power to pin 30 disappears (this would be why when you turn the headlights off or high beams on the fog lights turn off).
A next question I have is, is there a Bosch-style relay like this that is a changeover relay? To explain, instead of either switching on and off the switch from 30 to 87, switch between either 30 and 87 or 30 and 87a? I am having a hard time finding a relay that does what I am looking for. It is possible it does not exist. In that case is there a combination of relays or wiring that I could do to achieve this effect?

A: The alternating action is typically inside the push button switch itself, and the relay merely acts as a power switch.
Alternating relays do exist but they are not often found in automobiles.


text:
Q: How to use different kinds of navbar components on different pages I have two different navbar components created for two different subsystems of our project.
App.js
function App() {
  return (
    <>
      <Router>
        <Routes>
          <Route path="/" element={<CirclePage />} />
          <Route
            path = "*"
            element={
              <>
                <Navbar/>
                <Routes>
                  <Route path="/homepage" element={<Homepage />} />
                  <Route path="/events" element={<Events />} />
                  <Route path="/clubs" element={<Clubs />} />
                  <Route path="/notifications" element={<Notifications />} />
                  <Route path="/profile" element={<Profile />} />
                  <Route path="/contact" element={<Contact/>}/>
                </Routes>
              </>
            }
          />

          <Route
            path = "*"
            element={
              <>
                <NavbarClub/>
                <Routes>
                  <Route path="/homepage-club" element={<HomepageClubs />} />
                  <Route path="/events-club" element={<EventManagement />} />
                  <Route path="/contact-clubs" element={<ContactClubs />} />
                  <Route path="/notifications-club" element={<NotificationsClub />} />
                  <Route path="/profile-club" element={<ClubProfile />} />
              </Routes>
              </>
            }
            />

        </Routes>
      </Router>
    </>
  );
}

export default App;

Navbar is visible on every screen except the main screen CirclePage. I want Navbar to be visible on homepage, events, clubs, notifications, profile and contact while NavbarClub to be visible in with the -club pages. How can I implement this?

A: Create layout wrapper components for each that renders the specific navbar and an Outlet for nested Route components.
Example:
import { Outlet } from 'react-router-dom';

const NavbarLayout = () => (
  <>
    <Navbar />
    <Outlet />
  </>
);

const NavbarClubLayout = () => (
  <>
    <NavbarClub />
    <Outlet />
  </>
);

App
function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<CirclePage />} />
        <Route path="*" element={<NavbarLayout />}>
          <Route path="homepage" element={<Homepage />} />
          <Route path="events" element={<Events />} />
          <Route path="clubs" element={<Clubs />} />
          <Route path="notifications" element={<Notifications />} />
          <Route path="profile" element={<Profile />} />
          <Route path="contact" element={<Contact />} />
        </Route>

        <Route path="*" element={<NavbarClubLayout />}>
          <Route path="homepage-club" element={<HomepageClubs />} />
          <Route path="events-club" element={<EventManagement />} />
          <Route path="contact-clubs" element={<ContactClubs />} />
          <Route path="notifications-club" element={<NotificationsClub />} />
          <Route path="profile-club" element={<ClubProfile />} />
        </Route>
      </Routes>
    </Router>
  );
}


text:
Q: How To Send Vault logs to CloudWatch When running Hashicorp Vault on EC2, I'm able to install the CloudWatch agent and ship logs to over CloudWatch in order to create alerts and notifications on specific events.
However, when running Vault via a helm chart in Kubernetes, I'm not sure how to go about the same thing.
Is there a way to install the CloudWatch agent when running Vault in Kubernetes? Or some other way to get the logs to CloudWatch?
I have the file audit device enabled at vault/audit/vault_audit.log but all the logs are currently sitting on that file.
It's back by persistent storage, but ideally, ,I'd like to get it into CloudWatch somehow.


text:
Q: Is there a way to specific 'all except' in RunDeck ACLs? In order to allow users to see a specific job but not actually be able to do anything with it I have the following in place in the relevant .aclpolicy file (edited down for brevity):
context:
  project: '.*'
for:
  job:
    - deny: [run,create,delete,kill,killAs,runAs,scm_create,scm_delete,scm_update,toggle_execution,toggle_schedule,update,read]
      equals:
        uuid: ee70e193-733c-4cb2-bdf0-0d6672da563f
    - allow: '*'
by:
  group: [users]

The deny line here is listing all available actions except view.  I want my users to have access to all other jobs (in the example above I have '*' for the allowed actions, just by way of example).
What I'm wondering is if there is a way to shorten the deny line to something like - deny: [!view] or something -- basically an "everything except view" shortcut.
While the above works, I'm worried that a future update might add in extra actions, and these will then be available for this job as they are not specifically denied.

A: By default Rundeck ACLs denies all actions (works like a network firewall, denies all and you need to open step by step), in your case, you can use - allow: [view].
EDIT: Right now doesn't exist a rule like the question.


text:
Q: maxlength ignored for input type="number" in Chrome The maxlength attribute is not working with <input type="number">. This happens only in Chrome.
<input type="number" class="test_css"  maxlength="4"  id="flight_number" name="number"/>

A: try use tel :
 maxlength="5" type="tel"

A: I wrote a small and clean workaround. Using this function will make it work, as it should
  const inputHandler = (e) => {
    const { value, maxLength } = e.target;
    if (String(value).length >= maxLength) {
      e.preventDefault();
      return;
    }
  };

For example, it can be used in React like this:
<input
  type="number"
  maxlength="4"
  onKeyPress={inputHandler}
/>

A: this code worked for me

<form method="post">
      My Number:
      <input type="number" maxlength="9" required
      oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" >

      <input type="submit" value="Submit">
</form>

A: Chrome (technically, Blink) will not implement maxlength for <input type="number">.
The HTML5 specification says that maxlength is only applicable to the types text, url, e-mail, search, tel, and password.

A: Here is my solution with jQuery...
You have to add maxlength to your input type=number
$('body').on('keypress', 'input[type=number][maxlength]', function(event){
    var key = event.keyCode || event.charCode;
    var charcodestring = String.fromCharCode(event.which);
    var txtVal = $(this).val();
    var maxlength = $(this).attr('maxlength');
    var regex = new RegExp('^[0-9]+$');
    // 8 = backspace 46 = Del 13 = Enter 39 = Left 37 = right Tab = 9
    if( key == 8 || key == 46 || key == 13 || key == 37 || key == 39 || key == 9 ){
        return true;
    }
    // maxlength allready reached
    if(txtVal.length==maxlength){
        event.preventDefault();
        return false;
    }
    // pressed key have to be a number
    if( !regex.test(charcodestring) ){
        event.preventDefault();
        return false;
    }
    return true;
});

And handle copy and paste:
$('body').on('paste', 'input[type=number][maxlength]', function(event) {
    //catch copy and paste
    var ref = $(this);
    var regex = new RegExp('^[0-9]+$');
    var maxlength = ref.attr('maxlength');
    var clipboardData = event.originalEvent.clipboardData.getData('text');
    var txtVal = ref.val();//current value
    var filteredString = '';
    var combined_input = txtVal + clipboardData;//dont forget old data

    for (var i = 0; i < combined_input.length; i++) {
        if( filteredString.length < maxlength ){
            if( regex.test(combined_input[i]) ){
                filteredString += combined_input[i];
            }
        }
    }
    setTimeout(function(){
        ref.val('').val(filteredString)
    },100);
});

I hope it helps somebody.

A: <input type="number" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" onKeyDown="if(this.value.length==10 && event.keyCode!=8) return false;">

DEMO - JSFIDDLE

A: Input type text and oninput event with regex to accept only numbers worked for me.
<input type="text" maxlength="4" oninput="this.value=this.value.replace(/[^0-9]/g,'');" id="myId"/>

A: I have two ways for you do that
First: Use type="tel", it'll work like type="number" in mobile, and accept maxlength:
<input type="tel" />

Second: Use a little bit of JavaScript:

<input type="tel" onKeyDown="if(this.value.length==2 && event.keyCode!=8) return false;" />

A: Try this,
<input type="number" onkeypress="return this.value.length < 4;" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />

A: If you want to do it in a React Function Component or without using "this", here is a way to do it.
<input onInput={handleOnInput}/>

const handleOnInput = (e) => {
  let maxNum = 4;
  if (e.target.value.length > maxNum) {
    e.target.value = e.target.value.slice(0, maxNum);
  }
};

A: The below code will allow the user to:

*

*Enter digits only in the 0-999 range.

*This also restricts the user not to enter more than 3 characters.

*When the user enters more than 3 characters then it will clear the textbox.

<input type="number" name="test_name" min="0" max="999" oninput="validity.valid||(value='');">

A: From MDN's documentation for <input>

If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.

So maxlength is ignored on <input type="number"> by design.
Depending on your needs, you can use the min and max attributes as inon suggested in his/her answer (NB: this will only define a constrained range, not the actual character length of the value, though -9999 to 9999 will cover all 0-4 digit numbers), or you can use a regular text input and enforce validation on the field with the new pattern attribute:
<input type="text" pattern="\d*" maxlength="4">

A: In my experience most issues where people are asking why maxlength is ignored is because the user is allowed to input more than the "allowed" number of characters.
As other comments have stated, type="number" inputs do not have a maxlength attribute and, instead, have a min and max attribute.
To have the field limit the number of characters that can be inserted while allowing the user to be aware of this before the form is submitted (browser should identify value > max otherwise), you will have to (for now, at least) add a listener to the field.
Here is a solution I've used in the past: http://codepen.io/wuori/pen/LNyYBM

A:
maxlength ignored for input type="number"

That's correct, see documentation here
Instead you can use type="text" and use javascript function to allow number only.
Try this:

function onlyNumber(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)){
            return false;
        }
    return true;
}
<input type="text" maxlength="4" onkeypress="return onlyNumber(event)">

A: Max length will not work with <input type="number" the best way i know is to use oninput event to limit the maxlength. Please see the below code.
<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />

A: You can use the min and max attributes.
The following code do the same:

<input type="number" min="-999" max="9999"/>

A: I know there's an answer already, but if you want your input to behave exactly like the maxlength attribute or as close as you can, use the following code:
(function($) {
 methods = {
    /*
     * addMax will take the applied element and add a javascript behavior
     * that will set the max length
     */
    addMax: function() {
        // set variables
        var
            maxlAttr = $(this).attr("maxlength"),
            maxAttR = $(this).attr("max"),
            x = 0,
            max = "";

        // If the element has maxlength apply the code.
        if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) {

            // create a max equivelant
            if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){
                while (x < maxlAttr) {
                    max += "9";
                    x++;
                }
              maxAttR = max;
            }

            // Permissible Keys that can be used while the input has reached maxlength
            var keys = [
                8, // backspace
                9, // tab
                13, // enter
                46, // delete
                37, 39, 38, 40 // arrow keys<^>v
            ]

            // Apply changes to element
            $(this)
                .attr("max", maxAttR) //add existing max or new max
                .keydown(function(event) {
                    // restrict key press on length reached unless key being used is in keys array or there is highlighted text
                    if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false;
                });;
        }
    },
    /*
     * isTextSelected returns true if there is a selection on the page.
     * This is so that if the user selects text and then presses a number
     * it will behave as normal by replacing the selection with the value
     * of the key pressed.
     */
    isTextSelected: function() {
       // set text variable
        text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        return (text.length > 0);
    }
};

$.maxlengthNumber = function(){
     // Get all number inputs that have maxlength
     methods.addMax.call($("input[type=number]"));
 }

})($)

// Apply it:
$.maxlengthNumber();

A: Done! Numbers only and maxlength work perfect.
<input  maxlength="5" data-rule-maxlength="5" style="height:30px;width: 786px;" type="number"  oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />

A: This code worked quite nicely for me.
In the input with type="number", you can add the following attribute:
oninput="constrainUserInput(this.id)"

The full input will look like this:
<input type="number" class="test_css" maxlength="4" oninput="constrainUserInput(this.id)" id="flight_number" name="number"/>

Note: You must assign your input and ID for this method to work

Then you can add the following JavaScript to your HTML, which basically replaces any characters that exceed your maxlength attribute with an empty quote (essentially removing them):
function constrainUserInput(id) {
  let input = document.getElementById(id);
  let value = input.value;
  if (value.length > input.maxLength) {
    input.value = value.substring(0, input.maxLength);
  }
}

A:
This works in Android as well

Change your input type to text and use "oninput" event to call function:
<input type="text" oninput="numberOnly(this.id);" maxlength="4" id="flight_number" name="number"/>

Now use Javascript Regex to filter user input and limit it to numbers only:
function numberOnly(id) {
    // Get element by id which passed as parameter within HTML element event
    var element = document.getElementById(id);
    // This removes any other character but numbers as entered by user
    element.value = element.value.replace(/[^0-9]/gi, "");
}

Demo: https://codepen.io/aslami/pen/GdPvRY

A: The absolute solution that I've recently just tried is:
<input class="class-name" placeholder="1234567" name="elementname"  type="text" maxlength="4" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />

A: As per the Neha Jain's answer above ,I just added below code to common area
$(':input[type="number"]').on('input', function() {
        if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);

});

then you can use maxlength="4" like text type fields.

A:

<input type="number" min="1" onKeyPress="if(this.value.length==5) return false"/>

Use type number with min and handle max with onKeyPress
<input type="number" min="1" onKeyPress="if(this.value.length==5) return false"/>

A: For React users,
Just replace 10 with your max length requirement
 <input type="number" onInput={(e) => e.target.value = e.target.value.slice(0, 10)}/>

A: how to limit input type max length
<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />

A: Many guys posted onKeyDown() event which is not working at all i.e. you can not delete once you reach the limit. So instead of onKeyDown() use onKeyPress() and it works perfectly fine.
Below is working code:

User will not be allowed to enter more than 4 digits

<input type="number" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==4) return false;" />

A: You can try this as well for numeric input with length restriction
<input type="tel" maxlength="4" />

A: I once got into the same problem and found this solution with respect to my needs.
It may help Some one.
<input type="number" placeholder="Enter 4 Digits" max="9999" min="0"
onKeyDown="if(this.value.length==4 && event.keyCode>47 && event.keyCode < 58)return false;"
/>

Happy Coding :)

A: <input type="number"> is just that... a number input (albeit, unconverted from a string to float via Javascript).
My guess, it doesn't restrict characters on key input by maxLength or else your user could be stuck in a "key trap" if they forgot a decimal at the beginning (Try putting a . at index 1 when an <input type"text"> "maxLength" attr has already been reached). It will however validate on form submit if you set a max attribute.
If you're trying to restrict/validate a phone number, use the type="tel" attr/value. It obeys the maxLength attr and brings up the mobile number keyboard only (in modern browsers) and you can restrict input to a pattern (i.e. pattern="[0-9]{10}").

A: I will make this quick and easy to understand!
Instead of maxlength for type='number' (maxlength is meant to define the maximum amount of letters for a string in a text type), use min='' and max='' .
Cheers

A: I was able archive it using this.
<input type="text" onkeydown="javascript: return event.keyCode === 8 || event.keyCode === 46 ? true : !isNaN(Number(event.key))" maxlength="4">

A: I had problem with this on django forms.Form this is the code of how I solved it.
HTML
<input type="tel" maxlength="6" oninput="this.value=this.value.replace(/[-]/g,'');"></input>

Django form
class TokenForm(forms.Form):
code = forms.CharField(
    required=True,
    label="Enter 6 digit confirmation code",
    widget=forms.TextInput(
        attrs={
            "class": "form-control",
            "placeholder": "Enter 6 digit code",
            "type": "tel",
            "maxlength":"6",
            "oninput":"this.value=this.value.replace(/[-]/g,'');"
        }
    ),
)

A: Try it out on React.
<input
   onInput={(e) => {
   if (e.target.value.length > e.target.maxLength)
   e.target.value = e.target.value.slice(0,e.target.maxLength);
}}
    type = "number"
    maxlength = {6}
 />

A: maxlenght - input type text
<input type="email" name="email" maxlength="50">

using jQuery:
$("input").attr("maxlength", 50)

maxlenght - input type number
JS
function limit(element, max) {
    var max_chars = max;
    if(element.value.length > max_chars) {
        element.value = element.value.substr(0, max_chars);
    }
}

HTML
<input type="number" name="telefono" onkeydown="limit(this, 20);" onkeyup="limit(this, 20);">


text:
Q: Why can I not set the selection of a drop down list in VB.net before the form has been shown? I cannot seem to get Visual Studio 2010 to let me set the SelectedItem or SelectedIndex property of a drop down list before the form has been shown on the screen. I can set these without issue if I wait until the form can be seen, so I'm not sure what the problem is. Here is my code.
Private Sub Test_Program_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    For each item in System.IO.Directory.GetFiles(Application.StartupPath + "\Pictures\")
        dd_pics.items.add(item)
    Next
    dd_pics.SelectedIndex = 0
    background = dd_pics.SelectedIndex
End Sub

background is an integer variable. I've tried to change SelectedIndex to SelectedItem and change the background variable type to string, but that hasn't helped. Later in the code, I use the background variable to set a picture based on the file it references from the above code. I do not get an error, but it seems as if Visual Studio is skipping the line dd_pics.SelectedIndex = 0 and all sequential lines in the Sub. I found this out because I'm actually getting an error when I try to set the picture referenced here to a PictureBox and the debugger is telling me there is Nothing in the variable I am trying to set the PictureBox to. I can use the exact same code in a button and it works fine. The only difference I can find is that the form is fully loaded and I have to click the button where it is automated here. Can anybody at least tell me when Visual Studio is having this problem or possibly how to fix it? Any help is greatly appreciated. Thanks in advance.

A: I usually do these in the constructor:
Public Sub New()

  ' This call is required by the designer.
  InitializeComponent()

  ' Add any initialization after the InitializeComponent() call.
  For each item in System.IO.Directory.GetFiles(Application.StartupPath + "\Pictures\")
    dd_pics.items.add(item)
  Next
  dd_pics.SelectedIndex = 0
  background = dd_pics.SelectedIndex
End Sub

Could this work in your situation?


text:
Q: how to call a PHP class function in another page by a link i have a menu that has an option to retrieve data from the database and show it to the user, i set up a link on an icon, when the user clicks on the icon, i want it to redirect to the php class page and call a function from it, i don't need to pass any parameter to it, i just want to call the function, how can i do this?
the menu

                   see menu

the php class page
class userRides
{

function showMenu()
{

//retrieve data and show it
}

//other functions
}

A: A PHP class isn't a "page", and doesn't correspond to a particular URL which you can request directly from the browser. To execute the method, you write some PHP code which includes the file which defines it, and then uses it, e.g.
require_once __DIR__ . '/../classes/userRides.php';
$rides = new userRides;
$rides->showMenu();

(Or you can configure an autoloader which automatically triggers the file include when you use the class.)
You then place that code in a file and point your web server at that. For instance, your web server might point at the directory "/home/h.nasserel/website/public", the three lines above in "/home/h.nasserel/website/public/menu.php", and the class in "/home/h.nasserel/website/classes/userRides.php". You would then access "http://something.example.com/menu.php" in your browser, and it would run the PHP code.


text:
Q: How to mark an issue as resolved on Bit Bucket? I am working on this project and I was assigned to work on an issue. I have finished my work on the issue. How do I make it resolved? I don't see any button that does that or do I need to add something in the commit message?

A: Check in the work flow drop down if it doen't appear directly on the issue. You can also resolve issues using commit messages it seems. Please refer https://confluence.atlassian.com/bitbucket/resolve-issues-automatically-when-users-push-code-221451126.html


text:
Q: How equals() different than == in Java As we know == compare references and equals() compare the content. But after checking equals() implementation in Object class I got confused. the implementation is,
public boolean equals(Object obj) {
        return (this == obj);
    }

as you see the implementation. equals internally calling == operator. Then how it different?

A: They're simply different in that you can override equals(), but cannot override == in any way.
So while equals() may check for logical equality of two objects if the class author decides so, == will always compare the reference and thus be true only if both operands are the same object (or same primitive value).

A: The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn't make a difference. Its the "value" (that is: the contents of the character array) inside each String instance that is being compared.
On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".


text:
Q: Threshold exceeded using Add-pnpfile We are trying to use the PowerShell SharePoint module, Pnp.PowerShell, more exactly the Add-Pnpfile cmdlet, but, our site has to many files on the list (more than 5000), so we are getting a error: The attempted operation is prohibited because it exceeds the list view threshold
Does its possible to modify this threshold?
Thank you for your time.
Best regards


text:
Q: How do you use the developers Name instead of hard coding RecordTypeID? Thanks! How do you use the developers Name instead of hard coding RecordTypeID? Thanks!

A: You can use the RecordTypeInfo class to get a list of record types without using a query, and select one based on the name of the record type.

A: Just to add, I have created a RecordTypeUtility Class.. feel free to try it out..
public class RecordTypeUtils {
    public static List<RecordType> RECORD_TYPES {
        get {
            if (RECORD_TYPES == null) {
                RECORD_TYPES = [
                    select Name,Id,
                        DeveloperName
                    from RecordType
                ];
            }

            return RECORD_TYPES;
        }
        private set;
    }

    public static Map<String, Id> RECORD_TYPE_BY_DEVNAME {
        get {
            if (RECORD_TYPE_BY_DEVNAME == null) {
                RECORD_TYPE_BY_DEVNAME = new Map<String, Id>();

                for (RecordType rt: RECORD_TYPES) {
                    RECORD_TYPE_BY_DEVNAME.put(rt.DeveloperName, rt.Id);
                }
            }

            return RECORD_TYPE_BY_DEVNAME;
        }

        private set;
    }

    public static Map<String, Id> RECORD_TYPE_BY_NAME {
        get {
            if (RECORD_TYPE_BY_NAME == null) {
                RECORD_TYPE_BY_NAME = new Map<String, Id>();

                for (RecordType rt: RECORD_TYPES) {
                    RECORD_TYPE_BY_NAME.put(rt.Name, rt.Id);
                }
            }

            return RECORD_TYPE_BY_NAME;
        }
        private set;
    }
}

Then you just call the class..
 Id foo = RecordTypeUtils.RECORD_TYPE_BY_NAME.get('bar'); or dev name..

A: I always use
where RecordType.Name = 'developerName'

A: I created a couple of utility methods to do this better.
//Gets all record types by SObject
public static Map<String, Schema.RecordTypeInfo> getRecordTypeBySObject(String apiName)
{
    return Schema.getGlobalDescribe().get(apiName).getDescribe().getRecordTypeInfosByName();
}

//Gets a specific RecordType by SObject name/Label
public static Id getRecordTypeId(String objApiName, String recordTypeLabel)
{
    return getRecordTypeBySObject(objApiName).get(recordTypeLabel).getRecordTypeId();
}

A: It is best practice To use "RecordType.Name" via Query
Because ID will be Different in Sandbox and in Production, If you mention the Id in Test class it will pass the method in sandbox but doesn't validate in the production.


text:
Q: "Imported content is empty" Google Sheet =IMPORTXML("https://www.tradingview.com/chart/1BxJl0Xz/", "//body/div/div/div/div/div/table/tr[3]/td/div/div/div/div[1]/div[1]/div[3]/div/div/div")

So i am trying to extract this information

to my google sheets but i it just says that imported content is empty. Anybody have any idea how to fix this issue? :(
The path line i tried using inside my google sheet comes from this line in chrome console

A: This isn't going to work because that page appears to be using javascript to generate the content.
So while the xpath is valid (I'd guess since I checked on that page and tried this myself) the xpath doesn't actually exist when you use importXML because that will not trigger the javascript.
If you run wget or use the powershell below, you can browse the raw content and see that the values you see in a browser don't exist because no javascript is running.
(iwr "https://www.tradingview.com/chart/1BxJl0Xz/").RawContent | more
You'll need to do something else to make this happen.


text:
Q: redis-cli on windows 7 has strange ascii characters when I run my redis-cli on windows, it show the following message.
redis 127.0.0.1:6379> help @generic
     [1mDEL[0m [90mkey [key ...][0m

    .......

       [1mDUMP[0m [90mkey[0m
       [33msummary:[0m Return a serialized version of the value stored at the fied key.
       [33msince:[0m 2.6.0

       [1mEXISTS[0m [90mkey[0m
       [33msummary:[0m Determine if a key exists
       [33msince:[0m 1.0.0

It seems that there is some ascii color charactars show not the color show in the window. Do I need to do some configuration in my windows 7?

A: Those unix TTY color codes are not meant for cmd.exe on Windows, what you are seeing is a minor problem that is not addressed (yet).
Redis on Windows is beta software.
It makes sense that MSOpenTech focus on redis-server, and not on redis-cli which is mainly a testing client that technically isn't needed. On top of that, redis-cli works, it's only the default formatting of HELP and other feedback that's faulty.
You can work around this by using this redis-cli option:
--raw              Use raw formatting for replies (default when STDOUT is
                   not a tty).

To see all options, do:
redis-cli --help

If it bothers you, post an issue on (https://github.com/MSOpenTech/redis) .
Hope this helps, TW


text:
Q: Как дождаться разблокировки мьютекса потока, запущенного сигналом Qt? Есть такой код
for (;;) {
    //...
    _mutex.unlock();
    f();
    _mutex.lock();
    //...
}

Функция f() вызывает сигнал Qt для перерисовки, обработка которого, как я понимаю происходит в новом неизвестном мне потоке, и он не всегда успевает захватить мьютекс и _mutex.lock из кода выше срабатывает раньше. Как я могу заставить _mutex.lock выполниться не раньше, чем отработает обработка сигнала? Я использую потоки C++11.

A: Вы что-то делаете не правильно, блокировать/разблокировать мутекс должны потоки выполняющие работу с разделяемым ресурсом. То есть, раз потоки "знают" о ресурсе, то они обязаны "знать" и о мутексе. Это означает, что вам нужно "протянуть" мутекс внутрь f(). Либо выбрать другую схему синхронизации, например на сообщениях, которыми, кстати, и являются сигналы Qt.


text:
Q: error installing PyObjC osX I am new to Python and I am desperately trying to install PyObjC via spyder.
The command
pip install PyObjC

returns an error:

Command "python setup.py egg_info" failed with error code 1 in
  /private/var/folders/0v/cg_rdz_x4d32jm6hz7n5txgh3djxb1/T/pip-build-UBlDtP/pyobjc-core/

No solutions found in other posts worked. I have also tried to install the whole thing manually & via conda.
It seems that Xcode is installed.
And it is the only module I have had issues with.
Any suggestions? :)
Note: I´m working with Python 2.7, on a macOS Sierra 10.12

A: The actual error message which can help more is in the beginning of the traceback. In my case it is
xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  ...

If you are getting the same, here are the answers on how to debug this:
xcode-select active developer directory error


text:
Q: Play framework 2.0: Create validation error message using attribute value Using scalaforms for the play framework, say that i have form such as:
case class User(name: String, emails: List[String])

val userForm = Form(
    mapping(
        "name" -> text,
        "emails" -> list(text).verifying("Emails are duplicated",x => SomeFunctionThatHandlesDuplicateEmails(x))
    )(User.apply, User.unapply)
  )

Where SomeFunctionThatHandlesDuplicateEmails is a function that returns false (thus, making the field invalid) if any of the emails received in the form is already in database.
Now then, my question is:
Is there a way to use the value of the validated field to create the error message? I would like to tell the user which emails in particular were duplicated, not just tell them "Emails are duplicated" as shown above.

A: verifying() takes a series of Constraint[T].
You can see examples of Constraints implemented here.
Note that the validation function in each receives the value to be validated e.g. "o"  in the "min" constraint repeated below:
 def min(minValue: Int): Constraint[Int] = Constraint[Int]("constraint.min", minValue) { o =>
   if (o >= minValue) Valid else Invalid(ValidationError("error.min", minValue))
 }

This could just as easily be:
 def min(minValue: Int): Constraint[Int] = Constraint[Int]("constraint.min", minValue) { o =>
   if (o >= minValue) Valid else Invalid(ValidationError("error.min", minValue, o))
 }

which would make "o" available to the error message formatter as {1} (minValue is {0}).


text:
Q: How to fix "error:cannot generate COM file, stack segment present"? I've been trying to fix my code for a while, but I can't seem to get it to work.It always tells me error:cannot generate COM file, stack segment present. Any ideas how I can fix this?
Here's my code:
.model small
.386
.stack 100h
.data
     inpM db "Input string: $"
     input db 19              ; max allowed 20
              db ?                ; # char entered
              db 19 dup(0)   ; chars entered
     output db 19 dup("$")
.code
start:    mov ax, @data
            mov ds, ax

            mov ah, 9              ; print inpM
            lea dx, inpM
            int 21h

            mov ah, 0Ah         ; get input
            lea si, input
            mov dx, si
            int 21h

            mov cl, [si+1]        ; reverse
            mov ch, 0
            add si, cx
            inc si
            lea di, output

rev:      mov al, [si]
            mov [di], al
            dec si
            inc di
            loop rev

again:  mov ah, 6         ; clrscr
            mov al, 0
            mov cl, 0
            mov ch, 0
            mov dl, 4Fh
            mov dh, 18h
           mov bh, 0Fh
           int 10h

          mov ah, 0
          mov bh, 0
          mov dl, 27h            ; column
          mov dh, 0               ; row

          mov ah, 9               ; print output
          lea dx, output
          int 21h

          mov bx, 20000       ; delay
l1:       mov cx, 0Fh

l2:      dec bx
          loop l2
          jnz l1

          add dh, 1                ; adds 1 to row

          loop again

          mov ah, 4Ch
          int 21h
end start

Additional info: My code reverses a string input then displays it in rows with a delay. Hoping to find out what's the cause of the error and how I'll be able to fix it.

A: I'm assuming from the error you are using TASM and TLINK to build this as a .COM program and not an EXE. Things you need to be aware of:

*

*COM programs should use the tiny model, not small.

*COM programs need to start with an ORG of 100h after you start the .code segment.

*The stack in a COM program starts from the top of the segment the code runs in so setting the stack size needs to be removed.

*You no longer need to set up DS as you would with building an EXE file since CS=DS=ES=SS with a COM program.

With those things in mind, you can modify the top of your code to appear like this:
.model tiny
.386
.data
     inpM db "Input string: $"
     input db 19              ; max allowed 20
              db ?                ; # char entered
              db 19 dup(0)   ; chars entered
     output db 19 dup("$")
.code
org 100h
start:
        mov ah, 9              ; print inpM
        lea dx, inpM
        int 21h

        ...

You can then build it with:
tasm myprg.asm
tlink /t myprg.obj


text:
Q: In which cases can we find the tikz key "execute at begin to" useful In the the tikz/pgf manual, we can read in the subsection "14.13 The to path operation"   about the key /tikz/execute at begin to but without any examples on how to use it concretely. So I am asking for some examples that may demonstrate how this key may be useful in practical cases. So please give one example by answer.

A: OK, here is a rather simple but perhaps not completely pointless example which draws a line parallel to the line you want to draw.
\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{calc}
\tikzset{
illustrate at begin to/.style=
    {to path={
      (\tikztostart) -- (\tikztotarget) \tikztonodes
    },
    execute at begin to={
    \draw[blue] ($(\tikztostart)!5pt!90:(\tikztotarget)$) --
    ($(\tikztotarget)!5pt!-90:(\tikztostart)$) node[midway,above,sloped]{I'm parallel};}}
}

\begin{document}
\begin{tikzpicture}
\draw[illustrate at begin to] (0,0) to (5,1);
\draw[illustrate at begin to] (0,-2) to (4,-3);
\end{tikzpicture}
\end{document}

Just for fun, another application, using Jake's complete sines and motivated by (my interpretation of) this question. (No, this trick does not work for curved paths, just in case you're wondering. ;-)
\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{decorations,calc}
\pgfdeclaredecoration{complete sines}{initial}
{
    \state{initial}[
        width=+0pt,
        next state=sine,
        persistent precomputation={\pgfmathsetmacro\matchinglength{
            \pgfdecoratedinputsegmentlength / int(\pgfdecoratedinputsegmentlength/\pgfdecorationsegmentlength)}
            \setlength{\pgfdecorationsegmentlength}{\matchinglength pt}
        }] {}
    \state{sine}[width=\pgfdecorationsegmentlength]{
        \pgfpathsine{\pgfpoint{0.25\pgfdecorationsegmentlength}{0.5\pgfdecorationsegmentamplitude}}
        \pgfpathcosine{\pgfpoint{0.25\pgfdecorationsegmentlength}{-0.5\pgfdecorationsegmentamplitude}}
        \pgfpathsine{\pgfpoint{0.25\pgfdecorationsegmentlength}{-0.5\pgfdecorationsegmentamplitude}}
        \pgfpathcosine{\pgfpoint{0.25\pgfdecorationsegmentlength}{0.5\pgfdecorationsegmentamplitude}}
}
    \state{final}{}
}

\begin{document}
\tikzset{fancy sines/.style={#1,decoration={
            complete sines,
            segment length=3mm,
            amplitude=1mm
        },decorate,to path={
      (\tikztostart) --
      ($(\tikztotarget)!{-5*\pgflinewidth}!-135:(\tikztostart)$)
      (\tikztotarget) \tikztonodes
    },
    execute at begin to={\foreach \X in {1,...,5}
    {\draw[decorate,#1]
    ($(\tikztostart)!{\X*\pgflinewidth}!45:(\tikztotarget)$)
    -- ($(\tikztotarget)!{(-5+\X)*\pgflinewidth}!-135:(\tikztostart)$);}}}
}
\begin{tikzpicture}
\draw[fancy sines=blue] (0,0) to (0,-3);
\draw[fancy sines=red] (0,0) to (3,0);
\draw[fancy sines=green!60!black] (3,0) to (0,-3);
\end{tikzpicture}
\end{document}


text:
Q: iOS: Provisioning profile missing private key? In my Keychain, I have my iOS developer certificate, along with its nested private key.
In the Apple developer center, I created a provisioning profile under Distribution for my app, and downloaded it. When I bring it into Xcode, I see the provisioning profile but it says "valid signing identity not found" and I can't properly build an archive for ad hoc distribution.
How can I resolve this? Like I said, under my Keychain, I have my private key AND my developer profile certificate.

A: In the apple developer's Certificates, Identifiers and Profiles section, you have an option to generate a certificate for ad-hoc or app store. After selection that, you should have to create a signing request such as this screen...

once you created a certificate, then proceed to create a provisioning profile with THAT certificate.

A: When you were creating your provisioning profile in the provisioning portal your first step would have been to select Distribution or Development (you selected Distribution).
Then in the second step you were supposed to select app ID (make sure this app ID matches the bundle ID of your app).
Then on the next screen you select the certificate with which to sign this provisioning profile. Make sure this is the same certificate that you downloaded. It needs to be a special distribution certificate that you would have created beforehand. Note the name and the expiration date of the certificate, then download this certificate from the Production section in Certificates.

A: There are some few steps to get it working:

*

*Request a certificate from Keychain Access -> Certificate Assistant

*Add iOS Certificate from developer.apple.com -> Certificates, Identifiers & Profiles -> Certificates

*Download that certificate

*Then add iOS Provisioning Profiles with that Certificate

It worked for me.