text:
Q: Running two linux commands via PHP, don't wait for first to end before executing second This is pretty weird, and I searched and tried everything, but I think I'm just making a dumb syntax error here.
I'm trying to run a stress test on the CPU , then immediately limit it's cpu usage to 30% , all this via PHP. The test is also run under another user and with a specified name so it can be limited. The stress test starts fine, but I can see the PHP file still loading, and it ends the second the stress test ends.
Here's some of the ways I tried doing it
$output = exec('sudo runuser -l test -c "exec -a MyUniqueProcessName stress -c 1 -t 60s & cpulimit -e MyUniqueProcessName -l 30"');

$output = exec('sudo runuser -l test -c "exec -a MyUniqueProcessName stress -c 1 -t 60s > /dev/null & cpulimit -e MyUniqueProcessName -l 30"');

The whole purpose of this is because I am writing a script for a game hosting website, and I want to limit the resource consumption of each server to improve quality and not let someone hog all the resources.
Basically, instead of the stress test, a game server will run.
edit::
here's what I have now:
I need to run the stress under "test" , but the cpulimit under either sudo apache or root, because it requires special permissions. The stress still starts fine but it eats 99.9%
passthru('sudo runuser -l test -c "exec -a MyUniqueProcessName stress -c 1 -t 60s &" & sudo cpulimit -e MyUniqueProcessName -l 30 -i -z');

I can't see the cpulimit in the process list after doing this http://i.imgur.com/iK2nL43.png

A: Unfortunately, the && does more or less the opposite of what you want. :-) When you do A && B in Bash, that means, "Run command A and wait until it's done; if it succeeded, then run command B."
By contrast, A & B means, "Run command A and then immediately run command B."
So you're close to right in your command, but just getting tripped up by using two bash commands (should only need one) and the &&.
Also, did you try running each command separately, outside PHP, in two terminals? I just downloaded and built both stress and cpulimit (I assume these are the ones you're using?), ran the commands separately, and spotted a problem: cpulimit still isn't limiting the percentage.
Looking at the docs for stress, I see it works by forking child processes, so the one you're trying to CPU-limit is the parent, but that's not the one using the CPU. cpulimit --help reveals there's option -i, which includes child processes in what is limited.
This gets me to the point of being able to enter this in one terminal (first line shows input at the prompt; subsequent show output):
$> exec -a MyUniqueProcessName stress -c 1 -t 60s & cpulimit -e MyUniqueProcessName -l 30 -i
[1] 20229
MyUniqueProcessName: info: [20229] dispatching hogs: 1 cpu, 0 io, 0 vm, 0 hdd
Process 20229 found

Then, in another terminal running top, I see:
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM     TIME+ COMMAND
20237 stackov+  20   0  7164  100    0 R 30.2  0.0   0:04.38 stress

Much better. (Notice that outside the Bash shell where you aliased it with exec -a, you will see the process name as stress.) Unfortunately, I also see another issue, which is cpulimit remaining "listening" for more processes with that name. Back to cpulimit --help, which reveals the -z option.
Just to reduce the complexity a bit, you could leave the alias off and use the PID of the stress process, via the special Bash variable $!, which refers to the PID of the last process launched. Running the following in a terminal seems to do everything you want:
stress -c 1 -t 60s & cpulimit -p $! -l 30 -i -z

So now, just change the PHP script with what we've learned:
exec('bash -c "exec -a MyUniqueProcessName stress -c 1 -t 60s & cpulimit -e MyUniqueProcessName -l 30 -i -z"');

...or, simpler version:
exec('bash -c "stress -c 1 -t 60s & cpulimit -p \$! -l 30 -i -z"');

(Notice the $ in the $! had to be escaped with a backslash, \$!, because of the way it's quoted when passed to bash -c.)
Final Answer:
Based on the last example you amended to your question, you'll want something like this:
passthru('bash -c "sudo -u test stress -c 1 -t 60s & sudo -u root cpulimit -p \$! -l 30 -i -z"');

When I run this with php stackoverflow-question.php, it outputs the following:
stress: info: [3374] dispatching hogs: 1 cpu, 0 io, 0 vm, 0 hdd
stress: info: [3374] successful run completed in 60s
Process 3371 found

(The second two lines only appear after the PHP script finishes, so don't be mislead. Use top to check.)
Running top in another terminal during the 60 seconds the PHP script is running, I see:
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM     TIME+ COMMAND
 3472 test      20   0  7160   92    0 R 29.5  0.0   0:07.50 stress
 3470 root       9 -11  4236  712  580 S  9.0  0.0   0:02.28 cpulimit

This is exactly what you've described wanting: stress is running under the user test, and cpulimit is running under the user root (both of which you can change in the command, if desired). stress is limited to around 30%.
I'm not familiar with runuser and don't see the applicability, since sudo is the standard way to run a process as another user. To get this to work, you may have to adjust your settings in /etc/sudoers (which will require root access, but you obviously already have that). That's entirely outside the scope of this discussion, but as an example, I added the following rules:
my-user ALL=(test) NOPASSWD:NOEXEC: /home/my-user/development/stackoverflow/stress
my-user ALL=(root) NOPASSWD:NOEXEC: /home/my-user/development/stackoverflow/cpulimit


text:
Q: python curses: detect text's display width before printing it I'm using Python and curses to make a little text editor.
However, I'm having some trouble when trying to compute the width of a given text.
In particular, I've noticed that Chinese characters (e.g. 大) and emojis (e.g. ) on my terminal (the default Terminal app on MacOS) actually take twice the width of a typical ASCII printable character.
Given a string I intend to display using curses, is there some way I can determine how many columns a string will use up on the screen without actually displaying it?

A: You probably want wcwidth() and wcswidth(). They're not in the standard library (and not part of curses), but are available via pip install wcwidth.

A: You can create a window which you will not refresh (i.e., treating it as a hidden window), and obtain the y,x coordinates after printing into the hidden window.
It is unnecessary for the application to know how the curses library interprets the data (whether it uses wcwidth for example), but only necessary to be able to observe what curses would do with the information.
That approach is used in the lynx browser to decide if special treatment is needed for wrapping text (see source code).  Although that is written in C, the same idea can be used in the Python binding for curses.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как сделать мультиязычный лендинг? Подскажите, как реализовать мультиязычный лендинг?

A: Реализация на JS + HTML + CSS3
Если решили делать на JS + HTML + CSS3, то сделайте себе несколько лендингов под разные языки и переключайтесь между ними с помощью ссылок или JS.
Например, создаем три версии:
site.com - англоязычная версия,
site.com/ru/ - русскоязычная версия,
site.com/ch/ - китайская версия
И в шапке добавляйте блок переключения в виде флажков обычными ссылками на подпапки:
ru

Можно так же сделать select выпадающий список где при смене будет перенаправление на нужную версию.

<select onChange="document.location.href=this.options[this.selectedIndex].value;">
<option value="/">EN</option>
<option value="/ru/">RU</option>
<option value="/ch/">CH</option>
</select>

Реализация на PHP
Если хотите сделать на php, то можно занести весь текст в переменные (по 3 раза для каждого из языков соответственно), и в дальнейшем передавать актуальный язык через $_GET параметр.
Проверять его значение и выводить нужные языковые переменные.
Думаю в случае лендинга это пустая трата времени. Разумнее сделать с подпапками на HTML + JS + CSS.


text:
Q: Circuit for selecting between PCB antenna and external I'm just developing the second iteration of an 2.4Ghz sensor and receiver set. Because I can't afford the expensive development path of a big commercial project and because the environment these products get placed in is not constant or easy to stimulate, I'm trying to incorporate both an external antenna connector and a PCB antenna, with the option to select between the two.
To sum it up:

*

*Allow for switching between the PCB antenna and the external one. It's ok for this to be done by soldering/removing components.

*Have connectors (UFL) for both external antenna and VNA needed for antenna tuning.

Given the above, I was thinking of the following solution:

*

*Transmitter ->

*UFL with short stub for VNA ->

*PI matching network ->

*UFL connector for external antenna ->

*0 ohm resistor with two positions to select between PCB and external antenna

Does that sound like a good solution?

A: why the first UFL? that connector will bring in more inconsistencies than you'll fix by being able to measure at that point.
Also, I don't know your 2.4 GHz transmitter (IC, I guess), but that thing usually needs matching of its own.
So, in my world, this would look more like

*

*2.4 GHz interface of IC

*matching circuit for 50Ω transmission line impedance

*50 Ω microstrip line up to 0 Ω "selector"

*

*on one side of that, line, matching, and chip/PCB antenna

*on the other, line, and RF connector

In manufacturing, often having different population options comes at a cost. Check whether a simple RF switch IC isn't the better option financially at the quantity of boards you'll produce, overall, and control that through a GPIO and some firmware on a microcontroller you probably have in your system, anyways, for example.


text:
Q: Async for each loop node.js typescript I have tried to call a database operation from async for each loop. I have the following code
let succussCounter = 0;
let failureCounter = 0;

let mydata=[101,102,104,105];

myData.forEach(async data => {
          let response =
              await DbConnector.updateSampleTable(data);
          if(response){
            succussCounter ++;
          }else{
            failureCounter++;
          }
 });

      console.log('succussCounter = ' + succussCounter);
      console.log('failureCounter = ' + failureCounter);

I want to print the success count & failure count after completing the whole loop. But this always prints both are 0.

A: you need to learn a bit of await async.
forEach just isn't usable for your case because it is synchronous, it doesnt await anything. Therefore in your code console logs are run before the foreach has the time to run any query.
here is my favorite option : (it runs db queries sequentially)
for (let data of myData) {
          let response =
              await DbConnector.updateSampleTable(data);
          if(response){
            succussCounter ++;
          }else{
            failureCounter++;
          }
 }

console.log(...);

here is another option, it closer to your code but less readable in my opinion. But it has the advantage to run queries in parralel.
await Promises.all(myData.map(async data => {
          let response =
              await DbConnector.updateSampleTable(data);
          if(response){
            succussCounter ++;
          }else{
            failureCounter++;
          }
});
console.log(...);


text:
Q: AlarmManagerIntent doesn't get called I want to use the AlarmManager to call a BroadcastReciever:
Context ctx=getApplicationContext();
Intent StartIntent = new Intent(ctx, tartReceiver.class);

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC, StartTime.toMillis(false), PendingIntent.getActivity(ctx, 6,
                        StartIntent, PendingIntent.FLAG_CANCEL_CURRENT ));

The receiver is declared in the manifest like this:
<receiver android:process=":remote" android:name=".StartReceiver" android:exported="true"/>

But nothing ever happens. If I use ctx.sendBroadcast(StartIntent), the intend gets called, so it should be all right, or not?
I also checked the StartTime, it should be ok and I tried also 0 (which should cause the Intent to be called immediately according to the documentation).
What must I change to get it working?

A: JonathanK,
You want PendingIntent.getBroadcast() not PendingIntent.getActivity().


text:
Q: Android - Share custom link via facebook I need to share specific part in my app when user open it , if he download my app it navigate direct to this part (it may be nested fragment).
String AppURL = "https://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName();
String urlToShare = "http://stackoverflow.com/questions/7545254"; // I need custom url to specific part in my app

// See if official Facebook app is found
boolean facebookAppFound = false;
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
    if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana")) {
        intent.setPackage(info.activityInfo.packageName);
        facebookAppFound = true;
        break;
    }
}

// As fallback, launch sharer.php in a browser
if (!facebookAppFound) {
    String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
}else{

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_SUBJECT, "Foo bar"); // NB: has no effect!
intent.putExtra(Intent.EXTRA_TEXT, urlToShare);
}

