text:
Q: Angular Typeahead: click on suggestion and instantly make a post? I am working on a project and I'm using the Siyfion's angular Typeahead. I have a Typeahead for searching users. When a username is found in the suggestions dropdown you should be able to click on a name or press enter to directly make a post instead of needing to press a button to do the post. For this to work I need to "catch" the click- or return-event on one of the user names.
Below you will find the html and the js for it and I also made a plunker to makes things more clear.
Does anybody know how I can catch the click and the return events? All tips are welcome!
<body ng-controller="MainCtrl">
    <input class='typeahead' type="text" sf-typeahead options="exampleOptions" datasets="numbersDataset" ng-model="selectedName">
    <input type="button" value="Post user to server" type="text" ng-click="postUserToServer(selectedName.id)">
</body>

Here is the JS code:
var app = angular.module('plunker', ['siyfion.sfTypeahead']);

app.controller('MainCtrl', function($scope) {

    $scope.selectedNumber = null;

    // instantiate the bloodhound suggestion engine
    var numbers = new Bloodhound({
        datumTokenizer: function(d) {
        return Bloodhound.tokenizers.whitespace(d.name); },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: [
                   { name: 'John',id: 1 },
                   { name: 'Richard', id: 2 },
                   { name: 'Dennis', id: 3 }
        ]
    });

    // initialize the bloodhound suggestion engine
    numbers.initialize();

    $scope.numbersDataset = {
        displayKey: 'name',
        source: numbers.ttAdapter()
    };

    // Typeahead options object
    $scope.exampleOptions = {
        highlight: true
    };

    $scope.postUserToServer = function(userId){
        alert(userId);
    };
});

A: Typeahead supports custom events which you can bind to a function to automatically submit your form. You can view all of the custom events available in the docs here.
Here's an example:
$('.typeahead').bind('typeahead:select', function(ev, suggestion) {
  console.log('Selection: ' + suggestion);
});

The above code "typeahead:select" binds a function to the event. This  will fire when a suggestion is clicked on, or when the return key is hit and a suggestion is hightlighted.
From here you can do anything you want inside your function, so in your case you'd want to submit the search. Honestly I'm not that familiar with Angular so I'm not sure what the correct syntax would be to actually submit the search. You could however use the .trigger() method in jQuery to trigger a click on your search button; although I appreciate this is a bit hacky and I'm sure there is a more elegant way to submit the search.