startActivity(intent);

here is what I need to approach

A: In order to share the something in Facebook better go with latest Facebook SDK. It will make your task simpler. Because Android Intent has its own restrictions when we use share to facebook. Refer my answer below regarding this
Share text via Intent on Facebook without using Facebook sdk
The screenshot that you posted seems to have the sharing of link from the App.
Here is how you will integrate the Facebook SDK to your project.
Facebook SDK integration
Then use the following code to share link on the facebook.
ShareDialog shareDialog;
FacebookSdk.sdkInitialize(Activity.this);
shareDialog = new ShareDialog(act);
ShareLinkContent linkContent = new ShareLinkContent.Builder()
                    .setContentTitle("title")
                    .setContentDescription(
                            "Description")
                    .setContentUrl(Uri.parse("your url")).build();
            shareDialog.show(linkContent);

More sharing options from Facebook can be found here, which is pretty simple and straightforward.
Happy coding..!!

A: Try the following code:
File mFileImagePath = " /storage/emulated/0/Image Editor/Media/FilterImages/Image_Editor_1547816365839.jpg  ";  // Just example you use file URL

private void shareFacebook(File mFileImagePath) {
    String application = "com.facebook.katana";
    boolean installed = checkAppInstall(application);
    if (installed) {
        Intent mIntentShare = new Intent(Intent.ACTION_SEND);
        String mStrExtension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(mFileImagePath).toString());
        String mStrMimeType = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(mStrExtension);
        if (mStrExtension.equalsIgnoreCase("") || mStrMimeType == null) {
            // if there is no extension or there is no definite mimetype, still try to open the file
            mIntentShare.setType("text*//*");
        } else {
            mIntentShare.setType(mStrMimeType);
        }
        mIntentShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFileImagePath));
        mIntentShare.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        mIntentShare.setPackage(application);
        startActivity(mIntentShare);
    } else {

        Toast.makeText(mContext, "Facebook have not been installed.", Toast.LENGTH_SHORT).show();
    }

}

private boolean checkAppInstall(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
        //Error
    }
    return false;
}

This code works for me and will work on all Android devices.

A: As mentioned by @Ragu Swaninathan, you can use ShareLinkContent
from Facebook SDK.
Now to achieve the redirection to the specific screen of the app, you can use Firebase dynamic link
feature. You can generate dynamic links using Firebase SDK and then receive those links in the app to handle the navigation flow. You need to share these dynamic links along with the contents.


text:
Q: In Django, form submit is working but not able to parse user input User can able to submit the form without any issue, however user input data does not parse into database. Only predefined default data is parsing.
In my opinion, my model has an issue however I could not able to find because first time I am creating an object with ForeignKey and my knowledge on 'instance' part of the model is limited. Or I am too tired...
My models.py
class Ticket(models.Model):
    ticket_id = models.AutoField(primary_key=True, unique=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='ticketer')
    status = models.CharField(max_length=6, choices=STATUS_CHOICES, default='open', blank=True)
    subject = models.CharField(max_length=60, default='Ticket', blank=False)
    body = models.TextField(blank=False)
    priority = models.CharField(max_length=6, choices=PRIORITY_LEVEL, default='low', blank=False)
    display = models.BooleanField(default=True, blank=True)
    created_at = models.DateTimeField(auto_now=True, blank=True)
    closed_at = models.DateTimeField(blank=True, null=True)
    handler = models.CharField(max_length=14, default='MT', blank=True)
    response = models.TextField(blank=True, default='We are working on your ticket!')

    def save(self, *args, **kwargs):
        super(Ticket, self).save(*args, **kwargs)

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_or_update_ticket(sender, instance, created, **kwargs):
    Ticket.objects.create(user=instance)

My views.py
@login_required
@transaction.atomic
def add_ticket_view(request, username):
    if request.method == 'POST':
        add_ticket_form = AddTicketForm(request.POST, instance=request.user)
        if add_ticket_form.is_valid():
            add_ticket_form.save()
            messages.success(request, ('Your ticket was successfully submitted!'))
            return redirect('..')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        add_ticket_form = AddTicketForm(instance=request.user)
        context = {
        'add_ticket_form': add_ticket_form,
        }
    return render(request, 'pages/user-ticket-add.html', {
        'add_ticket_form': add_ticket_form
    })

My forms.py
class AddTicketForm(forms.ModelForm):

    class Meta:
        model = Ticket
        fields = ('priority', 'subject', 'body',)

My urls.py
urlpatterns = [
    path("", view=dashboard_view, name="dashboard"),
    url(r'^(?P<username>[\w.@+-]+)/profile/$', views.get_user_profile),
    url(r'^(?P<username>[\w.@+-]+)/profile/edit/$', views.edit_profile_view),
    url(r'^(?P<username>[\w.@+-]+)/tickets/$', views.user_ticket_view),
    url(r'^(?P<username>[\w.@+-]+)/tickets/add/$', views.add_ticket_view, name='add_ticket_view'),
]

My add-ticket.html:
                    <form method="POST" class="add-ticket-form" enctype="multipart/form-data">
                    {% csrf_token %}
                    {{ add_ticket_form|crispy }}
                    <div class="text-right mt-3">
                    <button type="submit" class="save btn btn-success btn waves-effect mb-1 waves-light">Submit</button>
                    </div>
                    </form>

Thank you all for your help guys.
UPDATE - SOLUTION:
If anyone come to this question, I was not passing the form as data, I was passing it with a related user. However this is not OneToOne relation, USER is a ForeignKey here.
my views.py now and working:
@login_required
@transaction.atomic
def add_ticket_view(request, username):
    if request.method == 'POST':
        add_ticket_form = AddTicketForm(request.POST, request.FILES)
        if add_ticket_form.is_valid():
            data = add_ticket_form.save(commit=False)
            data.user = request.user
            data.save()
            messages.success(request, ('Your ticket was successfully submitted!'))
            return redirect('dashboard:user_ticket', username)
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        add_ticket_form = AddTicketForm(instance=request.user)
        context = {
        'add_ticket_form': add_ticket_form,
        }
    return render(request, 'pages/user-ticket-add.html', {
        'add_ticket_form': add_ticket_form
    })


text:
Q: How to create custom testcase settings in Robot Framework I want to create a custom settings (OR Attribute) (say TEST_ID) in Robot Framework to tag them with test id.
During teardown I will use that settings to update my test management tool to record the execution result.
*** Test Cases ***
Test With Settings
    [Documentation]    Another dummy test
    [Tags]    dummy    owner-johndoe
    [TEST_ID] XXX
    Log    Hello, world!

A: There is no need to create a new attribute. You can use tags.
You could tag your tests with something like ALMID:5432. In the teardown, the tags are available via the builtin variable @{TEST_TAGS}. The list could be searched and the id extracted from the tag.


text:
Q: Why is Echo statement in SQL query not writing in text file? Following code is used for writing a number in the text file but instead it is writing "Echo is ON" into the text file.
SET @CMD = 'ECHO '+@Ver+'>'+@Vercheck
Print @CMD

EXEC xp_cmdshell @CMD, NO_OUTPUT

Print @CMD gives ECHO 1>C:\Pharmsuite\Vercheck.txt
Here instead of 1 the query is writing Echo is ON in the text file. What am I doing wrong?


text:
Q: concatenate innerhtml of div into string variable i tried to concatenate innerhtml of div into string variable:
games variable:

$games = '';

DOMinnerHTML function:
function DOMinnerHTML($element)
{
    $innerHTML = "";
    $children = $element->childNodes;
    foreach ($children as $child)
    {
        $tmp_dom = new DOMDocument();
        $tmp_dom->appendChild($tmp_dom->importNode($child, true));
        $innerHTML.=trim($tmp_dom->saveHTML());
    }
    return $innerHTML;
}

ExtractFromType function:
function ExtractFromType($type)
{
$html = file_get_contents('www.site.com/' .$type);
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
if (strpos($div->getAttribute('style'),'MyString') !== false) {

//////
$games = $games.DOMinnerHTML($div);
//////

}
}
}

code:

ExtractFromType('MyType');
echo $games; // = Nothing.

this code return nothing.

A: $games is defined in the global scope, and it's not available inside ExctractFromType. Define it inside the function, then return the value:
function ExtractFromType($type) {
  $html = file_get_contents('www.site.com/' .$type);
  $dom = new domDocument;
  @$dom->loadHTML($html);
  $dom->preserveWhiteSpace = false;
  $divs = $dom->getElementsByTagName('div');

  $games = '';
  foreach ($divs as $div) {
    if (strpos($div->getAttribute('style'),'MyString') !== false) {
      $games = $games.DOMinnerHTML($div);
    }
  }
}

echo ExtractFromType('MyType');


text:
Q: Javascript Promise resolve confusion private runMiddlewares(route: Route | ExceptionRoute, request: HttpRequest, response: HttpResponse): Promise<any> {
    return new Promise((resolve, reject) => {
        try {
            route.middlewares.forEach(async (middleware: IMiddleware) => {
                console.log('begin run middleware');
                await middleware.process(request, response);
                console.log('resolve run middleware');
                console.log(request.body);
            });
            console.log('resolve all runMiddlewares');
            resolve();
        } catch (e) {
            reject(e);
        }
    });
}