A: The Siyfion's plugin doesn't seem to have enough documentation about event handling. Try using this plugin [https://github.com/borntorun/angular-typeaheadjs]
They have very good documentation on event handling and this is specifically for AngularJS.
Examples from their documentation:
<angular-typeaheadjs angty-onselect="vm.onselect" ...>
  <input class="typeahead" type="text" ... />
</angular-typeaheadjs>

//on the controller
vm.onselect = function() {
  //do something
}

or you can simply say:
$scope.$on('typeahead:select', function() {
  //Your post code goes here....
});

Hope this helps!


text:
Q: How to get a unix script to run every 15 seconds? I've seen a few solutions, including watch and simply running a looping (and sleeping) script in the background, but nothing has been ideal.
I have a script that needs to run every 15 seconds, and since cron won't support seconds, I'm left to figuring out something else.
What's the most robust and efficient way to run a script every 15 seconds on unix? The script needs to also run after a reboot.

A: I would use cron to run a script every minute, and make that script run your script four times with a 15-second sleep between runs.
(That assumes your script is quick to run - you could adjust the sleep times if not.)
That way, you get all the benefits of cron as well as your 15 second run period.
Edit: See also @bmb's comment below.

A: If you insist of running your script from cron:
* * * * * /foo/bar/your_script
* * * * * sleep 15; /foo/bar/your_script
* * * * * sleep 30; /foo/bar/your_script
* * * * * sleep 45; /foo/bar/your_script

and replace your script name&path to /foo/bar/your_script

A: Modified version of the above:
mkdir /etc/cron.15sec
mkdir /etc/cron.minute
mkdir /etc/cron.5minute

add to /etc/crontab:
* * * * * root run-parts /etc/cron.15sec > /dev/null 2> /dev/null
* * * * * root sleep 15; run-parts /etc/cron.15sec > /dev/null 2> /dev/null
* * * * * root sleep 30; run-parts /etc/cron.15sec > /dev/null 2> /dev/null
* * * * * root sleep 45; run-parts /etc/cron.15sec > /dev/null 2> /dev/null

* * * * * root run-parts /etc/cron.minute > /dev/null 2> /dev/null
*/5 * * * * root run-parts /etc/cron.5minute > /dev/null 2> /dev/null

A: Won't running this in the background do it?
#!/bin/sh
while [ 1 ]; do
    echo "Hell yeah!" &
    sleep 15
done

This is about as efficient as it gets.  The important part only gets executed every 15 seconds and the script sleeps the rest of the time (thus not wasting cycles).

A: I wrote a scheduler faster than cron. I have also implemented an overlapping guard. You can configure the scheduler to not start new process if previous one is still running. Take a look at https://github.com/sioux1977/scheduler/wiki

A: Use nanosleep(2). It uses structure timespec that is used to specify intervals of time with nanosecond precision.
struct timespec {
           time_t tv_sec;        /* seconds */
           long   tv_nsec;       /* nanoseconds */
       };

A: #! /bin/sh

# Run all programs in a directory in parallel
# Usage: run-parallel directory delay
# Copyright 2013 by Marc Perkel
# docs at http://wiki.junkemailfilter.com/index.php/How_to_run_a_Linux_script_every_few_seconds_under_cron"
# Free to use with attribution

if [ $# -eq 0 ]
then
   echo
   echo "run-parallel by Marc Perkel"
   echo
   echo "This program is used to run all programs in a directory in parallel"
   echo "or to rerun them every X seconds for one minute."
   echo "Think of this program as cron with seconds resolution."
   echo
   echo "Usage: run-parallel [directory] [delay]"
   echo
   echo "Examples:"
   echo "   run-parallel /etc/cron.20sec 20"
   echo "   run-parallel 20"
   echo "   # Runs all executable files in /etc/cron.20sec every 20 seconds or 3 times a minute."
   echo
   echo "If delay parameter is missing it runs everything once and exits."
   echo "If only delay is passed then the directory /etc/cron.[delay]sec is assumed."
   echo
   echo 'if "cronsec" is passed then it runs all of these delays 2 3 4 5 6 10 12 15 20 30'
   echo "resulting in 30 20 15 12 10 6 5 4 3 2 executions per minute."
   echo
   exit
fi

# If "cronsec" is passed as a parameter then run all the delays in parallel

if [ $1 = cronsec ]
then
   $0 2 &
   $0 3 &
   $0 4 &
   $0 5 &
   $0 6 &
   $0 10 &
   $0 12 &
   $0 15 &
   $0 20 &
   $0 30 &
   exit
fi

# Set the directory to first prameter and delay to second parameter

dir=$1
delay=$2

# If only parameter is 2,3,4,5,6,10,12,15,20,30 then automatically calculate
# the standard directory name /etc/cron.[delay]sec

if [[ "$1" =~ ^(2|3|4|5|6|10|12|15|20|30)$ ]]
then
   dir="/etc/cron.$1sec"
   delay=$1
fi

# Exit if directory doesn't exist or has no files

if [ ! "$(ls -A $dir/)" ]
then
   exit
fi

# Sleep if both $delay and $counter are set

if [ ! -z $delay ] && [ ! -z $counter ]
then
   sleep $delay
fi

# Set counter to 0 if not set

if [ -z $counter ]
then
   counter=0
fi

# Run all the programs in the directory in parallel
# Use of timeout ensures that the processes are killed if they run too long

for program in $dir/* ; do
   if [ -x $program ]
   then
      if [ "0$delay" -gt 1 ]
      then
         timeout $delay $program &> /dev/null &
      else
         $program &> /dev/null &
      fi
   fi
done

# If delay not set then we're done

if [ -z $delay ]
then
   exit
fi

# Add delay to counter

counter=$(( $counter + $delay ))

# If minute is not up - call self recursively

if [ $counter -lt 60 ]
then
   . $0 $dir $delay &
fi

# Otherwise we're done

A: Since my previous answer I came up with another solution that is different and perhaps better. This code allows processes to be run more than 60 times a minute with microsecond precision. You need the usleep program to make this work. Should be good to up to 50 times a second.
#! /bin/sh

# Microsecond Cron
# Usage: cron-ms start
# Copyright 2014 by Marc Perkel
# docs at http://wiki.junkemailfilter.com/index.php/How_to_run_a_Linux_script_every_few_seconds_under_cron"
# Free to use with attribution

basedir=/etc/cron-ms

if [ $# -eq 0 ]
then
   echo
   echo "cron-ms by Marc Perkel"
   echo
   echo "This program is used to run all programs in a directory in parallel every X times per minute."
   echo "Think of this program as cron with microseconds resolution."
   echo
   echo "Usage: cron-ms start"
   echo
   echo "The scheduling is done by creating directories with the number of"
   echo "executions per minute as part of the directory name."
   echo
   echo "Examples:"
   echo "  /etc/cron-ms/7      # Executes everything in that directory  7 times a minute"
   echo "  /etc/cron-ms/30     # Executes everything in that directory 30 times a minute"
   echo "  /etc/cron-ms/600    # Executes everything in that directory 10 times a second"
   echo "  /etc/cron-ms/2400   # Executes everything in that directory 40 times a second"
   echo
   exit
fi

# If "start" is passed as a parameter then run all the loops in parallel
# The number of the directory is the number of executions per minute
# Since cron isn't accurate we need to start at top of next minute

if [ $1 = start ]
then
   for dir in $basedir/* ; do
      $0 ${dir##*/} 60000000 &
   done
   exit
fi

# Loops per minute and the next interval are passed on the command line with each loop

loops=$1
next_interval=$2

# Sleeps until a specific part of a minute with microsecond resolution. 60000000 is full minute

usleep $(( $next_interval - 10#$(date +%S%N) / 1000 ))

# Run all the programs in the directory in parallel

for program in $basedir/$loops/* ; do
   if [ -x $program ]
   then
      $program &> /dev/null &
   fi
done

# Calculate next_interval

next_interval=$(($next_interval % 60000000 + (60000000 / $loops) ))

# If minute is not up - call self recursively

if [ $next_interval -lt $(( 60000000 / $loops * $loops)) ]
then
   . $0 $loops $next_interval &
fi

# Otherwise we're done

A: To avoid possible overlapping of execution, use a locking mechanism as described in that thread.

redpajama_set_name: RedPajamaStackExchange


text:
Q: remember user selected folder and reopen it by NSOpenPanel under Sandbox Apple review require my app to remember the folder that user selected last time. But I can not make it under Sandbox. the  -setDirectoryURL seems not working under Sandbox.
What should I do? Thank you for your help!
// read string saveFolder from NSUserDefaults
NSOpenPanel * myPanel = [NSOpenPanel openPanel];
[myPanel setTitle:@"Select Output Folder"];
[myPanel setCanChooseDirectories:YES];
[myPanel setCanCreateDirectories:YES];
[myPanel setAllowsMultipleSelection:NO];
[myPanel setCanChooseFiles:NO];

NSLog(@"before openpanel:folder=%@",saveFolder); // <== return normal
[myPanel setDirectoryURL:[NSURL URLWithString:saveFolder.stringValue]];
NSLog(@"readback:folder=%@",[[myPanel URL] path]); // <== return nil here

if ([myPanel runModal] == NSOKButton)
{
    //
    saveFolder = [[myPanel URL] path]];
    // then save the saveFolder string to NSUserDefaults
    //
}

A: it seems we should add and use this entitlement:
com.apple.security.files.bookmarks.app-scope
SAVE THE URL:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSError *error = nil;
NSData *bookmarkData = [[myPanel URL] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
if (!error)
{
    [defaults setObject:bookmarkData forKey:@"iData"];
    [defaults synchronize];
}

READ BACK:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
bookmarkFileURL = nil;
NSData *bookmarkData = [defaults objectForKey:@"iData"];
if (bookmarkData != nil)
{
    NSError *error=nil;
    bookmarkFileURL = [NSURL URLByResolvingBookmarkData:bookmarkData options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:nil error:&error];
    if (error != nil) bookmarkFileURL = nil;
}
if (bookmarkFileURL)
{
    [bookmarkFileURL startAccessingSecurityScopedResource];
}
//
//
[bookmarkFileURL stopAccessingSecurityScopedResource];


text:
Q: How to make a short link to specific code line from markdown in github issue text? How to make a short link to specific code line from markdown in github issue text?
I have read the question How to link to specific line number on github, but it's about putting full link in markdown.
My question is about some markdown shortcut, like @user or #11 issue
Doc Autolinked references and URLs doesn't help.

A: There is no way to do this.
When you use @user to point a user page or #17 for a specific issue in the current project, you create a link to a unique object. When you want to provide a link to a file code, maybe you want to point to the latest revision in master (ex: https://github.com/google/apitools/blob/master/apitools/init.py) or on another branch (ex: https://github.com/google/apitools/blob/csl-patch/apitools/init.py). As far as I know, there is no shortcut available in GitHub flavord markdown for linking to a specific file in the project.
As you already noticed, using this long form (the full URL), you will be able to add a #LXXX to the end of the URL to point to specific line in the file (ex: https://github.com/google/apitools/blob/master/apitools/init.py#L5 or https://github.com/google/apitools/blob/csl-patch/apitools/init.py#L8. But if you really want to avoid long links, you could use GitHub URL Shortener to convert any link (with or without line number) to an equivalent short form: https://git.io/vMD6U


text:
Q: Writing pages - selecting correct content with PHP/SQL? I'm making a blog article system and I fill out a form with the content and then submit it to the database, from there I fopen() and fwrite(). I fwrite() the entire page. How do I recall the information? I was going to select the highest ID in the database and +1 that (thus that ID would be the one I'm writing into my fwrite() however that would change with each article. Is there any information I could pass over to the file which would identify the article specifically? Kinda blanking on what I could do to avoid the fwrite()'d page from pulling hte wrong information from the database later on :).
EDit
$included = '<?php
$connection=mysql_connect("localhost","codefund","pw removed");
// Check connection
if (!$connection)
{
    echo "Could not connect to the database: " . mysql_error();
}
mysql_select_db("codefund_articles") or die();
$articleID =

$page="";
require_once($_SERVER[\'DOCUMENT_ROOT\'].\'/includes/beginning.php\');
?>

    <?php require_once($_SERVER[\'DOCUMENT_ROOT\'].\'/includes/header.php\');?>

        <?php require_once($_SERVER[\'DOCUMENT_ROOT\'].\'/includes/sidebar.php\'); ?>

    <?php require_once($_SERVER[\'DOCUMENT_ROOT\'].\'/includes/footer.php\');?>

';

A: If your ArticleID is auto_incremented as you said, you can use mysql_insert_id() to retrieve the ID of the last inserted row.
That way you'll be sure to get the ID of the row you added in you script, and can therefore use that ID and be sure that it will correspond to the article you're 'fwritting' next. (And use it to name your article for example)
There are several examples on mysql_insert_id usage on the PHP manual :
http://php.net/manual/en/mysqli.insert-id.php


text:
Q: Ruby on Rails 4: Devise with Users Controller, Couldn't find User with 'id'=sign_up I'm getting this error: Couldn't find User with 'id'=sign_up when I'm trying to go to localhost:3000/users/sign_up in my URL browser.
I have a separate Users Controller that I generated...
I did this:
rails g devise:controllers users
rails g controller Users show

I didn't touch the controllers that was produced by devise.
In the regular users controller that I created, I have this:
class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
  end
end

In my routes:
devise_scope :user do
  get 'users/:id' => 'users#show', as: :user
end
devise_for :users

My rake routes looks like this:
new_user_registration GET    /users/sign_up(.:format)       devise/registrations#new
                 user GET    /users/:id(.:format)           users#show

It makes sense why I'm getting an error because :id is sign_up in my URL, I just don't get what I should be doing to fix this.
And of course, it'll always give me an error for anything after localhost:3000/users/ because of the id in my show method in users controller

A: You have a separate users_controller which doesn't belongs to devise so devise_scope is of no use there. If you need to use any devise controller action then devise_scope is useful. So just make your routes as this:
devise_for :users
get 'users/:id' => 'users#show', as: :user

The sequence of routes matters when we have similar routes. In devise the routes sign_up, sign_out are defined as /users/sign_up(.:format) so suppose you visit sign_up url then it would check with the routes in devise and will find the match there. So it will redirect you to that route. Now if you enter /users/1 it will find in devise routes but it will find no match so ultimately it will map to your route and if there is no route defined as such it will throw error..
Glad this helped. :)


text:
Q: generate casenumber i need to generate a casenumber like this with perl and mysql:
xx-201012080001
the first part is just a couple of chars, followed by the date. the
last four digits is the problem, it should start at 0001 and increment
by one for each case. the real trouble is that it must restart at 0001
every day.
any suggestions on how to do this?

A: use sprintf to generate the string:
 my $casenumber = sprintf("%2s-%8d%04d", $twochars, $date, $increment);

For example, on the command line:
$ perl -e 'printf("%2s-%8d%04d\n", "aa", "20101211", 2);'
$ aa-201012110002

As for resetting your count to 1, keep a variable called $lastDate for each record in your iteration. If the $lastDate != $currentDate, you reset your counter to 1.
For example:
# assumes @records contain arrayrefs with relevant info from mysql
# also assumes the data is sorted by date.
my $count = 1;
my $lastDate;
my $currentDate;
for my $record (@records)
{
   my $twochars    = $record->[0];
   my $currentDate = $record->[1];
   if($currentDate != $lastDate)
   {
     $count = 1;
   }
   my $casenumber  = sprintf("%2s-%8d%04d", $twochars, $currentDate, $count++);
   $lastDate = $currentDate;
}

A: How about using a query like this:
select casenr from cases where casenr like ? order by 1 desc limit 1

where the ? is the prefix for today ("xx-20101208").
This should give you the last casenr for today or NULL, then just increment the suffix or set it to 0001.


text:
Q: JWT authentication 401 Unauthorized .net
Hello Dear Friends,
I have jwt token problem on my project. I want to do Authorization however, http 401 error was occured in my app. I want to enter the website by connecting NVS and the controller I wrote with WEBAPI.
How can I solve this error guys, Thank yoU.
I shared my codes below.
Here is my WebAPI Login Code
[HttpPost("Login")]
        public async Task<IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
        {
            LoginCommand loginCommand = new() { UserForLoginDto = userForLoginDto, IpAddress = GetIpAddress() };
            LoginDto result = await Mediator.Send(loginCommand);

            if (result.RefreshToken is not null) setRefreshTokenToCookie(result.RefreshToken);

            return Ok(result.CreateResponseDto());
        }

and this is my MVC controller code
[HttpPost]

        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel loginViewModel)
        {
            var response = await _client.PostAsJsonAsync("Auth/Login",loginViewModel);
            if (response.IsSuccessStatusCode)
            {
                //var body =await response.Content.ReadFromJsonAsync<LoginResponse>();
                var body=await response.Content.ReadAsStringAsync();
                LoginResponse loginResponse=JsonConvert.DeserializeObject<LoginResponse>(body);

                return RedirectToAction("Index", "Dashboard");

            }
            return View("Index",loginViewModel);

and my startup cs MVC code
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidAudience = builder.Configuration["Jwt:Audience"],
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

startup cs WEBAPI  code
builder.Services.AddControllers();
builder.Services.AddApplicationServices();
builder.Services.AddSecurityServices();
builder.Services.AddPersistenceServices(builder.Configuration);
//builder.Services.AddInfrastructureServices();
builder.Services.AddHttpContextAccessor();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(x =>
{
    x.LoginPath = "/Login";
});
TokenOptions? tokenOptions = builder.Configuration.GetSection("TokenOptions").Get<TokenOptions>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidIssuer = tokenOptions.Issuer,
        ValidAudience = tokenOptions.Audience,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey)
    };
});

builder.Services.AddSwaggerGen(opt =>
{
    opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer",
        BearerFormat = "JWT",
        In = ParameterLocation.Header,
        Description =
            "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345.54321\""
    });
    opt.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
                { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } },
            new string[] { }
        }
    });
});

ı tried change  [Authorize] from my dasboard
and am ı need change someting about this. Thanks For Helping


text:
Q: JavaScript Toggle not working with many elements with the same class attribute I am trying to toggle 'disable' for 'active' CSS class to make the fill property of some SVG change when it is clicked.
I am able to make the first element change correctly but when trying the same with the second and third SVGs it changes the color of the first one inside the first div.
HTML

       <svg onclick="toggleColor()" class="home__like disable heart">
           <use xlink:href="img/sprite.svg#icon-heart-full"></use>
       </svg>

       <svg onclick="toggleColor()" class="home__like disable heart">
           <use xlink:href="img/sprite.svg#icon-heart-full"></use>
       </svg>

       <svg onclick="toggleColor()" class="home__like disable heart">
           <use xlink:href="img/sprite.svg#icon-heart-full"></use>
       </svg>

CSS
.disable {
    fill: #fff;
}

.active {
    fill: $color-primary;
}

JavaScript
function toggleColor() {

    const toggleHeart = document.querySelector('.heart');

    if(toggleHeart.classList.contains('disable')) {
        toggleHeart.classList.remove('disable');
        toggleHeart.classList.add('active');
    } else {
        toggleHeart.classList.remove('active');
        toggleHeart.classList.add('disable');
    }
}

A: You're using .querySelector() which returns the first element in the document that matches the selector provided.
To get multiple elements, you'd need to use .querySelectorAll() which will return a static NodeList of elements that match the selector. At that point you need to loop through the NodeList and manipulate the classes.
However, since you're trying to target the event-invoking element, I think you could simplify it with a reference to the element.
function toggleColor(el, e) {
    el.classList.toggle('disable');
    el.classList.toggle('active');
}

And change your onclick handler to onclick="toggleColor(this,event);"
Here's a quick snippet:

function toggleColor(el, e) {
    el.classList.toggle('disable');
    el.classList.toggle('active');
}
.disable { color: #ccc }
.active  { color: #0095ee; }

    <svg class="disable" onclick="toggleColor(this,event);" viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="currentColor" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>

     <svg class="disable" onclick="toggleColor(this,event);" viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="currentColor" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>

     <svg class="disable" onclick="toggleColor(this,event);" viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="currentColor" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>

A: Why is this happening?
Since there are multiple elements with the class of heart, it doesn't know which element to perform the script on! It's like a teacher trying to call Bob, when the class contains 5 people named Bob.
How can we fix this?
You can change the function in onclick, by supplying the element's reference in the script, like so: onclick="myFunction(this)". Now in the javascript, you can do whatever you need with the element.
Try it! Run the example below!

function toggleColor(element) {

    toggleHeart = element;

    if(toggleHeart.classList.contains('disable')) {
        toggleHeart.classList.remove('disable');
        toggleHeart.classList.add('active');
    } else {
        toggleHeart.classList.remove('active');
        toggleHeart.classList.add('disable');
    }
}
.disable {
    color: blue;
}

.active {
    color: red;
}

    Click Me!

    Click Me!

    Click Me!

    Click Me!


text:
Q: Ingress gives 502 error If I run through the http load balancer example it works fine in my google container engine project.  When I run "kubectl describe ing" the backend is "HEALTHY".  If I then change the svc out to one that points to my app as shown here:
apiVersion: v1
kind: Service
metadata:
  name: app
  labels:
    name: app
spec:
  ports:
  - port: 8000
    name: http
    targetPort: 8000
  selector:
    name: app
  type: NodePort

The app I'm running is django behind gunicorn and works just find if I make that a load balancer instead of a NodePort.
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: main-ingress
spec:
  backend:
    serviceName: app
    servicePort: 8000

Now when I run "kubectl describe ing" the backend is listed as "UNHEALTHY" and all requests to the ingress IP give a 502.

*

*Is the 502 a symptom of the bad health check?

*What do I have to do to make the health check pass?  I'm pretty sure the container running my app is actually healthy.  I never set up a health check so I'm assuming I have to configure something that is not configured, but my googling hasn't gotten me anywhere.

A: After a lot of digging I found the answer:
According to the requirements here: https://github.com/kubernetes/kubernetes/tree/master/cluster/addons/cluster-loadbalancing/glbc#prerequisites the application must return a 200 status code at '/'.  Because my application was returning a 302 (redirect to login), the health check was failing.  When the health check fails, the ingress resource returns 502.

A: I just wanted to supplement the accepted answer with a more concrete explanation of why a health check on / is needed, even though livenessProbe and readinessProbe may be set up and working on the containers in the pods.
I had originally thought they were the same thing, but they're not.
The probes are used by the kubernetes engine to manage individual containers within a service. Whereas the health check on / is at the service level, and is part of the GCP load balancer contract. It's got nothing to do with kubernetes or containers per-se.
The reason it's needed with GKE is that the GCP load balancer is the default ingress controller. As stated in the docs, by default the GCP load balancer requires backing services to return a 200 on / to check if they're live so it can manage which ones to route to.
If you want to configure this health check endpoint:

*

*From GKE cluster version 1.17.6-gke.11 (currently in beta) you can configure it on the GCP load balancer. See docs here.

*Below 1.17.6-gke.11, you cannot configure it on the GCP load balancer. It has to be a 200 on /. The only option to configure it would be to use a different, more configurable ingress controller like the nginx one. I haven't used this myself, so can't point to any specifics on that.

A: There are two kind of health checks

*

*Kubernetes health checks

*GKE (or GCP) ingress/loadbalancer health checks

Kubernetes health checks
Kubernetes uses liveness, readiness and startup probes to check the health of the containers.
https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
In web applications usually a path that returns a success code for a HTTP GET request is used in health check probes. Any code greater than or equal to 200 and less than 400 indicates success. Any other code indicates failure.
GKE ingress/loadbalancer health checks
According to the GCP documentation

In GKE, an Ingress object defines rules for routing HTTP(S) traffic to applications running in a cluster. An Ingress object is associated with one or more Service objects, each of which is associated with a set of Pods. When you create an Ingress object, the GKE Ingress controller creates a Google Cloud HTTP(S) Load Balancer and configures it according to the information in the Ingress and its associated Services. This load balancer supports multiple backend services on a single URL map. Each of the backend services corresponds to a Kubernetes Service, and each backend service must reference a Google Cloud health check. This health check is different from a Kubernetes liveness or readiness probe because the health check is implemented outside of the cluster.

GKE uses the following procedure to create a health check for each backend service corresponding to a Kubernetes Service:

*

*If the Service references a BackendConfig CRD with healthCheck
information, GKE uses that to create the health check

*If the Service does not reference a BackendConfig CRD:

*

*GKE can infer some or all of the parameters for a health check if the Serving Pods use a Pod template with a container whose readiness probe has attributes that can be interpreted as health check parameters( see inferred parameters ). For this, the following conditions need to be satisfied

*

*The readiness probe's port number must match the serving Pod's containerPort

*The serving Pod's containerPort matches the Service's targetPort

*The Service's port must match the Ingress object's backend.servicePort

*If the Pod template for the Service's serving Pods does not have a container with a readiness probe whose attributes can be interpreted as health check parameters, the default values are used to create the health check

*

*When using default values for the GKE health check, a HTTP GET request to / path must return 200 status code. So make sure to define the / of the application.

*Even for use default values in health checks, Pod's containerPort , Service's targetPort and Ingress object's backend.servicePort must be matched. Also try to refer ports using port numbers instead of port names.
Note:
In Kubernetes health checks, any code greater than or equal to 200 and less than 400 consider as success. But In GKE ingress health checks only status code 200 consider as success. Due to this you may notice application has deployed and running fine but you get a 502.
Make sure application's health endpoints return 200 for unauthenticated requests. If authentication is enabled for health endpoints the request will be redirected and return a 300 status code.

A: In our case external port and internalport are mentioned as 5000 in values.yaml , but service is listening on 3000 port ( came to know after seeing pod logs ) so 502 bad gateway has been displayed .
Once I updated external port and internal port to 3000 and upgraded the deployment of that particular service ,able to see required output .

A: In my case the reason was not running ingress-controller pod, after cluster crash.
The easiest way to detect it is to list ingresses with
kubectl get ingress

Field address should be filled, in my case there was empty value
I listed pods for ingress-nginx namespace
kubectl get pods -n ingress-nginx

and found that pod not running
NAME                                       READY   STATUS             RESTARTS   AGE
nginx-ingress-controller-95db98cc5-rp5c4   0/1     CrashLoopBackOff   218        18h

the reason was that pod scheduled to master node where port 80 is busy with external nginx.
I simply deleted pod with
kubectl delete pod nginx-ingress-controller-95db98cc5-rp5c4 -n ingress-nginx

and it reschedulled to worker node.
That's it. 502 error gone

A: AWS ALB Ingress: The case where Deployment POD terminates TLS/SSL
One thing that's important: If the backend is implemented completely with Self-signed CERTS and is the entity terminating TLS, the Ingress object MUST know that fact in order to have its healthcheck to work properly as the default healthcheck is HTTP. For example, AWS's ALB will needs to know that in order to properly verify its own Healthcheck.

*

*Verify if the Deployment, whose is being selected by the NodePort service, is terminating TLS/SSL (443, or any other port)

*If the pod itself has a healthcheck spec, it should include that.

*If there's no healthcheck specified in the POD, then you can verify if the ingress object is setting the proper protocol for the Ingress healthcheck itself.

*

*For the case of AWS Ingress, it should use the annotations alb.ingress.kubernetes.io/healthcheck-protocol: HTTPS, and alb.ingress.kubernetes.io/healthcheck-path: /.

Ingress

*

*For this example, the Deployment whose service forwards traffic to terminates TSL (The pod itself serves traffic with a self-signed cert).

*For this reason, the healthcheck on / must specify the correct protocol and path.

# Example from https://docs.aws.amazon.com/eks/latest/userguide/alb-ingress.html
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    # https://kubernetes-sigs.github.io/aws-load-balancer-controller/guide/ingress/annotations/
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/load-balancer-attributes: access_logs.s3.enabled=false
    alb.ingress.kubernetes.io/backend-protocol: HTTPS
    alb.ingress.kubernetes.io/scheme: internet-facing
    alb.ingress.kubernetes.io/listen-ports: '[{"HTTPS": 443}]'
    alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:sa-east-1:806101772216:certificate/3db92ed3-5439-44e8-843d-fec0c9709501

    #### SOLUTION TO HTTPS Healthcheck From AWS ALB Ingress
    # https://stackoverflow.com/questions/64264889/argo-workflows-ui-not-working-with-aws-ingress-controller/64268995#64268995
    # As the backend is implemented with certificates, it MUST include the healthcheck using HTTPS
    alb.ingress.kubernetes.io/healthcheck-protocol: HTTPS
    alb.ingress.kubernetes.io/healthcheck-path: /
  name: argo-server-ingress
spec:
  rules:
  - host: argoflows-my-server.com
    http:
      paths:
      - pathType: Prefix
        path: "/*"
        backend:
          service:
            name: argo-server
            port:
              number: 2746
  tls:
  - hosts:
    secretName: argo-workflows-data-tls


text:
Q: Compiler segfault during explicit template instantiation on clang 11 The following explicit template instantiation results in compiler frontend segfault under LLVM clang++ 11.0 on x86_64-pc-windows-msvc, using the clang-cl interface with -std=c++17, regardless of optimization level.
A.h
template <typename T>
class A
{
public:

    T value;

    static constexpr auto address = &A<T>::value;
};

extern template class A<float>;

A.cpp
#include "A.h"

template class A<float>;

Note that since C++17 A::address is an inline variable so ODR-using cannot be a problem here.
The compiler behavior is obviously wrong, I already filed a report at the LLVM bug tracker.
Nevertheless, I am still curious about the actual correctness of the code.
Is it an undefined behavior which is handled incorrectly by the compiler, or the code itself is free of any problems and it's only about the compiler. Personally I don't find anything in the standard at the specification of explicit template instantiations which would suggest that the above code is wrong.
I don't think that the above is ill-formed, am I missing something?

A: Your example class A

// A.h
#pragma once

template <typename T>
class A {
public:
    T value;
    static constexpr auto address = &A<T>::value;
};

extern template class A<float>;

// A.cpp
#include "A.h"

template class A<float>;

used e.g. as in the following example (full demo here)
#include <iostream>
#include "A.h"

int main() {
    A<float> af{42.F};  // uses explicit instantiation: no implicit instantiation occurs.
    A<int> ai{43};      // implicit instantiation.
    std::cout << af.*A<float>::address   // 42
        << "\n" << ai.*A<int>::address;  // 43
}

is well-formed, and it is naturally a (ICE; internal compiler error) compiler bug that the compiler crashes. Unless your own program also contains uncarefully placed explicit specializations (see below) or is otherwise very different from the minimal example above, your own program should likewise be well-formed.

Details
[temp.explicit]/14 requires, for an explicit instantiation declaration [emphasis mine]:

If an entity is the subject of both an explicit instantiation
declaration and an explicit instantiation definition in the same
translation unit, the definition shall follow the declaration. An
entity that is the subject of an explicit instantiation declaration
and that is also used in a way that would otherwise cause an
implicit instantiation in the translation unit shall be the subject
of an explicit instantiation definition somewhere in the program;
otherwise the program is ill-formed, no diagnostic required. [...] An
explicit instantiation declaration shall not name a specialization of
a template with internal linkage.

These requirements are all fulfilled the example above, as are the requirements on the definition of A to precede the explicit definition of a specialization of it as per [temp.explicit]/5.
Finally, [temp.spec]/5 contains the additional requirements that [emphasis mine]:

For a given template and a given set of template-arguments,

*

*(5.1) an explicit instantiation definition shall appear at most once in a program,

*(5.2) an explicit specialization shall be defined at most once in a program, as specified in [basic.def.odr], and

*(5.3) both an explicit instantiation and a declaration of an explicit specialization shall not appear in a program unless the
explicit instantiation follows a declaration of the explicit
specialization. An implementation is not required to diagnose a
violation of this rule.

(5.1) is fulfilled as the explicit instantiation definition of A<float> is located within a single translation unit (a common ill-formed NDR error is to uncarefully place explicit instantiation definitions in headers, where the header is included in more than a single source file). (5.2) does not apply as there is no explicit specialization of A present (for any specialization), and (5.3) subsequently does not apply as there is no explicit specialization of the A<float> specialization that can conflict with the explicit instantiation definition of the latter.

Finally note that, as per [temp.local]/2, you may use the injected-class-name A when initializing the static data member address of the class template A:
template <typename T>
class A {
public:
    T value;
    static constexpr auto address = &A::value;
};


text:
Q: Laravel: Filter Child Collection Back Into Itself I'm writing a search function that utilises three parameters, make, model, and fueltype. The 'make' parameter is required so I am first selecting the make and its related models into a collection using the code below.

// Find Make and Models
$makeAndModels = Make::where('name', $request->make)->with('carmodels', 'carmodels.fueltype')->first();

At this point the collection looks like this:
{
    "id": 2,
    "name": "Toyota",
    "created_at": "2020-07-26T16:11:06.000000Z",
    "updated_at": "2020-07-26T16:11:06.000000Z",
    "carmodels": [
        {
            "id": 3,
            "name": "Prius",
            "make_id": 2,
            "fueltype_id": 2,
            "created_at": "2020-07-26T16:44:21.000000Z",
            "updated_at": "2020-07-26T16:44:21.000000Z",
            "fueltype": {
                "id": 2,
                "name": "Hybrid",
                "created_at": "2020-07-26T16:11:06.000000Z",
                "updated_at": "2020-07-26T16:11:06.000000Z"
            }
        },
        {
            "id": 4,
            "name": "Hilux",
            "make_id": 2,
            "fueltype_id": 3,
            "created_at": "2020-07-26T16:44:21.000000Z",
            "updated_at": "2020-07-26T16:44:21.000000Z",
            "fueltype": {
                "id": 3,
                "name": "Diesel",
                "created_at": "2020-07-26T16:11:06.000000Z",
                "updated_at": "2020-07-26T16:11:06.000000Z"
            }
        }
    ]
}

I then want to filter the 'carmodels' child collection by name and fueltypes, returning the filtered data back into its original self, rather than into new collection. These filters should only run if the additional params have been provided, the code I am currently using looks like this.
        //Filter Models By Additional Parameters

            //Model
            if ($request->model) {
                $model = $request->model;
                $makeAndModels->carmodels = $makeAndModels->carmodels->filter()->where('name', $model);
            }

For some reason filtering this way doesn't override the original collection, If I filter into a new child collection, for example,
        //Filter Models By Additional Paramters

            //Model
            if ($request->model) {
                $model = $request->model;
                $makeAndModels->carmodelsFiltered = $makeAndModels->carmodels->filter()->where('name', $model);
            }

It produces the following outcome, so I know the filter should work.
{
    "id": 2,
    "name": "Toyota",
    "created_at": "2020-07-26T16:11:06.000000Z",
    "updated_at": "2020-07-26T16:11:06.000000Z",
    "carmodelsFiltered": [
        {
            "id": 3,
            "name": "Prius",
            "make_id": 2,
            "fueltype_id": 2,
            "created_at": "2020-07-26T16:44:21.000000Z",
            "updated_at": "2020-07-26T16:44:21.000000Z",
            "fueltype": {
                "id": 2,
                "name": "Hybrid",
                "created_at": "2020-07-26T16:11:06.000000Z",
                "updated_at": "2020-07-26T16:11:06.000000Z"
            }
        }
    ],
    "carmodels": [
        {
            "id": 3,
            "name": "Prius",
            "make_id": 2,
            "fueltype_id": 2,
            "created_at": "2020-07-26T16:44:21.000000Z",
            "updated_at": "2020-07-26T16:44:21.000000Z",
            "fueltype": {
                "id": 2,
                "name": "Hybrid",
                "created_at": "2020-07-26T16:11:06.000000Z",
                "updated_at": "2020-07-26T16:11:06.000000Z"
            }
        },
        {
            "id": 4,
            "name": "Hilux",
            "make_id": 2,
            "fueltype_id": 3,
            "created_at": "2020-07-26T16:44:21.000000Z",
            "updated_at": "2020-07-26T16:44:21.000000Z",
            "fueltype": {
                "id": 3,
                "name": "Diesel",
                "created_at": "2020-07-26T16:11:06.000000Z",
                "updated_at": "2020-07-26T16:11:06.000000Z"
            }
        }
    ]
}

Anyone know of a way to filter a collection's child collection without creating a new one? Thanks in Advance.

A: You can filter them using the with() call using array as first parameter. Where you can query the relation, if you pass keys that are the with includes and closures that are the queries. These closures are pretty generic in your case and i have defined the it before the array as it is the same for both cases.
This is not the same as you now are querying the database, but this have way better performance as you do not have to get all the data out.
$model = $request->model;

$nameFilter = function ($query) use ($model) {
    $query->when($model, function ($query) use ($model) {
        $query->where('name', $model);
    });
};

$makeAndModels = Make::when($model, function ($query) use ($model) {
    $query->where('name', $model);
})->with(
    [
        'carmodels' => $nameFilter,
        'carmodels.fueltype' => $nameFilter,
    ]
)->first();

Update
To only filter the database when name is there, Laravel has the when() call, that simply only executes the query if a boolean condition is met.


text:
Q: Sufficient condition for set equality Just a simple question that will help me do the programming homework:
I've got two sets and need to check if they're equal. I've already implemented intersection and union methods, now I've got to implement a method which checks if $S_1$ and $S_2$ are equal.
So, instead of repeating the code, I'd like to use intersection and union methods.
Now, a math question: is $$|S_1 \cup S_2| = |S_1|$$ a sufficient condition to say two sets are equal?

A: No, the condition you wrote does not suffice: Not even $S_1\cup S_2=S_1$ ensures equality; it simply says that $S_2$ is a subset of $S_1$.
Now, if you know that $S_1\cup S_2=S_1\cap S_2$, do you see how to conclude equality of $S_1$ and $S_2$?
By the way, I assume you are working with finite sets? If so, then $|S_1\cup S_2|=|S_1\cap S_2|$ will suffice. This won't be enough if you want you condition to work for infinite sets as well.

A: No. For example let $S_2$ be the empty set, or any proper subset of $S_1$.  But the idea works fine as long as you add that $S_1$ and $S_2$ have the same number of elements.

A: Take $S_1 = \{1,2 \}$ and $S_2 = \emptyset$. Then $|S_1 \cup S_2| = |S_1|$ but $S_1 \neq S_2$.


text:
Q: Bulk file restore from Google Cloud Storage Accidentally run delete command on wrong bucket, object versioning is turned on, but I don't really understand what steps should I take in order to restore files, or what's more important, how to do it in bulk as I've deleted few hundreds of them.
Will appreciate any help.

A: To restore hundreds of objects you could do something as simple as:
gsutil cp -AR gs://my-bucket gs://my-bucket

This will copy all objects (including deleted ones) to the live generation,  using metadata-only copying, i.e., not require copying the actual bytes. Caveats:

*

*It will leave the deleted generations in place, so costing you extra storage.

*If your bucket isn't empty this command will re-copy any live objects on top of themselves (ending up with an extra archived version of each of those as well, also costing you for extra storage).

*If you want to restore a large number of objects this simplistic script would run too slowly - you'd want to parallelize the individual gsutil cp operations. You can't use the gsutil -m option in this case, because gsutil prevents that, in order to preserve generation ordering (e.g., if there were several generations of objects with the same name, parallel copying them would end up with the live generation coming from an unpredictable generation). If you only have 1 generation of each you could parallelize the copying by doing something like:
gsutil ls -a gs://my-bucket/** | sed 's/\(.\)\(#[0-9]\)/gsutil cp \1\2 \1 \&/' > gsutil_script.sh
This generates a listing of all objects (including deleted ones), and transforms it into a sequence of gsutil cp commands to copy those objects (by generation-specific name) back to the live generation in parallel. If the list is long you'll want to break in into parts so you don't (for example) try to fork 100k processes to do the parallel copying (which would overload your machine).


text:
Q: chroot, gpg-agent, and Ubuntu 18.04 For SFTP access to my server, I have created a sftp user that is limited to a working directory by chroot.
Match User sftp-user
    AuthorizedKeysFile /home/sftp-user/.ssh/authorized_keys
    ChrootDirectory /var/www/domain
    ForceCommand internal-sftp
    AllowTcpForwarding no
    X11Forwarding no

And this entry in /etc/passwd
sftp-user:x:1003:1003::/html:/usr/sbin/nologin

There were some issues with the key file, but setting an absolute path for that solved the issue. The SFTP login worked fine until - I do not exactly know - the nagios server monitoring was installed on the server (a VPS) and/or updates have been run, and the system has been rebooted.
Now, connection fails and the syslog shows this error:
systemd[7590]: gpgconf: running /usr/bin/gpg-agent failed (exitcode=2): General error
systemd[7590]: gpgconf: fatal error (exit status 1)

This error occurs no matter if the login is done via key file or password. So I have tried following the question gpg-agent says agent exists, but gpg says agent doesn't exist? to narrow down the problem.
$ gpg-agent --version
gpg-agent (GnuPG) 2.2.4
libgcrypt 1.8.1

When I started gpg-agent as user (not the sftp user), it creates a file in the home directory on the first run:
$ gpg -d demo-file.asc
gpg: keybox '/home/username/.gnupg/pubring.kbx' created

When I disable the chroot in /etc/ssh/sshd_config, the login works properly. So I assume, that some access fails in the chroot session. As the sftp user is not allowed to use a shell, I did not bind any directories into the sftp-user's home directory.

A: It actually was the .gnupg directory that could not be created. The home directory specified in /etc/passwd (/html) is relative during the SFTP session, but understood as absolute path during the login. Therefore...

*

*Creating a folder .gnupg in chroot+home = /var/www/domain/html did not (!) help.

*Creating a folder /html/.gnupg (.gnupg owned by sftp-user) removed the error message from /syslog.

To take care of further problems (of course, it did not work immediately), I started another sshd daemon in verbose mode and connected to this port .... but that would lead off topic here.
sudo /usr/sbin/sshd -d -p 3321


text:
Q: SSE comparisons not working as intended while doing a linear search over an array of integers in c++ I have the following code intended to execute a linear search through an array using streaming SIMD extensions in c++:
#include <iostream>
#include <emmintrin.h>

using namespace std;

bool sse2_search_array(int* arr, int size, int key) {
    int iterations;
    if (size % 16 == 0) {
        iterations = size / 16;
    }
    else {
        iterations = size / 16 + 1;
    }
    __m128i* arr_ = reinterpret_cast<__m128i*>(arr);  /*Cast to corresponding int type for 128 bit registers. Each __m128i
                                occupies 8 bits, so 16 integers can be processed simultaneously.*/
    __declspec(align(16)) int key_arr[16];
    fill_n(key_arr, 16, key);  /*fill key array with 16 keys (for SSE comparisons)*/
    __m128i* key_arr_ = reinterpret_cast<__m128i*>(key_arr);

    int result;
    /*Actual search begins here.*/
    for (int i = 0; i < iterations; i++, arr_++) {
        result = _mm_movemask_epi8(_mm_cmpeq_epi8( *key_arr_, *arr_));  /*Comparison of 2 16 bit arrays simultaneously.*/
        cout << "result: " << result << endl;
        if (result != 0) { return true; }
    }
    return false;

}

int main() {
    __declspec(align(16)) int example_array[16] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };

    cout << "found: " << sse2_search_array(example_array, 16, 128);
    cin.get();
}

It works but the example in the main function should return false since 128 is not in example_array, but sse2_search_arrayseems to always return true, and the value of result in the example is 1110111011101110b or 61166 and that does not make sense to me because I'm expecting it to be 0. So can somebody tell me what the problem is and how I can fix it? I am not very experienced with c++ and know very little of SSE.

A: Two major problems:
Never fill a scratch array just so you can load it as a vector:
__declspec(align(16)) int key_arr[16];
fill_n(key_arr, 16, key);  /*fill key array with 16 keys (for SSE comparisons)*/
__m128i* key_arr_ = reinterpret_cast<__m128i*>(key_arr);

Instead, use __m128i keyvec = _mm_set1_epi8(key);.  There are much faster ways to broadcast a byte to all positions of a vector than doing 16 scalar stores to memory and then a vector load (which will suffer from a store-fowarding stall).  Let the compiler pick for you by using _mm_set intrinsics instead of writing to local arrays.

int is 4 bytes (on all modern x86 compilers), but you apparently want to work with arrays of single-byte elements, since you're using _mm_cmpeq_epi8.  Your example_array is actually 16 * 4 bytes long:
__declspec(align(16)) int example_array[16] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };
// equivalent byte array (on little-endian x86):
uint8_t byte_array[16*sizeof(int)] = { 1,0,0,0,  2,0,0,0,  3,0,0,0, ... };