I have written this function runMiddlewares which should ideally resolve() when all the middleware.process() have resolved. I am using typescript await functionality but it doesn't seem to be working.
I expect something like this to happen inside route.middlewares.forEach(

*

*'begin run middleware'

*then awaits resolves

*'resolve run middleware'

This continues for all of the middlewares in forEach loop and when the list is all done then and only then 'resolve all runMiddlewares' should be printed and finally, private runMiddlewares( ... ) should resolve.
But instead, forEach is now getting immediately resolved thus preventing all of the middlewares to even complete.
How should this be handled? I thought that await will take care of it inside the forEach loop and only then resolve of runMiddlewares will be called in the end.
What am I missing here?

A: You can use map to create an array of promises from your middlewares. This array of promises can ben handed to Promise.all which resolves when every single promise of the array has been resolved.
await Promise.all(route.middlewares.map((middleware: IMiddleware) => {
            console.log('begin run middleware');
            const promise = middleware.process(request, response);
            console.log('resolve run middleware');
            console.log(request.body);
            return promise
        });

Or even more compact:
runMiddlewares(...) {
  return Promise.all(
    route.middlewares.map((middleware: IMiddleware) => {
      return middleware.process(request, response))
    })
  )
}

A: So, following the recommendation ( https://cn.eslint.org/docs/3.0.0/rules/no-await-in-loop ), I wrote it as follows
private runMiddlewares(route: Route | ExceptionRoute, request: HttpRequest, response: HttpResponse): Promise<any> {
    return new Promise(async (resolve, reject) => {
        try {
            const middlewarePromiseArry: any[] = [];
            route.middlewares.forEach((middleware: IMiddleware) => {
                console.log('begin run middleware');
                middlewarePromiseArry.push(middleware.process(request, response));
                // removed the use of await inside of forEach loop following this link: https://cn.eslint.org/docs/3.0.0/rules/no-await-in-loop
                // await middleware.process(request, response);
                // console.log('resolve run middleware');
                // console.log(request.body);
            });

            await Promise.all(middlewarePromiseArry);
            console.log('resolve all runMiddlewares');
            resolve();
        } catch (e) {
            reject(e);
        }
    });
}

I am happy to accept further answers and recommendations/improvements :)


text:
Q: How to export file after use XSLT to transfer to data? I tried to export. But it's not working?
I checked https://firebearstudio.com/blog/magento-2-import-xslt-transformation-how-to-import-any-xml-to-magento-2.html but not succeded.


text:
Q: Render Monaco editor in a separate Window I am developing an application that needs a code editor in a separate window. I want to use monaco editor for this but the editor seems not to work when rendering it in a new window.
Here is a codesandbox with a minimal reproduction example: https://codesandbox.io/s/objective-stonebraker-rvleh
If you open the devtools in the new window you can see that the editor markdown gets rendered but it is not visible. I would expect to see the editor also in the new window. Does anyone know why it is not visible?


text:
Q: Success with AJAX Status code < 400? Basically it boils down to, is there any case where it would be bad for me to call the success callback function on status codes under 400?
In looking at the list of status codes for HTTP, I don't think there would be but I want to make sure. I don't think I'll be getting 1XX level codes as they look like most of them return before the full request is processed and readyState === 4 (I don't care about IE 7's 122). And I want to still return success on a 302 and 304 status codes. So is status < 400 an acceptable way to catch all of this?

A: A 301 means the client is responsible for making the HTTP call again with the new URL. Does your library or toolkit already handle this for you?

A: Building on @sarnold's concerns, it looks like the XMLHttpRequest specifications say the following:

If the response is an HTTP redirect (status code 301, 302, 303 or
  307), then it MUST be transparently followed (unless it violates
  security or infinite loop precautions). Any other error (including a
  401) MUST cause the object to use that error page as the response.

Which seems to indicate to me that either 2XX or 3XX responses are valid. So, in short, my findings indicate status < 400 is an appropriate status response check.


text:
Q: How to add ImplicitlyAnimatedReorderableList (Reordareble ) in ExpansionPanelList? I'm Using  ImplicitlyAnimatedReorderableList (implicitly_animated_reorderable_list: ^0.2.3) : https://pub.dev/packages/implicitly_animated_reorderable_list
Facing issue :

════════ Exception caught by rendering library ═════════════════════════════════════════════════════
The following assertion was thrown during performResize():
Vertical viewport was given unbounded height.

Viewports expand in the scrolling direction to fill their container. In this case, a vertical viewport was given an unlimited amount of vertical space in which to expand. This situation typically happens when a scrollable widget is nested inside another scrollable widget.

If this widget is always nested in a scrollable widget there is no need to use a viewport because there will always be enough vertical space for the children. In this case, consider using a Column instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size the height of the viewport to the sum of the heights of its children.
════════ Exception caught by rendering library ═════════════════════════════════════════════════════
RenderBox was not laid out: RenderViewport#ea59f NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1713 pos 12: 'hasSize'


text:
Q: Using jQuery, how do I add a class to elements that have an href that has part of the path of the active element's href? I would like the "Quick", "Brown", and "Fox" links to have the "dropdown" class, but not for the "Foo" or "Bar" links. How can I achieve this using jQuery?
HTML Code:

         Foo

         Bar

         Quick

         Brown

         Fox

A: You can edit the element attribute as href with .attr('href,'link') which will let you edit and also you can get the current active by adding the ul reference to a var or directly and after search all the $('.is-active') inside and there you'll have the active value or element name. I hope this has helped you
If i missunderstood something, let me know

A: Get the href of the active element
const activeHref = $('.is-active').attr('href')

Then find all elements with an href, filter it by the above value and add the class
$('[href]').filter(function() {
  return activeHref.indexOf(this.getAttribute('href')) !== -1
}).addClass('whatever')

const activeHref = $('.is-active').attr('href')
$('[href]').filter(function() {
  return activeHref.indexOf(this.getAttribute('href')) !== -1
}).addClass('whatever')
.is-active { font-weight: bold; }
.whatever { color: green; }

       Foo

       Bar

       Quick

       Brown

       Fox

A: Here you go with a solution https://jsfiddle.net/3t9yy4ou/

var activeHref = $('.is-active').attr('href');
$('a[href]').each(function(){
  if( activeHref.indexOf($(this).attr('href')) >= 0){
    $(this).addClass('dropdown');
  }
});
.dropdown {
  background: rgba(0,0,0,0.4);
}

       Foo

       Bar

       Quick

       Brown

       Fox

I've used jQuery .each method.


text:
Q: Should a "configure" script be distributed if configure.ac is available? Currently, our installation instructions are:
autoreconf -fi
./configure
...

The autoreconf step generates the configure file from configure.ac and Makefile.in from Makefile.in. If one of the dependencies (say pkg-config) is not installed, both configure and autoreconf fail although the latter prints a cryptic error message.
When releasing source tarballs, should the configure script be supplied in the package or not? What other files need to be included if it has to be distributed? The directories build-aux and autom4te.cache and files aclocal.m4 were also created.

A: In an SCM repository, nothing autogenerated should be present (including configure — but developer opinions digress here). A tarball should contain the state after autoreconf -fi and/or autogen.sh (or whichever name you chose for it). Third, you could also use make dist, though it requires that all files that shall appear in the tarball are also listed in the Makefiles.

A: Your installation instructions are horribly broken.  The user should not need to have the autotool chain installed to build your software.  You must distribute the configure script in your tarball.  Note that you should not include the configure script in your version control system.  (You should not use your version control system as a distribution system.)

A: The configure script should be built by the maintainer and distributed in the tarball. End users should never have to touch it, and it is a good idea to ensure this via AM_MAINTAINER_MODE if you are using automake. If not, make sure your Makefile.in doesn't re-generate configure when running for end users.
Let automake generate a distribution for you if you want to know what else belongs there. The auxiliary directory build-aux and aclocal.m4 do, automat4e.cache doesn't.


text:
Q: QProcess to extract file using 7zip as subprocess I have a use case in an application using C++ and Qt (on windows 10). The application uses 7zip.exe as a subprocess to uncompress the files in a selected folder. I need to use QProcess to extract files.
The code I came up with is as shown below.
     MainWindow.h
QStringList zipFiles;

MainWindow.cpp
void MainWindow::on_browseButton_clicked()
{
        directory = QFileDialog::getExistingDirectory(this);
        if(recursiveOperation){
            QDirIterator it(directory.canonicalPath(), QStringList() << "*.zip" <<  "*.7z", QDir::Files, QDirIterator::Subdirectories);
             ui->outputLogResultList->addItem("File selected to uncompress");
             ui->outputLogResultList->addItem("-----------------------------");
            while (it.hasNext()){
                QString file = it.next();
                ui->outputLogResultList->addItem(file);
                zipFilesWithRecursion.append(file);
            }

        }else{
            zipFilesWithoutRecursion = directory.entryList(QStringList() << "*.zip"<< "*.7z", QDir::Files);
            qDebug() << zipFilesWithoutRecursion;

            foreach(QString filename4, zipFilesWithoutRecursion) {
                     qDebug() << "inside loop";
                    zipFilesWithCompletePath.append( QString(directory.canonicalPath()+"/%1").arg(filename4));
                }

                qDebug() << "without recursion";
                qDebug() << zipFilesWithCompletePath;
        }
}

void MainWindow::unZipFile()
{
    int numberOfFiles;
    if(recursiveOperation){
        numberOfFiles = zipFilesWithRecursion.size();
        foreach(QString filename3, zipFilesWithRecursion) {
            QStringList queryArguments;
            queryArguments << "x";
                  qDebug() << filename3;
                  queryArguments <<""""+ filename3+ """";
                  queryArguments << "-o"+directory.canonicalPath()+"/output"+QString().setNum(numberOfFiles);
                  qDebug() << queryArguments;
                  unZip.setWorkingDirectory(QCoreApplication::applicationDirPath());
                  unZip.start("7za.exe", queryArguments);
                  numberOfFiles--;
              }
        numberOfFiles = 0;
    }else{
        numberOfFiles = zipFilesWithCompletePath.size();
        foreach(QString filename3, zipFilesWithCompletePath) {
            QStringList queryArguments;
            queryArguments << "x";
                  qDebug() << filename3;
                  queryArguments <<""""+ filename3+ """";
                  queryArguments << "-o"+directory.canonicalPath()+"/output"+QString().setNum(numberOfFiles);
                  qDebug() << queryArguments;
                  unZip.setWorkingDirectory(QCoreApplication::applicationDirPath());
                  unZip.start("7za.exe", queryArguments);
                  numberOfFiles--;
              }
        numberOfFiles = 0;
    }

}

The code run correctly, but after processing the first file, it does not process any other files and displays the state saying "QProcess::start: Process is already running"
The output segment is as follows.
Warning: QT_DEVICE_PIXEL_RATIO is deprecated. Instead use:
   QT_AUTO_SCREEN_SCALE_FACTOR to enable platform plugin controlled per-screen factors.
   QT_SCREEN_SCALE_FACTORS to set per-screen DPI.
   QT_SCALE_FACTOR to set the application global scale factor.
("SemiFinal.zip", "temata_vskp_-_podklady_pro_zadani_vskp(10).zip")
inside loop
inside loop
without recursion
("F:/taskPractiseDirectoryForQt/SemiFinal.zip", "F:/taskPractiseDirectoryForQt/temata_vskp_-_podklady_pro_zadani_vskp(10).zip")
"F:/taskPractiseDirectoryForQt/SemiFinal.zip"
("x", "F:/taskPractiseDirectoryForQt/SemiFinal.zip", "-oF:/taskPractiseDirectoryForQt/output2")
"F:/taskPractiseDirectoryForQt/temata_vskp_-_podklady_pro_zadani_vskp(10).zip"
("x", "F:/taskPractiseDirectoryForQt/temata_vskp_-_podklady_pro_zadani_vskp(10).zip", "-oF:/taskPractiseDirectoryForQt/output1")
QProcess::start: Process is already running

The folder has 2 .zip files, My question is why second file is not getting processed.

A: You have to wait for your QProcess (unZip) to finish, before processing next file or create QProcess instances per file in cycles foreach(QString filename3, zipFilesWithCompletePath) in void MainWindow::unZipFile() method to process them concurrently.
If you try to wait unZip.waitForFinished(), your application would be unresponsive for that time as it's main thread would be suspened till process finished.
If you want to process files concurrently, QProcess instances should be created in heap, e.g. auto unZipFileProcess = new QProcess(this); and you'll need to write some code to control started processes and wait them all for finish before you close your application, because in that case all processes would be interrupted and killed by their decstructors. To control process state it's proper to connect to QProcess instance signals - errorOccurred and finished. Also these signals should be connected to QProcess' deleteLater slot to avoid memory growth. At this moment you would not need your unZip static or member variable (i don't know how it is declared) at all.
In another way, if you do not need to track files processing (wait for finished, report process errors and so on), you can to start processes as detached with static QProcess::startDetached method and not create any QProcess instance at all. So you would not need to control them and synchronize them with your application lifetime.
And you defenetly need to redesign your MainWindow::unZipFile() method to avoid code repetitions.

A: As @Alexey suggested I used
unZip.waitForFinished(3000);

before the end of loop and it worked for me.


text:
Q: Presenting a NIB Modally Crashes on iOS 8 but not on iOS 9+ I have created a NIB which has a name of SomeViewController and all the corresponding code are correct and all the views are bound correctly, but somehow the code self.presentViewController(SomeViewController(), animated: true, completion: nil) causes a crash:

fatal error: unexpectedly found nil while unwrapping an Optional value

What is the problem?

A: To fix this we need to version check by doing this
    if #available(iOS 8, *) {
        self.presentViewController(SomeViewController(nibName: "SomeViewController", bundle: nil), animated: true, completion: nil)
    } else {
        self.presentViewController(SomeViewController(), animated: true, completion: nil)
    }