Your comments are often completely wrong, e.g. Comparison of 2 16 bit arrays simultaneously.  Perhaps you meant "byte"?

If you actually wanted to search arrays of int, use _mm_set1_epi32(key) and _mm_cmpeq_epi32.  A 16 byte vector holds four ints.  The movemask result is still based on bytes, but each group of 4 bits in the result will be the same.
See also the sse tag wiki and the x86 tag wiki for useful links.  The c++ tag wiki has a lot of good stuff for the language in general, since you said you're new to that, too.

IDK why you're getting hits for key=128; that doesn't seem to make sense unless there's even more wrong with your code that I didn't notice.
Your debugger should be able to show you what's in your __m128i variables.  Storing some temporaries in variables will make it easier to look at them with a C++ source-level debugger, instead of single-stepping the asm code.


text:
Q: How to use Command pattern by passing to it runtime params I have functionality that I am encapsulate on diff commands using Command pattern.
I am creating the command with the information and logic it need how ever I am getting some params only on runtime which I need to provide my commands
for example:
public class sendMessageToServerCommand implements Command {

    @Override
    public void execute(String msg){
          sendToServerTheMsg(msg);
    }
}

..
Command command=new sendMessageToServerCommand();
command.execute("msg I got on runtime");

Perhaps I shouldnt use command pattern and think about something else? suggestions ?
Thanks.

A: The Command pattern stipulates an object that can be executed with no arguments after its creation (for example: Runnable or Callable) however, there is nothing preventing arguments from being passed during creation; so you can simply move the msg argument from the execute() method to the command's constructor.
In a typical use of the Command pattern, commands are created in one place and executed in another. The creation logic is parameterized; the execution logic is not.


text:
Q: Send multiple files from Mongodb to view with gridFs Code can send one image file to view, but when I want to send many files, it gives error:
Error: Can't set headers after they are sent.
app.get('/api/upload', function (req, res) {

var arr = [];
var i =0;

gfs.files.find({}, {}).forEach(function (files) {

    if (files.length === 0) {
        return res.status(400).send({
            message: 'File not found'
        });
    }

        arr.push(files);

        res.writeHead(200, {'Content-Type': arr[i].contentType});

        var readstream = gfs.createReadStream({
            filename: arr[i].filename
        });

        arr.splice(i, 1 );

        readstream.on('data', function (data) {
            res.write(data);
        });

        readstream.on('end', function () {
            res.end();
        });

        readstream.on('error', function (err) {
            console.log('An error occurred!', err);
            throw err;
        });

});

});

So; How can I make the code send all images to view? One by one, or as one object?
Ps. Reason for splice is, that forEach push first item, first & second, first & second & third, etc.:
Value:
[ { _id: 5927bd80b4f177148865960d,
filename: '9m79o7R.jpg',
contentType: 'image/jpeg',
length: 796432,
chunkSize: 261120,
uploadDate: 2017-05-26T05:30:44.947Z,
aliases: null,
metadata: { objectId: '9m79o7R.jpg' },
md5: 'e58694132f00a7b5d2f623cdd45d36f6' } ]