or just
self.presentViewController(SomeViewController(nibName: "SomeViewController", bundle: nil), animated: true, completion: nil)

for some reason iOS 8's not automated on including the nibName on initialization with it's corresponding class.
Update:
Can also be fixed by doing this
class SomeViewController: UIViewController {
    init() {
        super.init(nibName: "SomeViewController'sNibNameHere", bundle: nil)
    }
}

// on some other part of your code
self.presentViewController(SomeViewController(), animated: true, completion: nil)


text:
Q: Converting from pascal to Delphi XE2 I am converting a Pascal program to Delphi using CRT32. There is one command, mem, that is not recognized in Delphi. I use it to save screen memory on a stack in order to save all or part of a window so that I can restore it after deleting a window that was put on top of the original window. Any ideas?
BTW, I have added a new procedure to CRT32 to supplement ReadKey because the ReadKey function does not read function keys.  I can share if anybody is interested.

A: mem is a function in Turbo Pascal for accessing 16 bit DOS memory. In your case it is used for direct access of the console text part in the memory located at a certain address.
Since this is not possible (does not exist) in windows, there has to be a function in your library that records everyting written onto the the console, for later retrieval, or using ways to access the windows console by other means.
You might get some inspiration from this library, Crt replacement for Delphi (fully functional) 1.20.


text:
Q: Dynamically creating a javascript/jQuery object to use in the $.css() method Question:
I'm creating a javascript object to hold css attributes. If I add new variables to the object on the fly, I run into an unknown problem with the jQuery .css() method and nothing happens. However, if I initiate the object with the variables I want to/do change, the .css() method works fine.
In reference to a post I found, is it necessary that I preset the variables of the object, or is there a way to improve my code to be more dynamic?
(If I can find a way to add variables on the fly I would be able to set any css attribute, not just the ones I predetermine.)

Extended Explanation:
I'm trying to change the padding and margin values on the fly in my HTML.
I have created a function that works based on a similar question. However if I simply create an empty object,
var cssObject = {};

instead of,
var cssObject = {
            padding : "inherit",
            paddingBottom : "inherit",
            paddingLeft : "inherit",
            paddingRight : "inherit",
            paddingTop : "inherit",
            margin : "inherit",
            marginBottom : "inherit",
            marginLeft : "inherit",
            marginRight : "inherit",
            marginTop : "inherit"
          };

When I add each new css attribute to the cssObject, the $.css() method doesn't do anything.
i.e.

    for(...){
      cssObject[cssName] = cssValue;
    };

    // The cssObject has (for loop).length many attributes.
    // Set new css with cssObject

    $(this).css(cssObject);

The cssObject gets created (as viewed in the source code and console logs) but the css of $(this) doesn't change. Adversely, When I create the cssObject with preset variables using all the same code, it executes fine.
Steps of the function:

*

*Loop through each HTML objects (i.e. div, etc.) with a class name(s) that contains "setspacing".

*The class names of the current object are split into an array.

*Loop through the class names, and stop if the name contains "setspacing".

*The parts of the current class name are split into an array.

*Use class name parts to add new attributes to the css object.

Sample HTML Code:

Bleep Blorp!

jQuery Code:
$("[class*='setspacing']").each(function(){
    var classList = $(this).attr('class').split(" ");

    for (var i = classList.length - 1; i >= 0; i--) {
      if (classList[i].indexOf("setspacing") >= 0) {
        var splitName = classList[i].split("-");

        var cssName=null, cssValue=null;
        var cssObject = {}; /*
            padding : "inherit",
            paddingBottom : "inherit",
            paddingLeft : "inherit",
            paddingRight : "inherit",
            paddingTop : "inherit",
            margin : "inherit",
            marginBottom : "inherit",
            marginLeft : "inherit",
            marginRight : "inherit",
            marginTop : "inherit"
          };*/

        for (var j = 2; j < splitName.length-1; j++) {

          if (splitName.length<=3) {
            cssName = splitName[1];
          } else {
            part = splitName[j].substring(0,1).toUpperCase() + splitName[j].substring(1);
            cssName = splitName[1]+part;
          };

          cssValue = splitName[splitName.length-1]+" !important";
          cssObject[cssName] = cssValue;
        };
        console.log(JSON.stringify(cssObject)); // EDIT : Added after comment
        $(this).css(cssObject);
      };
    };
  });

Console output when empty object is used:
[Log] {"marginTop":"0px !important","marginBottom":"0px !important","marginRight":"0px !important","marginLeft":"0px !important"} (setup.js, line 50)
[Log] {"paddingTop":"0px !important","paddingBottom":"0px !important","paddingRight":"0px !important","paddingLeft":"0px !important"} (setup.js, line 50)
[Log] {"marginTop":"0 !important","marginBottom":"0 !important","marginRight":"0 !important","marginLeft":"0 !important"} (setup.js, line 50)
[Log] {"paddingTop":"0 !important","paddingBottom":"0 !important","paddingRight":"0 !important","paddingLeft":"0 !important"} (setup.js, line 50)

A: As Wolf said in his comments and according to this SO question, jQuery css() method doesn't support !important, if you try to remove !important part then it will works, here is a JSFiddle to test.
Also the inner for loop var j = 1; j < splitName.length-1; is starting from the 3rd item, so in case of setspacing-padding-30px it will not iterate since the condition j < splitName.length-1; is false.
$("[class*='setspacing']").each(function(){
    var classList = $(this).attr('class').split(" ");

    for (var i = classList.length - 1; i >= 0; i--) {
      if (classList[i].indexOf("setspacing") >= 0) {
        var splitName = classList[i].split("-");

        var cssName=null, cssValue=null;
        var cssObject = {}; /*
            padding : "inherit",
            paddingBottom : "inherit",
            paddingLeft : "inherit",
            paddingRight : "inherit",
            paddingTop : "inherit",
            margin : "inherit",
            marginBottom : "inherit",
            marginLeft : "inherit",
            marginRight : "inherit",
            marginTop : "inherit"
          };*/

        for (var j = 1; j < splitName.length-1; j++) {// start from 2nd item

          if (splitName.length<=3) {
            cssName = splitName[1];
          } else {
            if(j==1) continue; // if it is the 2nd skip..
            part = splitName[j].substring(0,1).toUpperCase() + splitName[j].substring(1);
            cssName = splitName[1]+part;
          };

          cssValue = splitName[splitName.length-1];// remove !imprtant since it is not supported +" !important";
          cssObject[cssName] = cssValue;
        };
        console.log(JSON.stringify(cssObject)); // EDIT : Added after comment
        $(this).css(cssObject);
      };
    };
});

A: I don't know if you are able to modify your code much, but I came up with this much simpler alternative. It uses data attributes instead of classes so you don't have to go about splitting class names.
It is as follows:
http://jsfiddle.net/yn7tB/1/
HTML:

Bleep Blorp!

Javascript:
$(".setspacing").each(function(){
    var attrib = $(this).data();
    var el = $(this);

    $.each(attrib, function (i, e) {
        el.css(i,e);
    });
});


text:
Q: Send Form Content to Endpoint in Different App Django Say I have an app called App1 - inside of which there is a template that has a form with name and email.
Now, say I have an app called App2 - that has an endpoint which takes in a name and email and sends an email to that email.
Now, I want to combine the two, so that I can make the form contents go to the endpoint in App2 on submit, thus sending an email to the email in the form.
How would I do this? Would it be better to just put them in the same app? When would someone use 2 apps over 1?
Does this make sense? Thanks for your help!


text:
Q: Returning all field from Datatable to AJAX My problem is, it doesn't display table from c# after I input text and click search button. I have tried many ways, but it can't work. Below is my code.
Below is my javascript:
url: "/Testing/TraceReport/traceReport.aspx/app",
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
    var xmlDoc = $.parseXML(response.d);
    var xml = $(xmlDoc);
    var EquipmentList = xml.find("Table1");
    var content = "";
    if (EquipmentList.length > 0) {
        $(EquipmentList).each(function () {
            content += "
";

            if ($(this).find('Column1').text() == "") { content += "UNKNOWN	"; }
            else { content += "" + $(this).find('Column1').text() + "	"; }

            if ($(this).find('Column2').text() == "") { content += "UNKNOWN	"; }
            else { content += "" + $(this).find('Column2').text() + "	"; }

            if ($(this).find('Column3').text() == "") { content += "UNKNOWN	"; }
            else { content += "" + $(this).find('Column3').text() + "	"; }

            if ($(this).find('Column4').text() == "") { content += "UNKNOWN	"; }
            else { content += "" + $(this).find('Column4').text() + "	"; }

            if ($(this).find('Column5').text() == "") { content += "UNKNOWN	"; }
            else { content += "" + $(this).find('Column5').text() + "	"; }

            if ($(this).find('Column7').text() == "") { content += "UNKNOWN	"; }
            else { content += "" + $(this).find('Column7').text() + "	"; }

            content += "
";
        });
    }

Below is my c#:
DataTable table = new DataTable();
table = ConvertListToDataTable(list);
DataSet ds = new DataSet();
ds.Tables.Add(table);

return ds.GetXml();

A: The dataType property tells the server what type of data to return.
You're telling the server you want to receive json.  Yet, it looks like the server is sending xml.  Update the dataType in the ajax method:
...
dataType: 'xml',
...

A: Well as far as I understand, You are returning the DataTable object itself from your WebMethod and you want to read all the returned rows from the column.
Here is my suggestion to do it, Make a model and copy your values from the DataTable to a C# class object Generic List. Below is the idea:
// Sample Class
public class MyData
{
    public string Column1 {get; set;}
    public string Column2 {get; set;}
    public string Column3 {get; set;}
    public string Column4 {get; set;}
    // ... and so on
}

Then in your WebMethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]  // To Force the service method to return JSON only
public static List<MyData> DoStuff()
{
    DataTable table = FetchMyTable(); // method that gets your data from SQL
    List<MyData> data = new List<MyData>();
    foreach(DataRow row in table.Rows)
    {
        MyData dataItem = new MyData
        {
            Column1 = row["Column1"].ToString(),
            Column2 = row["Column2"].ToString(),
            // And So on...
        };
        data.Add(dataItem);
    }
    return data;
}

Then in your ajax call:
$.ajax({
// your other parameters
contentType: 'application/json; charset=utf-8;',
accept: 'application/json; charset=utf-8;',
dataType: 'json',
success: function(response){
        // Now from here you can loop through it
        for(var i = 0; i < response.length; i++){
            var column1 = response[i].Column1;
            var column2 = response[i].Column2;
            // and so on....
        }
    }
});

This is a rough idea how to achieve the task you are doing. Hope it helps.
PS: I didn't used any compiler so the code is not tested, it may need some love.


text:
Q: javascript closure ,who can help me to understand why var functions = [];
(function foo() {

    for (var i=0; i<5; i++ ) {
        var f = function() {
            console.log(i);
        }
        functions.push(f);
    }

    for (var i=0; i<5; i++ ) {
        f = new Function("console.log(i);");
        functions.push(f);
    }

})();

for (var i=0; i<10; i++ ) {
    functions[i]();
}

the output is :
5
5
5
5
5
5
6
7
8
9
can anybody help me sort out the flow?

A: first of all you should know whenever you want to run this function:
Function("console.log(i);");

this would use the current context's i variable as its value. so you might want to do:
var functions = [];
(function foo() {

    for (var i = 0; i < 5; i++) {
        var f = function func() {
            console.log(func._i);
        };
        f._i = i;
        functions.push(f);
    }

    for (var i = 0; i < 5; i++) {
        f = new Function("console.log(" + i + ");");
        functions.push(f);
    }

})();

for (var i = 0; i < 10; i++) {
    functions[i]();
}

I changed it this way and my result is:
0, 1, 2, 3, 4, 5, 6, 7 ,8, 9

Why is that?
1- all of the functions in your first for loop use a single variable i, and as its last value is 5 then all would print 5.
2- the other ones which get created in your second for loop, whenever they get invoked they would use the i variable in their current context, and as far as they get invoked in your last for loop, they use the i variable in the loop, to make it clear. you can easily change your last for loop like this:
for (var j = 0; j < 10; j++) {
    functions[j]();
}

and as there is no i variable in the context (I changed it to j), then your output would be:
5 5 5 5 5 undefined undefined undefined undefined undefined

undefined is there because function can not fin any i variable in the context.

A: It's actually printing out five 5's and then 5, 6, 7, 8, 9. The first five 5's are from var i in that for loop, the functions save a reference to that var i and access it when you run it, and since it equals 5 at the end of the for loop, they all return 5. The second set of numbers comes from the quoted function accessing i from the for loop there, ergo it printing out 5, 6, 7, 8, 9.
Lots of good answers here:
How do JavaScript closures work?

A: The first 'for' loop is generating 5 functions each of them creates a closure which captures the 'i' as 5 (last value of 5 for that loop after last increment) so they all render out 5 (it just shows in Chrome as the first 5 with 5 in a circle next to it meaning the same value was logged out 5 times)
The second 'for' loop generates functions that will use 'i' from the scope it executes from, in this case the scope is the 3rd 'for' loop...

A: Closure allow you to access the variable from parent scope, which sometime cause strange or wrong behavior, here in this scenario closure is causing the output: 5 5 5 5 5 0 1 2 3 4
I am trying this code with:
f = new Function("alert("+i+");");

In first loop:
 for (var i = 0; i < 5; i++) {
    var f = function func() {
        console.log(func._i);
    };
    f._i = i;
    functions.push(f);
 }

you are referencing i of parent means loop variable, so five different functions are created all with the same copy of variable i, which is changing with iteration, at the end of loop where condition break is i=5 since all functions are referencing the same copy, so change to original copy will effect all. So each function now has the i=5
Now in second loop, you are appending it as a string, which doesn't refer to original copy but creating a new string for each iteration:
for (var i = 0; i < 5; i++) {
  f = new Function("console.log("+i+");");
  functions.push(f);
}

this create five different functions with each different string:
console.log("0");
console.log("1");
console.log("2");
console.log("3");
console.log("4");

Now calling each function created by loop1 functions[0] to functions[4] is referring the same copy of i will print 5 while second functions[5]to end has there own strings to print.


text:
Q: PyQt, when button is pressed to connect to a method of different class, code never exits __init__ I'm currently implementing a model view architecture for my PyQt GUI. Here's a simpler, but representative version of my code at the moment.
class Model(QtGui.QWidget):
    def __init__(self):
        super(Model, self).__init__()
        self.openDir = '/some/file/dir/'
    def openFile(self):
        openFileName = QtGui.QFileDialog.getOpenFileName(None, "Open File",self.openDir,"AllFiles(*.*)")
        openFile = open(openFileName, 'r')
        ...

class View(QtGui.QWidget):
    def__init__(self):
    super(View, self).__init__()
    ...
    self.button = QtGui.QPushButton("Open")
    ...
    self.button.clicked.connect(Model().openFile)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    mainWindow = View()
    mainWindow.show()
    sys.exit(app.exec_())

So when I click the "open" button, I want to call the Model class' openFile method, but when I do click it, it goes into the Model.__init__ but it never actually goes into the openFile method. What do I have to fix?

Edit1: Fixed all mistakes.

Edit2: For those facing similar issues, here is the solution that Fred S provided and the fixed code.
class Model(QtGui.QWidget):
    def __init__(self):
        super(Model, self).__init__()
        self.openDir = '/some/file/dir/'
    def openFile(self):
        openFileName = QtGui.QFileDialog.getOpenFileName(None, "Open File",self.openDir,"AllFiles(*.*)")
        openFile = open(openFileName, 'r')
        ...

class View(QtGui.QWidget):
    def__init__(self):
    super(View, self).__init__()
    ...
    self.button = QtGui.QPushButton("Open")
    ...
    self.model = Model()
    self.button.clicked.connect(self.model.openFile)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    mainWindow = View()
    mainWindow.show()
    sys.exit(app.exec_())

A: Well, I don't have PyQt4 on my machine, but I have PySide.  Here's what I see when I run the code:
1) super(Model, self).__init__(parent) crashes.   "parent" is not defined.
2) open = open(openFileName, 'r') is very bad.  You're redefining a built-in.
3) self.loadDir doesn't seem to exist.
4) But as to your question, if I change
self.button.clicked.connect(Model().openFile)

to be:
self.model = Model()
self.button.clicked.connect(self.model.openFile)

Then the problem seems fixed.  But this is in PySide, so possibly not in PyQt4.  Good luck.


text:
Q: Filter Cursor type NSPredicate I need to use NSPredicate on Android, I'll explain why:
I am creating a lot of statistics on data and then do a read-only database of all the data, which gives me a Cursor.
Then I have to filter out many times these data based on different filters, but do not want to do a select query each time, then I would do the operation directly or by cursor or from an array.
What do you advise me to do?

A: I'm not exactly sure the problem you are solving. Would Apache Commons Collections be helpful?
e.g. filter a list with Predicate?
http://commons.apache.org/proper/commons-collections/javadocs/api-release/index.html


text:
Q: Finding all latlong inside a circle in google map Lets assume i have center point LatLong saved in database and a given radius of 20 meters. and all the other LatLong near to this center place but not necessarily inside 20 meters of the center. Is there a way i can find all the latlongs inside 20 meters of radius from the center without rending a map. just using some api or mathematical formula?

A: You can iterate the markers in a loop and subsequently use the API function
computeDistanceBetween()

This will provide you the shortest distance which in Google API is called geodesic.
You can also use the function
computeLength()

A: You can use the Haversine formula
https://en.wikipedia.org/wiki/Haversine_formula
this a good explanation
http://www.movable-type.co.uk/scripts/latlong.html
for JavaScript:
var R = 6371000; // metres
var φ1 = lat1.toRadians();
var φ2 = lat2.toRadians();
var Δφ = (lat2-lat1).toRadians();
var Δλ = (lon2-lon1).toRadians();

var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
        Math.cos(φ1) * Math.cos(φ2) *
        Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

var d = R * c;

Whit this you can  iterate on your point and get if the distance is lower then 20 meters.

A: Here is a MySQL query (written in PHP) that allows you to retrieve all points within a given distance:
$sql = "SELECT *, ( 3959 * acos( cos( radians(" . $lat . ") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(" . $lng . ") ) + sin( radians(" . $lat . ") ) * sin( radians( lat ) ) ) ) AS distance FROM your_table HAVING distance < 5";

Where $lat and $lng are the coordinates of your point, lat/lng are your table columns and your_table is your table name. The above will list the locations within a 5 nm range. Replace 3959 by 6371 to change to kilometers.
It uses the Haversine formula, as pointed by @scaisEdge in his answer.