Value:
[ { _id: 5927bd80b4f177148865960d,
filename: '9m79o7R.jpg',
contentType: 'image/jpeg',
length: 796432,
chunkSize: 261120,
uploadDate: 2017-05-26T05:30:44.947Z,
aliases: null,
metadata: { objectId: '9m79o7R.jpg' },
md5: 'e58694132f00a7b5d2f623cdd45d36f6' },
{ _id: 5927bdadb4f1771488659614,
filename: 'blue_sky-t2.jpg',
contentType: 'image/jpeg',
length: 43594,
chunkSize: 261120,
uploadDate: 2017-05-26T05:31:26.526Z,
aliases: null,
metadata: { objectId: 'blue_sky-t2.jpg' },
md5: 'feda400c51b0c37f7c3d2ba439f1c776' } ]


text:
Q: Is it possibly to automatically indent HTML source outputted by PHP? As a perfectionist, I like having valid & correctly indented HTML outputted by PHP.
I have a few complex webapps with IT-minded users, and they like to be able to View source and not see a garbled mess.
Currently I use this function I wrote:
function nl($tabs = 0)
{
    return "\r\n" . str_repeat("\t", $tabs);
}

Using it like so to add a newline and the required number of tabs:
if(array_key_exists('field', $row)){
    echo '<td>' . $row['field'] . '</td>' . nl(4);
}

Is there anything built-in to PHP, or is there a class I can use to do this indentation automatically?

A: When using output buffers you can use DOMDocument and set formatOutput to true before flushing the buffers to the client / browser.
ie:
libxml_use_internal_errors( TRUE );

$dom = new DOMDocument();
$dom->validateOnParse = FALSE;
$dom->preserveWhiteSpace = TRUE;
$dom->formatOutput = TRUE;
$om->loadHTML( mb_convert_encoding( ob_get_contents(), 'UTF-8' ) );

libxml_clear_errors();

/*
 perform any other operations on dom elements you wish
*/

$buffer = $dom->saveHTML();
ob_end_clean();
echo trim( $buffer );/* send data to client/browser */