A: Pythagoras is adequate for less than 20 meters.
Below is javascript function to return distances in metres. I am sure you can convert to Java'
function Pyth(lat1,lat2,lng1,lng2){
x = toRad(lng2-lng1) ;
y = toRad(lat2-lat1);
R = 6371000; // gives d in metres
d = sqrt(x*x + y*y) * R;
return d;
}


text:
Q: "No Limit" Versus "Unlimited" Senior programmer in my team in developing hotel management program and there is something about hotel rooms limit, how many room the hotel can provide to customer. He want to add option to indicate that hotel is sure to welcome any amount of customer and he was asking me that should we use "No Limit" or "Unlimited"

A: Is the number of rooms the hotel can provide truly infinite? If so, you can use either one. But if it is not, then you must hit the limit at some point. Therefore "no limit to the rooms" or "unlimited rooms" would be — what's the word I'm looking for here? — a lie.
I suggest you qualify your statement by saying the number of rooms you can offer is "virtually unlimited," to make clear that this is just advertising-speak, and that if a billion people were to show up one night you would have to turn a few of them away.

A: I assume this is not Hilbert's Hotel, which not only had an infinite number of rooms, but could accommodate infinitely more guests even when already full by some deft room changes.
I suspect this is more of a questionnaire trying to deal with people who do not want to give a limit figure for the rooms.  So you might consider words like any or not stated or unspecified.


text:
Q: The emulator process for avd has terminated 2022 new on Android Studio I am trying realy hard to make Android studio work but life is not eazy right now. I tried everything related to the "the emulator process for avd has terminated" problem. I have enough space on my disk, I tried so many other stuff that I saw on youtube and in here but nothing is working... I am a big newbie in the android dev world...
plz help me !
I tried : Tutorial about creating a txt file on the .android file (not working),
Trying under 30 api (not working) and I have enough space on my computer


text:
Q: Why the extra bits are added to the kernel version in Ubuntu 18.04 I am cloning the kernel version 4.14.98_2.0.0_ga from git in Ubuntu 16.04 PC.
I get the kernel version as 4.14.98-imx_4.14.98_2.0.0_ga+g5d6cbea.
But when I do the same in Ubuntu 18.04 PC, I get 5 bits extra added to the kernel version as 4.14.98-imx_4.14.98_2.0.0_ga+g5d6cbeafb80c. Can anyone please tell why these extra bits are added? Does it depend on the host PC what i am using or is it taking the git tags or commit?
If I give the command git describe in 16.04 i get
v4.14.98-5985-g1175b59

The same command in 18.04 gives
v4.14.98-5985-g1175b5961153

How can I remove the "61153" from that?

A: To print the same identifier just once,
git describe --abbrev=8

To permanently set this repo to always report the abbreviated hash with 8 hex digits,
git config core.abbrev 8

To set this permanently for all your local repos (unless a repo overrides it separately with a local per-repo configuration) add --global to the above command line.
When core.abbrev is not set, git displays enough hex digits to try to ensure that the printed identifier is safely unique.  This is described in the git-config documentation:

core.abbrev
Set the length object names are abbreviated to. If unspecified or
set to "auto", an appropriate value is computed based on the
approximate number of packed objects in your repository, which
hopefully is enough for abbreviated object names to stay unique for
some time. The minimum length is 4.


text:
Q: System() calls in C++ and their roles in programming I've often heard that using system("PAUSE") is bad practice and to use std::cin.get() instead. Now my understanding of system calls is that they take a string which they enter into a system command line and talk with the OS, so PAUSE is a DOS command that pauses the output in the command window. I assume this works similarly with Mac and unix with different keywords, and using system calls is discouraged because of a lack of cross OS compatibility. (If I'm wrong with any of this, please correct me)
my question is this: When is it appropriate to use system() calls? How should they be applied? When should they NOT be applied?

A: system("PAUSE") is certainly less than ideal.  using a call to system creates a subprocess, which on windows is fairly expensive and in any case not terribly cheap on any operating system.  On embedded systems the memory overhead is significant.
If there is any way to do it without much pain natively then do it.  In the case of waiting for the user to press a single button, cin.get() will be very hard to beat.  In this case, your applications process will just block on stdin, setting only a few flags visible to the kernel, and most importantly, allocates no new memory and creates no new scheduling entities, not even an interrupt handler.
Additionally, it will work the same on all operating systems with all c++ compilers, since it uses only a very basic feature of a very standard part of the language, rather than depend on anything the OS provides.
EDIT: predicting your concern that it doesn't matter if it's expensive because the whole idea is to pause.  Well, first off, if its expensive, then it's going to hurt performance for anything else that might be going on.  Ever notice (on windows) when one application is launching, other, already open apps become less responsive too?  Additionally, your user might not be a live human, but rather another program working on behalf of a human user (Say, a shell script).  The script already knows what to do next and can pre-fill stdin with a character to skip over the wait.  If you have used a subprocess here, the script will experience a (noticeable to a human) delay.  If the script is doing this hundreds (or hundreds of millions!) of times, a script that could take seconds to run now takes days or years.
EDIT2: when to use system(): when you need to do something that another process does, that you can't do easily.  system() isn't always the best candidate because it does two things that are somewhat limiting.  First, the only way to communicate with the subprocess is by command line arguments as input and return value as output.  The second is that the parent process blocks until the child process has completed.  These two factors limit the cases in which system is useable.
on unixy systems, most subprocesses happen with fork because it allows the same program to continue in the same place as two separate processes, one as a child of the other (which is hardly noticeable unless you ask for it from the OS).  On Linux, this is especially well optimized, and about as cheap as creating a pthread.  Even on systems where this is not as fast, it is still very useful (as demonstrated by the apache process-pool methodology) (unavailable on windows/link to unix docs)
other cases (on windows too!) are often handled by popen or exec family of functions.  popen creates a subprocess and a brand new pipe connecting to the subprocesses' stdin or stdout.  Both parent and child processes can then run concurrently and communicate quite easily.  (link to windows docs/link to unix docs)
exec* family of functions (there are several, execl, execv and so on) on the other hand causes the current program to be replaced by the new program. The original program exits invisibly and the new process takes over.  When then new process returns, it will return to whatever called the original process, as if that process had returned at that point instead of vanishing.  The advantage of this over exit(system("command")) is that no new process is created, saving time and memory (though not always terribly much) (link to windows docs /link to unix docs)
system could plausibly be used by some scripted tool to invoke several steps in some recipe action.  For example, at a certain point, a program could use system to invoke a text editor to edit some configuration file.  It need not concern itself too much with what happens, but it should certainly wait until the user has saved and closed the editor before continuing.  It can then use the return value to find out if the editing session was successful, in the sense that the editor actually opened the requested file (and that the editor itself existed at all!), but will read the actual results of the session from the edited file directly, rather than communicating with the subprocess. (link to windows docs/link to unix docs)

A: System calls are sent to the shell or command line interpreter of the OS (dos, bash, etc) and its up to the shell to do what it wants with this command.
You would avoid using these kind of calls as it would reduce your programs portability to work with other operating systems. I would think only when you are absolutely sure that your code is targeting a specific OS that you should use such calls.

A:
But my question is this: When is it appropriate to use system() calls? How should they be applied?

When you can't do the thing you're trying to do with your own code or a library (or the cost of implementing it outweighs the cost of launching a new process to do so).  system() is pretty costly in terms of system resources compared to cin.get(), and as such it should only be used when absolutely necessary.  Remember that system() typically launches both an entire new shell and whatever program you asked it to run, so thats two new executables being launched.

A: By the way, system() call should never be used with binaries with SUID or SGID bit set, quoting from the man page:

Do not use system() from a program with set-user-ID or set-group-ID
  privileges, because strange values for some environment variables
  might be used to subvert system integrity. Use the exec(3) family of
  functions instead, but not execlp(3) or execvp(3). system() will not,
  in fact, work properly from programs with set-user-ID or set-group-ID
  privileges on systems on which /bin/sh is bash version 2, since bash 2
  drops privileges on startup.

A: system() is used to ask the operating system to run a program.
Why would your program want the operating system to run a program?  Well there are cases.  Sometimes an external program or operating system command can perform a task that is hard to do in your own program.  For example, an external program may operate with elevated privileges or access propriety data formats.
The system() function, itself, is fairly portable but the command string you pass it is likely to be very platform-specific -- though the command string can be pulled from local configuration data to make it more platform-agnostic.
Other functions like fork(), exec*(), spawn*() and CreateProcess() will give you much more control over the way you run the external program, but are platform-specific and may not be available on your platform of choice.
system("PAUSE") is an old DOS trick and is generally considered to be fairly grotty style these days.

A: As far as i know system("PAUSE") is a windows only thing, and that is why it is frowned upon.


text:
Q: Transaction with many INSERT'S without locking the table I've got script that is creating same data in database. It looks like:
START TRANSACTION;
INSERT INTO table (data);
INSERT INTO table (data);
INSERT INTO table (data);
...
COMMIT;

The script run for about 30 minutes. But when it's working, the table is locked for other INSERTS. I'm not able to INSERT any row from in another process until the script ends. Is it necessary? I'd like to use transaction, but I can't lock whole table. Is there any way to do that?

A: Can you instead do:
START TRANSACTION;
INSERT INTO table (data);
COMMIT;
START TRANSACTION;
INSERT INTO table (data);
COMMIT;
...
START TRANSACTION;
INSERT INTO table (data);
COMMIT;

Not the most elegant, but it should solve your problem based upon the situation you describe.
If you need the whole item to be one TRANSACTION, then the best way to do things would be as follows:
INSERT INTO tmpTableA (dataX);
INSERT INTO tmpTableB (dataY);
INSERT INTO tmpTableC (dataZ);
...
'   Do all the "building / processing above using temp tables either in memory or on disc, and then only when all the "heavy lifting" is done; update/insert the data into your tables.
...
START TRANSACTION;
INSERT INTO tableA (tmpTableA);
UPDATE tableB.foo = tmpTableB.fee WHERE BlahBlobBlah;
INSERT INTO tableC (tmpTableC);
COMMIT;

You want to hold off on starting the TRANSACTION, until all of the processing is done.

A: You should create a temp table: table_temp
insert all data to table_temp, when you ready you can insert all temporary data into final table:
START TRANSACTION;
INSERT INTO table_temp (data);
INSERT INTO table_temp (data);
INSERT INTO table_temp (data);

insert into table
select * from table_temp;

commit;


text:
Q: Rails Engine vs. Rack Application I'm thinking about writing an "add-on" application and releasing it as a gem. However, I'm not sure if I should be writing a Rails Engine or a Rack application. What are the differences and which should I choose?
Update: The idea for the application is sort of like a "suggestion box". Your users (or co-workers) can submit suggestions for improvements to your application. Then, when you're ready to work on a new feature, you can attach a cucumber test (or point to the location of one) so the submitter can see when the feature has been completed (tests passing). So ideally, you could mount this application at /suggestions or where ever and get all this functionality.