text:
Q: NSSpeechSynthesizer and track duration This time I have a logic question. Hope someone of you could help me. Using the `NSSpeechSynthesizer' you can set the rate, i.e. 235 words per minute, 100 words per minute and so on...
I found that generally the average of words per minute is calculated using standardized word length of 5 characters per word, counting spaces and symbols too.
I need to automatically subdivide a long text in tracks with a pre-selected duration, let say 15 minutes per track.
How can we calculate the correct number of characters to pass for each 'split' to the speech engine?
My solution is as follow:
// duration is the number of minutes per track
numberOfWordsPerTrack = [rateSlider floatValue] * duration;
splits = [[NSMutableArray alloc] init];

finished = NO;
NSUInteger position = 0;
while( !finished ) {
    NSRange range;

    // the idea is: I take 5*numberOfWordsPerTrack characters
    // until the text allows me to select them
    range = NSMakeRange( position, 5*numberOfWordsPerTrack );
    if( range.location+range.length > mainTextView.string.length ) {
        // If there are not another full character track we get
        // the tail of the remaining text
        finished = YES;
        range = NSMakeRange( position, mainTextView.string.length-position );
    }

    // Here we get the track and add it to the split list
    if( range.location+range.length <= mainTextView.string.length ) {
        currentSplit = [mainTextView.string substringWithRange:range];
        [splits addObject:currentSplit];
    }

    position += range.length;
}

The problem with this solution is that the track duration is not correct. It is not quite far from the desired value, but it is not right. For example, using 235 words per minute with duration of 50 minutes, I have 40 minutes per track. If I set 120 minutes per track, I have 1h:39m per track... and so on...
Where do you think is the logic error?
EDIT AFTER JanX2 REPLY
Well, while randomly thinking I came to the following hypotesis Could you tell me what do you think about that before its implementation, because it is not a light change in my code
If I used the speechSynthesizer:willSpeakWord:ofString: delegate member I could test the .aiff file size frequently, i.e. before speaking the next word (real word, not standardized). Because we know the Hzs, bits and channels those file are created with by synthesizer and because we know they are not compressed, we could gain some guess about the current length of the track.
The biggest drawback of this solution could be che continuous disk access, that can highly degrade performance.
What do you think?

A: I can only guess, but the heuristic you use will include "silent" characters. Why not try an compensate for the measured error? You appear to have an error that is pretty much linear so you could factor that into your calculation:
40 / 50 = 80%
99 / 120 = 82.5%
So you have an error of about 17.5-20%. Just multiply the time you calculate above by 0.8 or 0.825 and you are getting closer. This is crude, but you are already using a heuristic.
BTW: You probably should consider using -enumerateSubstringsInRange:options:usingBlock: to achieve sentence granularity instead of arbitrary word splits.
Using "-speechSynthesizer:willSpeakWord:ofString:" causes bigger issues: in my experience it can be out of sync with the position in the file being written by several hundred ms up to several seconds. And speaking up the next word seems to have problems when used with the Nuance voices.


text:
Q: Gravitational potential energy of any spherical distribution The general formula to get the potential energy of any spherical distribution is this :
\begin{equation}\tag{1}
U = - \int_0^R \frac{GM(r)}{r} \, \rho(r) \, 4 \pi r^2 \, dr,
\end{equation}
where $M(r)$ is the mass inside a shell of radius $r < R$.  It is easy to get the gravitational energy of a uniform sphere of mass $M$ and radius $R$ :
\begin{equation}\tag{2}
U = -\, \frac{3 G M^2}{5 R}.
\end{equation}
In general, for any spherical distribution of total mass $M$ and exterior radius $R$, we can write this :
\begin{equation}\tag{3}
U = -\, \frac{k \, G M^2}{R},
\end{equation}
where $k > 0$ is a constant that depends on the internal distribution.  $k = \frac{3}{5}$ for the uniform distribution.  For a thin spherical shell of radius $R$ (all mass concentrated on its surface), we can get $k = \frac{1}{2}$.
Now, I suspect that for all cases :
\begin{equation}\tag{4}
\frac{1}{2} \le k < \infty.
\end{equation}
Physically, this makes sense.  But how to prove this from the general integral (1) ?

To simply things a bit, we may introduce the dimensionless variable $x = r/R  \le 1$, and defines relative mass $\bar{M}(x) \equiv M(r)/M \le 1$ and relative density $\bar{\rho}(x) = \rho(r) / \rho_{\text{average}}$, where $\rho_{\text{average}} = 3 M/4 \pi R^3$.  Thus, integral (1) takes the following form :
\begin{equation}\tag{5}
U = -\, \frac{3 G M^2}{R} \int_0^1 \bar{M}(x) \, \bar{\rho}(x) \, x \, dx.
\end{equation}
The last integral is $\frac{k}{3}$.  I'm not sure this may help to prove (4).

A: Start by writing that:
$$\tag1 M=\int^R_0 \rho(r)4\pi r^2 dr = \int^R_0 \frac{dM}{dr}dr.$$
From (1), we can identify that:
$$\tag2 \frac{dM}{dr}dr = 4\pi r^2 \rho(r)dr.$$
Now let's return to your equation (1):
$$U = - \int_0^R \frac{GM(r)}{r} \, \rho(r) \, 4 \pi r^2  dr,$$
using equation (2), this becomes:
$$U=-G\int_0^R \frac{M(r)}{r} \frac{dM}{dr}dr.$$
Let's concentrate on just the integral part, and call it $I$ for concreteness, $$I=\int_0^R \tag{3}\frac{M(r)}{r} \frac{dM}{dr}dr.$$  Aha! This looks like something we can integrate by parts.  Let's set $u=\frac{M(r)}{r}$, and $v'=\frac{dM}{dr}$.  Then $$u'=-\frac{M(r)}{r^2} + \frac{1}{r}\frac{dM}{dr}.$$  Continuing with IBP, we get:
$$I=\Bigg[\frac{M(r)}{r}M(r)\Bigg]^R_0-\int^R_0 \Big(-\frac{M(r)}{r^2} + \frac{1}{r}\frac{dM}{dr}\Big)M(r) dr.$$
Let's look at solely the integral part, calling it $J$:
$$J=-\int^R_0 \frac{M^2(r)}{r^2} dr  + \underbrace{\int^R_0 \frac{M(r)}{r}\frac{dM}{dr} dr}_{\textrm{we know this integral, it's }I}.$$
So now we have that:
$$I=\Bigg[\frac{M^2(r)}{r}\Bigg]^R_0 + \int^R_0 \frac{M^2(r)}{r^2} dr - I,$$ and so:
$$2I= \Bigg[\frac{M^2(r)}{r}\Bigg]^R_0 + \int^R_0 \Bigg(\frac{M(r)}{r}\Bigg)^2 dr.$$
For the case of non-pathological $M$, that is $M(0)=0$, we get:
$$I=\frac{M^2}{2R} + \frac{1}{2}\int^R_0 \Bigg(\frac{M(r)}{r}\Bigg)^2 dr.$$
Hence we can identify from this that $U$ has the limit of $-\frac{GM^2}{2R}$, and from that we subtract the integral of something positive definite.
I believe this proves (to physicist standards) your conjecture about $k$.

Request of simplifying the process:
Let's just consider with no dimensions the integral:
$$K=\int^X_0 \frac{f(x)  f'(x)}{x} dx.$$
Take: $$g(x)=\frac{f^2(x)}{2x},$$
then taking the derivative:
$$g'(x) = \frac{f(x) f'(x)}{x}-\frac{f^2(x)}{2 x^2}.$$
We can recognise our original integral in this mix, and so integrating $g'(x)$ will give us our integral, less $\int^X_0 \frac{f^2(x)}{2 x^2} dx$, and so we can write:
$$K=\big[g(x)\big]^X_0 + \frac{1}{2}\int^X_0 \frac{f^2(x)}{x^2}dx= \Bigg[\frac{f^2(x)}{2 x}\Bigg]^X_0 + \frac{1}{2}\int^X_0 \bigg( \frac{f(x)}{x} \bigg)^2 dx.$$
Giving us the result we wanted.  As IBP is always the inverse of the product rule, with a little bit of thought you can generally figure out the original function.  However if I'd just posted this last 4-step proof, I think you'd have just thought I was a wizard...

A: Your claim, $k\in\bigg[\dfrac{1}{2},\infty\bigg)$, is true.
I will provide a hand-wavy proof that physicists might accept as a proof but mathematicians will surely ridicule as a conjecture. So, here it goes:
If invert the sign of your integral (and we will set $4\pi G=1$) then it reads:
$$\displaystyle\int\dfrac{M_{\text{in}}(r)}{r}\rho(r) r^2 dr \tag{1}$$
This is identical to the expression (provided that we have set $4\pi\epsilon_0=1)$ for the self-potential energy of a spherical charge distribution if we identify $M_{\text{in}}(r)$ with the charge within radius $r$ and $\rho(r)$ with the charge density at radius $r$. Now, we know that if we put a certain charge on a metallic spherical ball then, in its equilibrium state, the charge distribution will be so that it minimizes the self-potential energy that a charge distribution of total charge $M$ can have when distributed within a radius $R$. But we know, according to Gauss's law, that the charge gets distributed in the form of a spherical shell on the surface of the spherical ball. Thus, the minimum value of $(1)$ will be when all the charge is at $R=1$. We know, as you calculated, the self potential energy in this case becomes $\dfrac{1}2\dfrac{M^2}R$. Of course, the maximum value $(1)$ can have is indefinitely large corresponding to larger and larger fraction of charge being put nearer and nearer to the center.
In the gravitational case, the additional minus sign makes you read minimum of the above explanation as maximum and vice-versa. But since you have kept the negative sign outside of the definition of $k$ (i.e. you multiply $k$ with a minus to get the final $U$), you can very directly see that $k\in\bigg[\dfrac{1}{2},\infty\bigg)$ holds.


text:
Q: Finding which COLUMN has a max( value per row MSSQL
Table looks like so
ID    1   | 2  |  3  |  4  |  5
AA1   1   | 1  |  1  |  2  | 1

any clues on how I could make a query to return
ID  |  MaxNo
AA1 | 4

, usign the above table example? I know I could write a case blah when statement, but I have a feeling there's a much simpler way of doing this

A: You can use UNPIVOT to get these comparable items, correctly1, into the same column, and then use ROW_NUMBER() to find the highest valued row2:
declare @t table (ID char(3) not null,[1] int not null,[2] int not null,
                 [3] int not null,[4] int not null,[5] int not null)
insert into @t (ID,[1],[2],[3],[4],[5]) values
('AA1',1,1,1,2,1)

;With Unpivoted as (
select *,ROW_NUMBER() OVER (ORDER BY Value desc) rn
from @t t UNPIVOT (Value FOR Col in ([1],[2],[3],[4],[5])) u
)
select * from Unpivoted where rn = 1

Result:
ID   Value       Col                       rn
---- ----------- ------------------------- --------------------
AA1  2           4                         1

1 If you have data from the same "domain" appearing in multiple columns in the same table (such that it even makes sense to compare such values), it's usually a sign of attribute splitting, where part of your data has, incorrectly, been used to form part of a column name.
2 In your question, you say "per row", and yet you've only given a one row sample. If we assume that ID values are unique for each row, and you want to find the maximum separately for each ID, you'd write the ROW_NUMBER() as ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Value desc) rn, to get (I hope) the result you're looking for.

A: You can use a cross apply where you do max() over the columns for one row.
select T1.ID,
       T2.Value
from YourTable as T1
  cross apply
    (
    select max(T.Value) as Value
    from (values (T1.[1]),
                 (T1.[2]),
                 (T1.[3]),
                 (T1.[4]),
                 (T1.[5])) as T(Value)
    ) as T2

If you are on SQL Server 2005 you can use union all in the derived table instead of values().
select T1.ID,
       T2.Value
from YourTable as T1
  cross apply
    (
    select max(T.Value) as Value
    from (select T1.[1] union all
          select T1.[2] union all
          select T1.[3] union all
          select T1.[4] union all
          select T1.[5]) as T(Value)
    ) as T2

SQL Fiddle


text:
Q: service keep crashing on OnDestroy() I'm creating a service that runs a mediaplayer for a set period of time.This service gets a constant value that I defined in another class and based on that the duration of the playing is determined.
I looked all over the web but couldn't find a solution or a similar problem , spent hours trying to no avail
  package com.quantyam.sleepbaby.sleepbaby;

 import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

 public class ContinousService extends IntentService {

private static final String TAG = "HelloService";
MediaPlayer player;
private boolean isRunning = false;
int time = 0;
Thread runner;
boolean keepplaying=true;

Handler mHandler = new Handler();

boolean keepgoiong = true;

public ContinousService() {
    super("ContinousPlayer");
}

private void sendMessageToActivity(int msg) {
    Intent intent = new Intent("intentKey");

    intent.putExtra("current_timing", msg);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

@Override
public void onCreate() {
    Log.i(TAG, "Service onCreate");

    isRunning = true;
}

public static String
        ACTION_CONTINOUS_PLAY = "";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    System.out.println("******************************************* selected DUration  = " + Constant.PlayDuration);
    Log.i(TAG, "Service onStartCommand");

    //Creating new thread for my service
    //Always write your long running tasks in a separate thread, to avoid ANR
    new Thread(new Runnable() {

        @Override
        public void run() {
            runner = Thread.currentThread();

            //Your logic that service will perform will be placed here
            //In this example we are just looping and waits for 1000 milliseconds in each loop.
            while (keepgoiong) {
                try {
                    Thread.sleep(1000);

                    startplaying();
                    time++;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (isRunning) {
                    Log.i(TAG, "Service running and time is = " + time);
                }
            }

            //Stop service once it finishes its task
            stopSelf();
        }
    }).start();

    return Service.START_STICKY;
}

public void startplaying() {

    try {

        if(keepplaying) {
            if (player == null) {
                AssetFileDescriptor afd = getAssets().openFd("music/" + Constant.SelectedMusic);
                player = new MediaPlayer();
                player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                player.prepare();
                player.start();
                System.out.println("============================= player Started!");
            }

            final int duration = Integer.parseInt(Constant.PlayDuration) * 15;
            int timeleft = duration - time;
            sendMessageToActivity(timeleft);
            System.out.println("============================= time left = " + timeleft);
            if (player.isPlaying() && timeleft > 0) {

            } else if (!player.isPlaying() && timeleft > 0) {
                System.out.println("================================== Run Again!");

                //    player.prepare();
                player.start();
            } else if (player.isPlaying() && timeleft <= 0) {

                System.out.println("============================= Time is up!");
                player.stop();
                keepplaying=false;
                keepgoiong = false;

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

@Override
public IBinder onBind(Intent arg0) {
    Log.i(TAG, "Service onBind");

    return null;
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {

}

Handler handler = new Handler();

@Override
public void onDestroy() {
    keepgoiong = false;
    isRunning=false;
    keepplaying=false;
    player.stop();
 super.onDestroy();
 //   stopSelf();

    Log.i(TAG, "Service onDestroy");
}

}
when the time is up I call stopSelf() but everytime I get the following error message :
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.quantyam.sleepbaby.sleepbaby, PID: 6550
              java.lang.RuntimeException: Unable to stop service com.quantyam.sleepbaby.sleepbaby.ContinousService@cbde8b0: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Looper.quit()' on a null object reference
                  at android.app.ActivityThread.handleStopService(ActivityThread.java:3732)
                  at android.app.ActivityThread.-wrap30(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1745)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6692)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Looper.quit()' on a null object reference
                  at android.app.IntentService.onDestroy(IntentService.java:138)
                  at com.quantyam.sleepbaby.sleepbaby.ContinousService.onDestroy(ContinousService.java:153)
                  at android.app.ActivityThread.handleStopService(ActivityThread.java:3715)
                  at android.app.ActivityThread.-wrap30(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1745)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6692)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

my code https://codeshare.io/5MJEVQ

A: An IntentService runs on its own thread.
So what you are doing is starting a thread that starts another thread that starts the media player and waits before calling stopSelf() on the first thread.
An intent service is only available for as long as it has work.
If the intent service launches another thread... its work is done and it will go away.
When you call the stopSelf() method your Intent service has already gone away because it started the thread and has completed its work...
I would first suggest that when the intent service starts you start the media player. Then use a PostDelayed runnable to stop the media player when it is finished. Something like below. Note: that this will still not work as is because the IntentService will finish its work once it starts the postDelayed Runnable. Solution is to use a Service instead of an IntentService.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    System.out.println("******************************************* selected DUration  = " + Constant.PlayDuration);
    Log.i(TAG, "Service onStartCommand");
    startMediaPlayer();
    new Handler().postDelayed(new Runnable() {
    public void run () {
        stopSelf();
        }
    }, playDuration);
    return Service.START_STICKY;
}

I would suggest that you use a Service instead of an IntentService.
Here is an example of a media player in a service. It uses state and intents to receive actions from UI and Uses Broadcast receivers to update ui when needed.


text:
Q: Report Viewer doesn't show any data after publish Hello I'm using C# 2010 and sql server compact edition 3.5 to build my database, and I use report wizard to generate a report from my database, but unfortunately after I published the app, my report viewer doesn't show anything even I have inserted a new record. Here is my code to simply show data on report viewer :
this.jadwalkuliahTableAdapter.Fill(this.Dataset.jadwalkuliah);

        this.reportViewer1.RefreshReport();

Note : report viewer shows data from my database while debugging process.

A: Your missing ReportDataSource:
this.reportViewer.LocalReport.DataSources.Clear();
DataTable dt = new DataTable();
dt = this.inputValuesTableAdapter.GetData();

Microsoft.Reporting.WinForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WinForms.ReportDataSource(dt.TableName, dt);

this.reportViewer.LocalReport.DataSources.Add(rprtDTSource);
this.reportViewer.RefreshReport();

Check this site below:
how can I load datatable as ReportDataSource? SO
Building Reports from a DataSet using ReportViewer c-sharp corner
Creating Dataset Dynamically in c# and passing to Report Viewer.. asp.net forum
Best Regards


text:
Q: Zxing Xamarin-forms Autofocus I am using Zxing to scan barcode in Xamarin forms App ,
The problem is Autofocus works only once when the scanpage Appeared ,
I tried to add timer as below  Code also not worked ,
and I noted when I change the application and return to it (in scan page ) Auto focus works perfect ,
I also added Button to Autofocus to overlay , it's fired but camera didn't focus
any advise ?
 scanPage.AutoFocus();
            TimeSpan ts = new TimeSpan(0, 0, 0, 10, 0);
            Device.StartTimer(ts, () =>
            {
                if (scanPage.IsScanning)
                {
                    scanPage.AutoFocus();
                }
                return true;
            });

A: Don't use a ScannerPage.
Use their MobileBarcodeScanner.
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
var result = await scanner.Scan();

From documentation: https://github.com/Redth/ZXing.Net.Mobile#usage


text:
Q: Save contents of those files which contain a specific known string in an single .txt or .tmp file using perl I'm trying to write a perl script where I'm trying to save whole contents of those files which contain a specific string 'PYAG_GENERATED', in a single .txt/.tmp file one after another. These file names are in a specific pattern and this pattern is 'output_nnnn.txt' where nnnn is 0001,0002 and so on. But I don't know how many number of files are present with this 'output_nnnn.txt' name.
I'm new in perl and I don't know how I can resolve this issue to get the output correctly. Can anyone help me. Thanks in advance.
I've tried to write perl script in different ways but nothing is coming in output file. I'm giving here one of those I've tried. 'new_1.txt' is the new file where I want to save the expected output and "PYAG_GENERATED" is that specific string I'm finding for in the files.
open(NEW,">>new_1.txt") or die "could not open:$!";
$find2="PYAG_GENERATED";
$n='0001';
while('output_$n.txt'){
    if(/find2/){
    print NEW;
    }
    $n++;
}
close NEW;

I expect that the output file 'new_1.txt' will save the whole contents of the the files(with filename pattern 'output_nnnn.txt') which have 'PYAG_GENERATED' string at least once inside.

A: Well, you tried I guess.
Welcome to the wonderful world of Perl where there are always a dozen ways of doing X :-) One possible way to achieve what you want. I put in a lot of comments I hope are helpful. It's also a bit verbose for the sake of clarity. I'm sure it could be golfed down to 5 lines of code.
use warnings;  # Always start your Perl code with these two lines,
use strict;    # and Perl will tell you about possible mistakes

use experimental 'signatures';

use File::Slurp;

# this is a subroutine/function, a block of code that can be called from
# somewhere else. it takes to arguments, that the caller must provide

sub find_in_file( $filename, $what_to_look_for )
{
    # the open function opens $filename for reading
    # (that's what the "<" means, ">" stands for writing)
    # if successfull open will return we will have a "file handle" in the variable $in
    # if not open will return false ...
    open( my $in, "<", $filename )
        or die $!; # ... and the program will exit here. The variable $! will contain the error message

    # now we read the file using a loop
    # readline will give us the next line in the file
    # or something false when there is nothing left to read
    while ( my $line = readline($in) )
    {
        # now we test wether the current line contains what
        # we are looking for.
        # the index function gives us the index of a string within another string.
        # for example index("abc", "c") will give us 3
        if ( index( $line, $what_to_look_for ) > 0 )
        {
            # we found what we were looking for
            # so we don't need to keep looking in this file anymore
            # so we must first close the file
            close( $in );

            # and then we indicate to the caller the search was a successfull
            # this will immedeatly end the subroutine
            return 1;
        }
    }

    # If we arrive here the search was unsuccessful
    # so we tell that to the caller
    return 0;
}

# Here starts the main program
# First we get a list of files
# we want to look at
my @possible_files = glob( "where/your/files/are/output_*.txt" );

# Here we will store the files that we are interested in, aka that contain PYAG_GENERATED
my @wanted_files;

# and now we can loop over the files and see if they contain what we are looking for
foreach my $filename ( @possible_files )
{
    # here we use the function we defined earlier
    if ( find_in_file( $filename, "PYAG_GENERATED" ) )
    {
        # with push we can add things to the end of an array
        push @wanted_files, $filename;
    }
}

# We are finished searching, now we can start adding the files together
# if we found any
if ( scalar @wanted_files > 0 )
{
    # Now we could code that us ourselves, open the files, loop trough them and write out
    # line by line. But we make life easy for us and just
    # use two functions from the module File::Slurp, which comes with Perl I believe
    # If not you have to install it
    foreach my $filename ( @wanted_files )
    {
        append_file( "new_1.txt", read_file( $filename ) );
    }

    print "Output created from " . (scalar @wanted_files) . " files\n";
}
else
{
    print "No input files\n";
}

A: use strict;
use warnings;
my @a;
my $i=1;
my $find1="PYAG_GENERATED";
my $n=1;
my $total_files=47276; #got this no. of files by writing 'ls' command in the terminal
while($n<=$total_files){
open(NEW,"<output_$n.txt") or die "could not open:$!";
my $join=join('',<NEW>);
$a[$i]=$join;
#print "$a[10]";
$n++;
$i++;
}
close NEW;
for($i=1;$i<=$total_files;$i++){
    if($a[$i]=~m/$find1/){
    open(NEW1,">>new_1.tmp") or die "could not open:$!";
    print NEW1 $a[$i];
    }
}
close NEW1;


text:
Q: EJB Bean passivation I have read that when ejbPassivate() is called Stateful Session Beans are usually evicted but Entity Beans and Stateless Beans are pooled which means they are not appilicable for passivation.
In another article I have read that activation and passivation is applicable only for Stateful Session Beans and Entity Beans which is a contrast to the claim that Entity Beans and Stateless Beans are pooled.
For what beans does the passivation apply and what does really happen when they do?

A: Passivation and Activation only apply to EJBs that have state, namely stateful session beans and entity beans.
Passivation is the process by which any state a given bean has is moved into storage.
Activation is the process by which any state that a given bean previously had is loaded from storage.
This mechanism is needed because the EJB contain creates a pool of each bean type but gives the illusion that there are an infinate number of each bean, loading and storing them using the ejbActive and ejbPassivate methods respectively as needed.
The full life-cycle of each bean type is described here:
Stateless Session Bean
Stateful Session Bean
Entity Bean


text:
Q: Thread Static variables for asynchronous operations in .NET Is there any way to have ThreadStatic variables be transferred from one thread to another?  I have a bunch of ThreadStatic variables, and now that I am converting my operation to be asynchronous, I want to be able to "transfer" them from the first thread (where they are set) to the callback thread (where they will be read).  Is this possible?

A: No. You need to keep the context of the operation with the asynchronous call. That's what the "state" parameter is for on most asynchronous calls.
ThreadStatic variables can be useful in some situations, but I'm generally wary of them. Unless you really know that you don't need any kind of thread agility, it's better to keep the state in a more explicit fashion.

A: The best approach for this would be to pass your operation some object, one which it can set your threadstatic variable prior to calling back.  There is no way to directly access the threadstatic variable from the calling thread.
That being said, I'd rethink your design.  If you want the variable to be available from multiple threads, it probably shouldn't be a threadstatic variable.  It probably should be managed by some other means.

A: If you need to do so, you probably don't want them to be ThreadStatic. You could make a static Dictionary<int,VarType> and map thread IDs to variables.

A: It seems to me that the best way would be to use the state parameter, as Jon said. However, if necessary, you could look at System.Runtime.Remoting.Contexts.Context.


text:
Q: how to read with Jquery and element readonly for django
see the image plx
there are some readonly field that i set up on django, but i want to read the values using Jquery but really idk how to do it, i want to do it cuz depending of the value that is set on field "tipo" i want a make some values visibles or not.
let tipo_persona_check = function(){
    if ($('#id_tipo').val() == 'fisica'){
        $('.field-empresa').hide();
        $('label[for=id_persona').text('Suscriptor');
    }else{
        $('label[for=id_persona').text('Apoderado');
        $('.field-empresa').show();
    }

in this case im hidding or showing field empresa depending of the value of id_tipo, but when it is on readonly, this id not exist, there is just a span class called readonly (for all readonly) with the value, but idk how to get from it, i need to know if the value is "fisica" or another from the readonly field tipo, to do things.
any ideas?

A: I did not check whether the ID is really visible when this is the case
We assume that the ID is not seen.
The solution is that you can add an input in that section so that you can find the ID from it.

admin.py

@admin.register(SomeModel)
class SomeModelAdmin(admin.ModelAdmin):
    def id_field(self, obj):
        return mark_safe(f"<input type='hidden' id='ID' value='{obj.pk}'>")
    readonly_fields = ["id_field"]

and in you js file:
id = document.getElementById('ID').value


text:
Q: How to verify a JWT on a workstation using .NET Is it possible for a desktop application verify that a JWT is valid and do so using .NET?

A: You can do this with System.IdentityModel.Tokens.Jwt.
Install the nuget package
PM> Install-Package System.IdentityModel.Tokens.Jwt
and then you can use the JwtSecurityTokenHandler class like this
var handler = new JwtSecurityTokenHandler();
handler.ValidateToken(tokenString, param, out validatedToken);


text:
Q: ORMlite not returning the object I just saved Here is my code that fails ( it is running within an activity and the DB helper creates the WishList object fine in the database )
DatabaseHelper helper = DatabaseHelper.getInstance( getActivity() );
int savedID = 0;
WishList wl = new WishList();
wl.setName("abc");
try {
    savedID = helper.getWishListDao().create(wl);
    WishList wl_saved = helper.getWishListDao().queryForId( savedID );
    wl_saved.getId();
} catch (SQLException e) {
    e.printStackTrace();
}

Here is my entity.  The ID field is auto generated.
@DatabaseTable
public class WishList {
    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField( canBeNull = false , unique = true )
    private String name;

    @ForeignCollectionField
    private ForeignCollection<WishItem> items;
    ...

What is wrong is the ID that is generated in the Database is not the same one that that ORMlite returns in the call below.  It returns 1.
 savedID = helper.getWishListDao().create(wl);

The ID in the database is actually 37.  Any ideas what I may be doing wrong?
Using version 4.41

A: ORMLite's Dao.create(...) method does not return the ID of the newly created object but the number of rows in the database that were changed – usually 1.  Here are the javadocs for Dao.create(...).

Create a new row in the database from an object. If the object being created uses DatabaseField.generatedId() then the data parameter will be modified and set with the corresponding id from the database. ...
  Returns: The number of rows updated in the database. This should be 1.

When ORMLite creates the object, the generated ID is then set to the id field afterwards.  To find the ID of your new object you get it from the object itself:
// create returns 1 row changed
helper.getWishListDao().create(wl);
// the id field is set on the w1 object after it was created
savedID = w1.getId();


text:
Q: GCD->blocks->C++->SQLCipher: Sqlite3MemMalloc memory does not release after task completion I am working on database application and using SQLCipher for database encryption. I am using GCD serial queue for all database related operation and manual memory management. Below is code snippet for my database related operations. I have more methods like saveRecordData: which calls the executeOnGCD: for different types of records.
-(void)saveRecordData:(NSArray *)dataObjects{
    [self executeOnGCD:^{
        std::vector<RecordData> list;

        for(id object in dataObjects){
            RecordData recordDataObject(/*create c++ data object*/)
            list.push_back(recordDataObject);
        }

        DataBaseManager::GetInstance()->saveData(list);
    }];
}

-(void)executeOnGCD:(void (^)())block{
    __block UIBackgroundTaskIdentifier task = UIBackgroundTaskInvalid;

    task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:task];
        task=UIBackgroundTaskInvalid;
    }];

    void (^executionBlock)() = ^(){
        @autoreleasepool {
            block();
            [[UIApplication sharedApplication] endBackgroundTask:task];
            task=UIBackgroundTaskInvalid;
        }
    };
    //dataManagerQueue is serial queue.
    dispatch_async(self.dataManagerQueue, executionBlock);
}

Here DataBaseManager is C++ class which performs actual database insert. DataBaseManager's saveData implementation is as below.
void saveData(std::vector<RecordData> list) {
    for(RecordData record : list)
    {
        sqlite3_stmt * statement = nullptr;

        if(sqlite3_prepare_v2(m_dbConnection, INSERT_STATEMENT, -1, &statement, NULL) == SQLITE_OK)
        {
            //Bind parameters
            int index = sqlite3_bind_parameter_index(statement, COLUMN1);
            sqlite3_bind_int(statement, index, value1);

            index = sqlite3_bind_parameter_index(statement, COLUMN2);
            sqlite3_bind_int(statement, index, value2);

            /*Bind other parameters*/

            sqlite3_step(statement);
        }
        sqlite3_finalize(statement);
    }
}

When my application saves 80k+ records using saveData function, there is  memory allocation difference between when the operation started and when operation ended. Instruments suggest there is still memory allocated by SQLCipher which is not released even after the 5 mins of operation completion. As shown in below image at the start of the operation memory allocation was 1.90mb and after completion of task memory reduces to 6.6mb not to 1.90mb

Also once the operation completed, memory reduce very slowly and takes around 6 mins to reduce memory from 20mb to 6.6mb.
my questions are
1)why memory did not drop to ~1.90mb after completion of task? Is this something related to using c++ objects in GCD?
2) Why it takes ~6min to reduce memory from 20mb to 6.6mb? Does GCD release memory slowly?
3) I also see _dispatch_alloc_try_create_heap block allocated by libdispatch.dylb, which is also not released after operation completion.
4) Am I using right approach for nested blocks in executeOnGCD: method?

A: I don't know the exact answer to the situation you have, but I have some suggestions, and they were more than would fit in a comment...
What you want to do here is to look at the stack traces of the free events that are happening over the 6 minutes after completion. That should give you some clues as to how the deallocations are being scheduled. It seems likely that there's some background thread doing cleanup. Getting those stack traces should allow you to search the code for where that cleanup is originally scheduled, and that should provide the answers you seek.
The close similarity between the upward and downward slopes of that graph makes me think that (conceptually) a timer is started when the object is last used, and that there's some mechanism that reaps them after some period of inactivity. This is probably implemented by registering the objects with some registry at malloc time, then updating a lastUsed field on every usage of the object, and then a periodic process walks the list and says, effectively, "free all objects that haven't been used for X amount of time." This might exist to provide some kind of implicit caching mechanism.
I don't know any of this for sure, but it seems like a probable explanation.