A: With Rails Engine, you generally have the power of Rails at your disposal, It is inherently a Rack Application because of Rails.
Generally a Rack Application will have a lot of less(or more) bells and whistles compared to Rails. You will have to figure which Rack components to use and how to setup the middleware if needed.
If you need a quick and easily testable solution, go for Rails Engines.
Otherwise building a Rack Application will be supremely more fun as compared to a Rails Engine.


text:
Q: Transferring Cordova debug build to real phone After running this command, the terminal says build succeeded,
ionic cordova build ios --debug

Can I transfer the build in my device? How to install it?
I am new to ios ...

A: Have you tried to run:
ionic cordova run ios --debug

Referring to Documentation of ionic https://ionicframework.com/docs/cli/cordova/run/
Anyway, if that was not helpful, simply you can open Xcode project from the build that you made, and run debug inside Xcode.
If you mean deploying it to Apple store, then you need to look into this: https://ionicframework.com/docs/intro/deploying/#ios-devices


text:
Q: How can I get an interactive shell inside a Google datalab container? I need to install additional software in a Google datalab container that runs with docker. It is possible to run bash commands with %%bash .... However, this does not allow interactivity. So, I need an interactive shell within the container.

A: If you need to modify the Datalab image you can write a new Dockerfile based on it like @Rambler suggested, or you can fork your own version, Datalab is open source.

A: You can try running the container in interactive mode in the following way :
docker run -it --name=<container_name> <image>:<tag> /bin/bash

If the container is already running , you can leverage docker exec :
docker exec -it <container_name> /bin/bash


text:
Q: VB.NET - Extracting text inside quotation in a complex string I have a string looking like this:
a:391:i:0;s:12:"jnKKPkvpNnfn";i:1;s:12:"ic9VAk3PvQ3j";i:2;s:12:"PEBFuE6bGepr";i:3;s:12:"bwuxRkH6QbGp";i:4;s:12:"LSRDQbAKXc9q";i:5;s:12:"eLuVbSAxQCgo";}

And I want to get the text inside the quotations and send them to a listbox.
I know sort of how to do it, but in an ineffective way that might now work... So I'm asking for advice with an example on how to do it.
Thanks

A: This should get you started; the method will run through an input string and return an array of strings that are contained within quotes.
    string[] ParseQuotes(string input)
    {
        List<string> matches = new List<string>();
        bool open = false;
        int index = -1;

        for (int i = 0; i < input.Length; i++)
        {
            if (input[i] == '"')
            {
                if (!open)
                {
                    open = true;
                    index = i;
                }
                else
                {
                    open = false;
                    string match = input.Substring(index + 1, index - i - 1);
                    matches.Add(match);
                }
            }
        }

        return matches.ToArray();
    }

Converted to VB...
Private Function ParseQuotes(input As String) As String()
    Dim matches As New List(Of String)()
    Dim open As Boolean = False
    Dim index As Integer = -1

    For i As Integer = 0 To input.Length - 1
        If input(i) = """"C Then
            If Not open Then
                open = True
                index = i
            Else
                open = False
                Dim match As String = input.Substring(index + 1, index - i - 1)
                matches.Add(match)
            End If
        End If
    Next

    Return matches.ToArray()
End Function

A: In your main code:
cbYourcomboBox.Items.Clear()
cbYourcomboBox.Items.AddRange(GetList(str).ToArray)

and then the function itself:
Public Function GetList(ByVal str As String) As List(Of String)
    Dim ar As String()
    Dim ar2 As List(Of String) = New List(Of String)
    ar = Split(str, Chr(34))

    ' making sure there is a matching closing quote with - (UBound(ar) And 1)
    For a As Integer = 1 To UBound(ar) - (UBound(ar) And 1) Step 2
        ar2.Add(ar(a))
    Next a

    Return ar2
End Function


text:
Q: Word meaning the arrangement of sounds or syllables to form words? See Title.
An answer would also satisfy:
Syntax is to Sentence as ______ is to Word?
Or, in more code-friendly terms
Syntax is to Function Logic as ______ is to Construct Logic? (idk, I tried)

A: The word you're looking for is phonotactics.

A: There are two possible answers to your question depending on your exact intent. If I were to guess, the word you're looking for is: morphology but it could also be phonology. However, I don't think "phonology" fits your second example.
The thing you seem to be describing are various parts of grammar. Grammar is the study of syntax, phonology and morphology.
Syntax describes the general structure of the language. How words fit together.
Phonology describes how sounds fit together in the language. How many vowels there are, the consonants, the types of consonants etc.
Morphology describes how words are formed in the language. Does the language modify words with tenses? Does the language modify words with gender? Does the language not modify words at all but instead use other words? etc.


text:
Q: update textView in a widget I've read a lot of Q&As but I couldn't find my answer.
May be something in my implementation is wrong.
The problem is that my TextView in the widget doesn't get updated.
The logic is this:
1.setOnClickPendingIntent on a specific button in the onUpdate()
2.clicking on this button will broadcast an intent with a declared action
3.at last i'll update the text of the textView in the onRecieve()
Widget2.class :
public class Widget2 extends AppWidgetProvider {

private static final String SCROLL_LEFT = "widget2.SCROLL_LEFT";

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    super.onUpdate(context, appWidgetManager, appWidgetIds);

    for (int i = 0; i < appWidgetIds.length; i++) {
        int appWidgetId = appWidgetIds[i];
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.small);

        Intent scrollLeft = new Intent(Widget2.SCROLL_LEFT);
        PendingIntent leftScrollPendingIntent = PendingIntent.getBroadcast(context,
                appWidgetId, scrollLeft, appWidgetId);
        remoteViews.setOnClickPendingIntent(R.id.left_scroller, leftScrollPendingIntent);

        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
    }
}

@Override
public void onReceive(Context context, Intent intent) {

    Log.e(getClass().getSimpleName(), "onReceive()");
    int appWidgetId = intent.getFlags();
    if (intent.getAction().equals(SCROLL_LEFT)) {
        updateCurrentWidget(context, appWidgetId);
        Log.i("onReceive", SCROLL_LEFT + "   appWidgetId = " + appWidgetId);
    }
            super.onReceive(context,intent);
}

private void updateCurrentWidget(Context context, int appWidgetId) {
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.small);
    remoteViews.setString(R.id.name_of_the_app, "setText", "android os");
    remoteViews.setTextViewText(R.id.description, "best ever");

    Log.i("updateCurrentWidget", "the text have been set");
    AppWidgetManager manager = AppWidgetManager.getInstance(context);
    manager.updateAppWidget(appWidgetId, remoteViews);
}

manifest.xml :
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="14" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <receiver android:name=".Widget2" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="widget2.SCROLL_LEFT" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_small" />
        </receiver>
    </application>

</manifest>

and here is the simplified logcat logs:
   onReceive()
   "myPackageName".Widget2.SCROLL_LEFT
   the text have been set
   "myPackageName".Widget2.SCROLL_LEFT appWidgetId = 268435456

everything seems to be correct but the text is never changed!

A: The key in the widget is you have to set every View and every Intent before calling the updateAppWidget() method. Here You can call updateWidgetInstance(...) from your onReceive() method:
// action = the String that you get from your intent in the onRecive() method
// id = the id of the appWidget instance that you want to update
// you can get the id in the onReceive() method like this:
// int id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
private static void updateWidgetInstance(Context context, AppWidgetManager manager, String action, int id) {
    RemoteViews remoteViews = updateCurrentWidget(context, id);
    remoteViews = setIntents(remoteViews, context, id);
    manager.updateAppWidget(id, remoteViews);
}

updating the View: (Here you can also change the layout of this instance depending on your needs)
  private static RemoteViews updateCurrentWidget(Context context, int appWidgetId) {
    RemoteViews remoteViews;

        remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_small_layout);
        remoteViews.setTextViewText(R.id.widget_name_of_the_app, "Android OS");
        remoteViews.setTextViewText(R.id.widget_app_description, "best ever");
        remoteViews.setImageViewUri(R.id.widget_icon_of_the_app, ...);

    return remoteViews;
}

updating intents:
private static RemoteViews setIntents(RemoteViews rm, Context context, int appWidgetId) {

    Intent click = new Intent(context, Widget.class);
    click.setAction("[name of the action]");
    click.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    PendingIntent pendingIntent =
            PendingIntent.getBroadcast(context, appWidgetId, click, PendingIntent.FLAG_UPDATE_CURRENT);
    rm.setOnClickPendingIntent(R.id.button1, pendingIntent);

    return rm;
}

A: you are setting your appWidgetId in the PendingIntent flags. that's just wrong since PendingIntet flags have meanings, they are not meant to save some data.
You should use the extras for that.


text:
Q: Ping on working site says Destination Unreachable I am pinging a working site from my cmd and I get this:
ping site.com

Pinging site.com [x.x.x.x] with 32 bytes of data:
Reply from x.x.x.x: Destination host unreachable.
Reply from x.x.x.x: Destination host unreachable.
Reply from x.x.x.x: Destination host unreachable.
Reply from x.x.x.x: Destination host unreachable.

Ping statistics for x.x.x.x:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

I have censored the IP and domain for obvious reasons. The site is accessible from my browser in this machine.
My question is, how/why would they do this?

A: ping is an ICMP command request which companies/organisations can block using their firewall for security reasons/purposes. It has nothing to do with website's accessibility using browser.
They are receiving your request and not taking any action further; so it says that destination host is unreachable!
So even though you can visit the organisation's website on the web-browser, your ping request can be blocked for the afore-mentioned reason.

A: The next diagnostic step is traceroute.  To get even more hard-core, use a more complicated tool like nmap or hping2 that lets you send a variety of packets.
Assuming nothing out-of-the-box strange is going on, some intermediate host (or even the destination host) is dropping your ICMP echo packet and responding with ICMP destination unreachable.
This is confusing, because that's not really the problem.  However, one big reason this happens is that some routers, even high-end ones, have limits on the kinds of ICMP errors that they can generate, and sometimes an administrator will configure it in an annoying way like this.  Another common manifestation of the same issue is intermediate routers dropping TCP packets with RST, making ports look closed instead of just blocked by a firewall.
If it's on your network, consider asking the administrator to switch it to a less confusing message, such as administratively prohibited.
If you still want to ping, consider using a ping utility that uses an alternate packet type, such as hping2, as mentioned above.
Given the foregoing, blocking ping is pretty much a TSA-style security measure.  It's tremendously annoying in practice for anyone trying to troubleshoot the site, but it doesn't actually prevent pinging using some other packet type.  Hypothetically, it might defeat the dumbest of host up/down scanners, but if port 80 is open, any real scan is still going to find it.
As an alternative explanation, it is possible that the host actually is unreachable using your current routing table, and the browser is finding it some other way.  For instance, your network might have no default route to the Internet, but the browser is using a proxy server, that does have access.  This kind of configuration is used by some sites, generally to prevent rogue malware or hackers on your network from being able to trivially call out.


text:
Q: Mongoose connection error with firebase-admin package I have been getting mongoose connection error whenever I install firebase-admin package and it fixes itself whenever I remove the package. I am using node.js with typescript
The config I am passing are as follows:
options: {
useUnifiedTopology: true,
useNewUrlParser: true,
socketTimeoutMS: 30000,
keepAlive: true,
autoIndex: false,
retryWrites: false
},
url: 'mongodb://127.0.0.1:27017/hello-hello-backend'

Code for mongoose connection:
mongoose
    .connect(dbConfig.url, dbConfig.options)
    .then(() => {
      console.log(TEXT.DATABASE_STATUS);
    })
    .catch((err) => {
      console.log("failed connecting to database");
      console.log(err);
    });

The error:

How can I solve this?


text:
Q: How do I change this data into proper format to do association rule mining in WEKA? This is how the data is stored in the file given. There are 8 attributes given.
I need association rule mining done using Apriori Algorithm in WEKA.
Such as, if item 1 & item 2 are bought --> item 4 is also bought or something reasonable as that.

What I tried:
Converting the file into .arff format and loading into weka.
Turning all attributes in Nominal and running the algorithm Apriori.
But the rules generated are very weird.
This is how the result comes. It has no proper information. No rules like what i want, which actually define what a user will buy with what or anything.
i.e. the rules generated here are of no information to me, there is no relation/rules given as to which item will be bought with what.

How should I preprocess this data to format it well or if am making any other mistake would be really appreciated.


text:
Q: Add local file to IE11 Trusted Zone or Local Intranet I'd like to add a local file (C:\Users\David\AppData\LocalLow\LastPass\iehome2.html) LastPass needs to open my LastPassVault in IE11.
Scripting is disabled in my Internet zone and the file needs JavaScript in order to work ("JavaScript is required for this page to function.").
However, I am having a hard time adding the file to IE's Trusted Sites or Local Intranet.
The most logical thing to me is to add file://* to the zones, but IE won't except that screenshot


text:
Q: Flex: Accessing video content over local network I am having a strange issue in my flex app. I have a Video element that loads an FLV file from the same directory as the SWF app. If I move my SWF and FLV to a local directory on my computer and load the SWF in my browser, the video plays without any issues. However, if I move the same collection of files (SWF, FLV, HTML) to a network share, the video no longer loads.
I am loading video using a NetConnection and NetStream and calling video.attachNetStream(stream) on my Video object.
stream = new NetStream(connection);
stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
var video:Video = new Video();
video.attachNetStream(stream);

In my netStatusHandler() callback I get an event status of: NetStream.Play.StreamNotFound.
Again, I only have this issue when loading content from a network share.

A: That would be because of the security sandbox since now your application is not 'local' anymore, the security sandbox policy is activated.  There's 2 things you can do; you can add that network share/swf into your security sandbox through the security settings page or you can 'share' this over an http server (apache).
You should read up more on security sandboxes.


text:
Q: Поиск и замена в файле с помощью регулярных выражений Собственно сабж. Есть много файлов .срр в который очень много блоков кода  вида:
Application->MessageBox("Текст.","Внимание",MB_OK);
Application->MessageBox("Другой текст.","Внимание",MB_OK);
Application->MessageBox("Совсем другой текст.","Внимание",MB_OK);

с очень большим вложением. Суть в чем. Необходимо преобразовать файлы в следующий вид:
Application->MessageBox(L"Текст.",L"Внимание",MB_OK);
Application->MessageBox(L"Другой текст.",L"Внимание",MB_OK);
Application->MessageBox(L"Совсем другой текст.",L"Внимание",MB_OK);

То есть добавить L перед каждой открывающей кавычкой строковой константы.
В редакторе регулярных выражений методом проб и ошибок составил РВ:
regex = r"(\bApplication->MessageBox[AW]?\()([^\,]+\,)([^\,]+\,)(\bMB_OK\)\;)"

Решил делать все на питоне, вот мои соображения:
currFile = open("C:/test.cpp","r") )
currLine = currFile.read()
print(currLine)
print("\n\n\n")
matches = re.finditer(regex,currLine)
for match in matches:
    subst = match.group(1)+ "L" + match.group(2)+ "L" + match.group(3) + match.group(4)
    result = re.sub(regex,subst, currLine,0)
    print(result)
currFile.close()

Сейчас он находит на 1 итерации все вхождения, и тут же все меняет, на второй опять все меняет, и так пока не дойдет до последней, получаем:
Application->MessageBox(L"Совсем другой текст.",L"Внимание",MB_OK);
Application->MessageBox(L"Совсем другой текст.",L"Внимание",MB_OK);
Application->MessageBox(L"Совсем другой текст.",L"Внимание",MB_OK);

Вот только не могу понять как с этим бороться.Необходимо сохранить оригинальный текст. Мб я не совсем корректно составил РВ?

A: Попробуйте с этой регуляркой:
import re

text = """\
Application->MessageBox("Текст.","Внимание",MB_OK);
Application->MessageBox("Другой текст.","Внимание",MB_OK);
Application->MessageBox("Совсем другой текст.","Внимание",MB_OK);
"""

new_text = re.sub(
    r'Application->MessageBox\("(.+)","(.+)",MB_OK\);',
    r'Application->MessageBox(L"\1",L"\2",MB_OK);',
    text
)
print(new_text)

Консоль:
Application->MessageBox(L"Текст.",L"Внимание",MB_OK);
Application->MessageBox(L"Другой текст.",L"Внимание",MB_OK);
Application->MessageBox(L"Совсем другой текст.",L"Внимание",MB_OK);


text:
Q: biblatex messing up citation entry with lots of authors Here is the citation:

@Article{boker2011,
  Author         = {Boker, S. and Neale, M. and Maes, H. and Wilde, M. and
                   Spiegel, M. and Brick, T. and Spies, J. and Estabrook,
                   R. and Kenny, S. and Bates, T. and others},
  Title          = {Open{M}x: {A}n open source extended structural
                   equation modeling framework},
  Journal        = {Psychometrika},
  Volume         = {76},
  Number         = {2},
  Pages          = {306--317},
  year           = 2011
}

Here is a test document:

\documentclass[doc]{apa6}
\usepackage[american]{babel}
\usepackage{csquotes}
\usepackage[style=apa,sortcites=true,sorting=nyt,apabackref=true,backend=biber]{biblatex}
\DeclareLanguageMapping{american}{american-apa}
\addbibresource{jpritikin.bib}

\shorttitle{IFA}

\begin{document}

OpenMx \parencite{boker2011}

\printbibliography

\end{document}

I obtain this mess: Boker, S. et al., Neale, M. et al., Maes, H., et al., Wilde, M., et al., Spiegel, M., et al., Brick,
T., et al., . . . Et al., et al., et al., Bates, T., et al. (2011). OpenMx: An open source
extended structural equation modeling framework. Psychometrika, 76 (2), 306–317.
(Cit. on p. 17).
I thought maybe I had a bad mix of versions. I tried "tlmgr update --all". I have biblatex 2.8 installed and I just installed biber 1.8 from http://biblatex-biber.sourceforge.net/. I still get too many "et al."
Suggestions?

A: This problem is due to biblatex-apa's (apa.bbx's) apaauthor name format; you might want to notify the author of this small bug.
The string and others in the author list sets ifmorenames to true. apaauthor checks for this case whenever a name is printed, not just at the very end of the list; consequently it prints the andothers string ("et al.") after each name.
The fix is to add the following lines to your preamble.
\DeclareNameFormat{apaauthor}{%
  \ifthenelse{\value{listcount}=\maxprtauth\AND\value{listcount}<\value{listtotal}}
    {\addcomma\addspace\ldots\addspace}
    {\ifthenelse{\value{listcount}>\maxprtauth\AND\value{listcount}<\value{listtotal}}
      {}
      {\ifthenelse{\iffieldequalstr{doubtfulauthor}{true}}
        {\mkbibbrackets{\usebibmacro{name:apa:last-first}{#1}{#3}{#4}{#5}{#7}?}}
        {\usebibmacro{name:apa:last-first}{#1}{#3}{#4}{#5}{#7}}}}%
  \ifthenelse{\value{listcount}=\value{listtotal}}% this test is new
    {\ifmorenames{\andothersdelim\bibstring{andothers}}{}}{}}

The MWE
\RequirePackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@Article{boker2011,
Author = {Boker, S. and Neale, M. and Maes, H. and Wilde, M. and
Spiegel, M. and Brick, T. and Spies, J. and Estabrook,
R. and Kenny, S. and Bates, T. and others},
Title = {Open{M}x: {A}n open source extended structural
equation modeling framework},
Journal = {Psychometrika},
Volume = {76},
Number = {2},
Pages = {306--317},
year = 2011
}

\documentclass{apa6}
\usepackage[american]{babel}
\usepackage{csquotes}
\usepackage[style=apa,maxnames=999,sortcites=true,sorting=nyt,apabackref=true,backend=biber]{biblatex}
\DeclareLanguageMapping{american}{american-apa}
\addbibresource{\jobname.bib}
\addbibresource{biblatex-examples.bib}

\DeclareNameFormat{apaauthor}{%
  \ifthenelse{\value{listcount}=\maxprtauth\AND\value{listcount}<\value{listtotal}}
    {\addcomma\addspace\ldots\addspace}
    {\ifthenelse{\value{listcount}>\maxprtauth\AND\value{listcount}<\value{listtotal}}
      {}
      {\ifthenelse{\iffieldequalstr{doubtfulauthor}{true}}
        {\mkbibbrackets{\usebibmacro{name:apa:last-first}{#1}{#3}{#4}{#5}{#7}?}}
        {\usebibmacro{name:apa:last-first}{#1}{#3}{#4}{#5}{#7}}}}%
  \ifthenelse{\value{listcount}=\value{listtotal}}
    {\ifmorenames{\andothersdelim\bibstring{andothers}}{}}{}}

\shorttitle{IFA}

\begin{document}

OpenMx \parencite{boker2011,aksin,wilde,murray}

\printbibliography
\end{document}

then yields

Update 2013-10: This has been corrected in biblatex-apa version 6.4 according to a comment below the question from user PLK.


text:
Q: subtract 2 negative numbers in binary So if we have 2 negative numbers and we want to subtract them do the subtraction becomes addition ? Or we subtract them normally
I tried to subtract them but it gave me a wrong number but when I add them I got overflow