text:
Q: How do you echo a 4-digit Unicode character in Bash? I'd like to add the Unicode skull and crossbones to my shell prompt (specifically the 'SKULL AND CROSSBONES' (U+2620)), but I can't figure out the magic incantation to make echo spit it, or any other, 4-digit Unicode character. Two-digit one's are easy. For example, echo -e "\x55", .
In addition to the answers below it should be noted that, obviously, your terminal needs to support Unicode for the output to be what you expect. gnome-terminal does a good job of this, but it isn't necessarily turned on by default.
On macOS's Terminal app Go to Preferences-> Encodings and choose Unicode (UTF-8).

A: Any of these three commands will print the character you want in a console, provided the console do accept UTF-8 characters (most current ones do):
echo -e "SKULL AND CROSSBONES (U+2620) \U02620"
echo $'SKULL AND CROSSBONES (U+2620) \U02620'
printf "%b" "SKULL AND CROSSBONES (U+2620) \U02620\n"

SKULL AND CROSSBONES (U+2620) ☠

After, you could copy and paste the actual glyph (image, character) to any (UTF-8 enabled) text editor.
If you need to see how such Unicode Code Point is encoded in UTF-8, use xxd (much better hex viewer than od):
echo $'(U+2620) \U02620' | xxd
0000000: 2855 2b32 3632 3029 20e2 98a0 0a         (U+2620) ....

That means that the UTF8 encoding is: e2 98 a0

Or, in HEX to avoid errors: 0xE2 0x98 0xA0. That is, the values between the space (HEX 20) and the Line-Feed (Hex 0A).
If you want a deep dive into converting numbers to chars: look here to see an article from Greg's wiki (BashFAQ) about ASCII encoding in Bash!

A: Here is a list of all unicode emoji's available:
https://en.wikipedia.org/wiki/Emoji#Unicode_blocks
Example:
echo -e "\U1F304"

For get the ASCII value of this character use hexdump
echo -e "" | hexdump -C

00000000  f0 9f 8c 84 0a                                    |.....|
00000005

And then use the values informed in hex format
echo -e "\xF0\x9F\x8C\x84\x0A"

A: So long as your text-editors can cope with Unicode (presumably encoded in UTF-8) you can enter the Unicode code-point directly.
For instance, in the Vim text-editor you would enter insert mode and press Ctrl + V + U and then the code-point number as a 4-digit hexadecimal number (pad with zeros if necessary). So you would type Ctrl + V + U 2 6 2 0. See: What is the easiest way to insert Unicode characters into a document?
At a terminal running Bash you would type CTRL+SHIFT+U and type in the hexadecimal code-point of the character you want. During input your cursor should show an underlined u. The first non-digit you type ends input, and renders the character. So you could be able to print U+2620 in Bash using the following:
echo CTRL+SHIFT+U2620ENTERENTER
(The first enter ends Unicode input, and the second runs the echo command.)
Credit: Ask Ubuntu SE

A: I'm using this:
$ echo -e '\u2620'
☠

This is pretty easier than searching a hex representation... I'm using this in my shell scripts. That works on gnome-term and urxvt AFAIK.

A: You may need to encode the code point as octal in order for prompt expansion to correctly decode it.
U+2620 encoded as UTF-8 is E2 98 A0.
So in Bash,
export PS1="\342\230\240"

will make your shell prompt into skull and bones.

A: If you don't mind a Perl one-liner:
$ perl -CS -E 'say "\x{2620}"'
☠

-CS enables UTF-8 decoding on input and UTF-8 encoding on output. -E evaluates the next argument as Perl, with modern features like say enabled. If you don't want a newline at the end, use print instead of say.

A: Sorry for reviving this old question.  But when using bash there is a very easy approach to create Unicode codepoints from plain ASCII input, which even does not fork at all:
unicode() { local -n a="$1"; local c; printf -vc '\\U%08x' "$2"; printf -va "$c"; }
unicodes() { local a c; for a; do printf -vc '\\U%08x' "$a"; printf "$c"; done; };

Use it as follows to define certain codepoints
unicode crossbones 0x2620
echo "$crossbones"

or to dump the first 65536 unicode codepoints to stdout (takes less than 2s on my machine.  The additional space is to prevent certain characters to flow into each other due to shell's monospace font):
for a in {0..65535}; do unicodes "$a"; printf ' '; done

or to tell a little very typical parent's story (this needs Unicode 2010):
unicodes 0x1F6BC 32 43 32 0x1F62D 32 32 43 32 0x1F37C 32 61 32 0x263A 32 32 43 32 0x1F4A9 10

Explanation:

*

*printf '\UXXXXXXXX' prints out any Unicode character

*printf '\\U%08x' number prints \UXXXXXXXX with the number converted to Hex, this then is fed to another printf to actually print out the Unicode character

*printf recognizes octal (0oct), hex (0xHEX) and decimal (0 or numbers starting with 1 to 9) as numbers, so you can choose whichever representation fits best

*printf -v var .. gathers the output of printf into a variable, without fork (which tremendously speeds up things)

*local variable is there to not pollute the global namespace

*local -n var=other aliases var to other, such that assignment to var alters other.  One interesting part here is, that var is part of the local namespace, while other is part of the global namespace.

*

*Please note that there is no such thing as local or global namespace in bash.  Variables are kept in the environment, and such are always global.  Local just puts away the current value and restores it when the function is left again.  Other functions called from within the function with local will still see the "local" value.  This is a fundamentally different concept than all the normal scoping rules found in other languages (and what bash does is very powerful but can lead to errors if you are a programmer who is not aware of that).

A: In Bash:
UnicodePointToUtf8()
{
    local x="$1"               # ok if '0x2620'
    x=${x/\\u/0x}              # '\u2620' -> '0x2620'
    x=${x/U+/0x}; x=${x/u+/0x} # 'U-2620' -> '0x2620'
    x=$((x)) # from hex to decimal
    local y=$x n=0
    [ $x -ge 0 ] || return 1
    while [ $y -gt 0 ]; do y=$((y>>1)); n=$((n+1)); done
    if [ $n -le 7 ]; then       # 7
        y=$x
    elif [ $n -le 11 ]; then    # 5+6
        y=" $(( ((x>> 6)&0x1F)+0xC0 )) \
            $(( (x&0x3F)+0x80 ))"
    elif [ $n -le 16 ]; then    # 4+6+6
        y=" $(( ((x>>12)&0x0F)+0xE0 )) \
            $(( ((x>> 6)&0x3F)+0x80 )) \
            $(( (x&0x3F)+0x80 ))"
    else                        # 3+6+6+6
        y=" $(( ((x>>18)&0x07)+0xF0 )) \
            $(( ((x>>12)&0x3F)+0x80 )) \
            $(( ((x>> 6)&0x3F)+0x80 )) \
            $(( (x&0x3F)+0x80 ))"
    fi
    printf -v y '\\x%x' $y
    echo -n -e $y
}

# test
for (( i=0x2500; i<0x2600; i++ )); do
    UnicodePointToUtf8 $i
    [ "$(( i+1 & 0x1f ))" != 0 ] || echo ""
done
x='U+2620'
echo "$x -> $(UnicodePointToUtf8 $x)"

Output:
─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟
┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿
╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟
╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿
▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟
■□▢▣▤▥▦▧▨▩▪▫▬▭▮▯▰▱▲△▴▵▶▷▸▹►▻▼▽▾▿
◀◁◂◃◄◅◆◇◈◉◊○◌◍◎●◐◑◒◓◔◕◖◗◘◙◚◛◜◝◞◟
◠◡◢◣◤◥◦◧◨◩◪◫◬◭◮◯◰◱◲◳◴◵◶◷◸◹◺◻◼◽◾◿
U+2620 -> ☠

A: The printf builtin (just as the coreutils' printf) knows the \u escape sequence which accepts 4-digit Unicode characters:
   \uHHHH Unicode (ISO/IEC 10646) character with hex value HHHH (4 digits)

Test with Bash 4.2.37(1):
$ printf '\u2620\n'
☠

A: Here's a fully internal Bash implementation, no forking, unlimited size of Unicode characters.
fast_chr() {
    local __octal
    local __char
    printf -v __octal '%03o' $1
    printf -v __char \\$__octal
    REPLY=$__char
}

function unichr {
    local c=$1    # Ordinal of char
    local l=0    # Byte ctr
    local o=63    # Ceiling
    local p=128    # Accum. bits
    local s=''    # Output string

    (( c < 0x80 )) && { fast_chr "$c"; echo -n "$REPLY"; return; }

    while (( c > o )); do
        fast_chr $(( t = 0x80 | c & 0x3f ))
        s="$REPLY$s"
        (( c >>= 6, l++, p += o+1, o>>=1 ))
    done

    fast_chr $(( t = p | c ))
    echo -n "$REPLY$s"
}

## test harness
for (( i=0x2500; i<0x2600; i++ )); do
    unichr $i
done

Output was:
─━│┃┄┅┆┇┈┉┊┋┌┍┎┏
┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟
┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯
┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿
╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏
═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟
╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯
╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿
▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏
▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟
■□▢▣▤▥▦▧▨▩▪▫▬▭▮▯
▰▱▲△▴▵▶▷▸▹►▻▼▽▾▿
◀◁◂◃◄◅◆◇◈◉◊○◌◍◎●
◐◑◒◓◔◕◖◗◘◙◚◛◜◝◞◟
◠◡◢◣◤◥◦◧◨◩◪◫◬◭◮◯
◰◱◲◳◴◵◶◷◸◹◺◻◼◽◾◿

A: Based on Stack Overflow questions Unix cut, remove first token and https://stackoverflow.com/a/15903654/781312:
(octal=$(echo -n ☠ | od -t o1 | head -1 | cut -d' ' -f2- | sed -e 's#\([0-9]\+\) *#\\0\1#g')
echo Octal representation is following $octal
echo -e "$octal")

Output is the following.
Octal representation is following \0342\0230\0240
☠

A: In UTF-8 it's actually 6 digits (or 3 bytes).
$ printf '\xE2\x98\xA0'
☠

To check how it's encoded by the console, use hexdump:
$ printf ☠ | hexdump
0000000 98e2 00a0
0000003

A: Quick one-liner to convert UTF-8 characters into their 3-byte format:
var="$(echo -n '☠' | od -An -tx1)"; printf '\\x%s' ${var^^}; echo

or
echo -n '☠' | od -An -tx1 | sed 's/ /\\x/g'

The output of both is \xE2\x98\xA0, so you can write reversely:
echo $'\xe2\x98\xa0'   # ☠

A: Easy with a Python2/3 one-liner:
$ python -c 'print u"\u2620"'    # python2
$ python3 -c 'print(u"\u2620")'  # python3

Results in:
☠

A: % echo -e '\u2620'     # \u takes four hexadecimal digits
☠
% echo -e '\U0001f602' # \U takes eight hexadecimal digits

This works in Zsh (I've checked version 4.3) and in Bash 4.2 or newer.

A: Just put "☠" in your shell script. In the correct locale and on a Unicode-enabled console it'll print just fine:
$ echo ☠
☠
$

An ugly "workaround" would be to output the UTF-8 sequence, but that also depends on the encoding used:
$ echo -e '\xE2\x98\xA0'
☠
$

A: In bash to print a Unicode character to output use \x,\u or \U (first for 2 digit hex, second for 4 digit hex, third for any length)
echo -e '\U1f602'

I you want to assign it to a variable use $'...' syntax
x=$'\U1f602'
echo $x

A: If hex value of unicode character is known
H="2620"
printf "%b" "\u$H"

If the decimal value of a unicode character is known
declare -i U=2*4096+6*256+2*16
printf -vH "%x" $U              # convert to hex
printf "%b" "\u$H"


text:
Q: Renesas -- cannot get I/O to work except onboard LED This is regarding an RL78G14 dev board/stick.
At first I initialized the led D2 using PM7 = 0x7F; and I toggled it every 63 ms using a timer ISR with P7 ^= 80;.
That went fine. Next step was getting another pin to do the same, but it did not work. I even tried toggling most of the I/O pins using
PM7 = 0x0;
PM6 = 0x0;
PM5 = 0x0;
PM4 = 0x0;
PM3 = 0x0;
PM2 = 0x0;

and
P7 ^= 0xFF;
P6 ^= 0xFF;
P5 ^= 0xFF;
P4 ^= 0xFF;
P3 ^= 0xFF;
P2 ^= 0xFF;

. The led still blinks, but about 95% of the 64 pins remain low (GND). (Implying no change in any other pins except P77 (led)).
I'm also using E2 studios v3.0.0.22 (Eclipse based), KPIT compiler v15.02, the built in code generator in e2 studios, and developing in Windows 8 at the moment.
Anyone have an idea how to approach this problem? It doesn't have to be specific to this board. If it were an embedded board you were familiar with, how would you fix it?

A: So, to answer my own question, it really was trivial in the end. It was a case of improper grounding. I assumed that the scope and board were both grounded, so I measured using only the positive lead of the scope. It does work in the end.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Openpyxl - How to copy data range from an excel worksheet to another I'm trying to copy a range of data based on row coordinates from a sheet to another.
I have a list with row coordinates
tbrow = [1, 34, 52, 75, 101]
What I would like to do is to copy the row range from:
1 to 34 from sheet 0 to sheet 1,
34 to 52 from sheet 0 to sheet 2,
52 to 75 from sheet 0 to sheet 3,
75 to 101 from sheet 0 to sheet 4.
What I tried so far is the following:
-Get the main sheet 0
sheet0 = wb["Sheet"]
Then I stored the sheets in a variable, ignoring the first sheet
sheets = wb.worksheets[1:]
In the end, I tried to copy the given values.
for i in range(tbrow[i],tbrow[i]+1)
    for j in range(1,sheet0.max_column+1):
        for k in sheets:
            k.cell(row=i, column=j).value = sheet0.cell(row=i, column=j).value
Problem is that I get only the first row copied to the rest of the sheets and not the whole range. (1-34;34-52 and so on)
What am I missing?
Can anyone help me on organizing a logic in here? Or provide a solution?
Thank you!

UPDATE

Another approach was to slice the list.
a,b = tbrow[:2]
for i in range(a,b):
    for j in range(1,sheet1.max_column+1):
        for k in sheets: k.cell(row=i, column=j).value = sheet1.cell(row=i, column=j).value
But that takes only the first two row coordinates from the list and I would like to go to the next item in the list:
-From first to second
-From second to third
-From third to fourth
...and so on –

A: The problem I notice with your code is the value of i inside the range method. The i inside the range method is not the same as the i being used in the for loop. I am assuming you must have a global definition of i=0 which is then not updated, hence why only the first rows are copied to the next sheet.
for i in range(tbrow[i],tbrow[i]+1):#------here
    for j in range(1,sheet0.max_column+1):
        for k in sheets:
            k.cell(row=i, column=j).value = sheet0.cell(row=i, column=j).value

Consider using a function where u can the pass the values of the rows
def addRowsToSheet(lb,ub):
    for i in range(lb,ub):#------here
        for j in range(1,sheet0.max_column+1):
              #consider using switch case, instad of the loop
              switch (ub):
                  case 34:
                    sheets[0].cell(row=i, column=j).value = sheet0.cell(row=i, column=j).value;
                    sheets[1].cell(row=i, column=j).value = sheet0.cell(row=i, column=j).value;
                  case 52:
                    sheets[2].cell(row=i, column=j).value = sheet0.cell(row=i, column=j).value;

              #Do the same logic below

#calls
for i in range(0,len(tbrow)-1):
     addRowsToSheet(tbrow[i],tbrow[i+1])


text:
Q: Laravel ajax pagination loads entire page I am attempting to create ajax pagination using a "load more" button instead of Laravel's default pagination. Now, I've spent the past couple of days searching online for a solution, but everything is jquery and I am relatively new to javascript and Laravel. I'd prefer to avoid jquery, since I am trying to get better at working with vanilla javascript.
I have tried all the suggestions on this site that I could find, none works for me.
The index view paginates 4 items (for testing purposes at this point) and on each ajax request, I would like to render the next 4 rows.
My problem is, the ajax request renders the entire page instead of just the data from the database. What am I doing wrong in my code?
Controller:
public function sandbox(Request $request)
    {

        $response = array(
            'status' => 'success',
            'msg' => $request->message,
        );

        $products = Product::orderBy('title', 'asc')->paginate(4);

        if ($request->ajax()) {
            return view('sandbox-more', compact('products'))->render();
        }
        else {
            return view('sandbox', compact('products'));
        }
    }

Javascript:
const container = document.querySelector('#sandbox-container');
const button = document.getElementById('load-stuff');
let url = button.getAttribute('href'); // http://127.0.0.1:8000/sandbox?page=2

button.addEventListener('click', (event) => {
    event.preventDefault();
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);

    xhr.onload = function() {
        if (xhr.status === 200) {
            container.insertAdjacentHTML('beforeend', xhr.responseText); // ouputs entire view instead of the partial
            console.log(xhr.responseText);
        }
        else {
            console.log(`Request failed, this is the response: ${xhr.responseText}`);
        }
    };

    xhr.send();
})

My partial view to be loaded on ajax request
@foreach ($products as $product)

{{ $product->title }}

        img }}" alt="{{ $product->title }}" style="width: 50px;">

@endforeach

I am not sure what I need to do in order to render the xhr.responseText as only the $products data? I've tried sending it as json data, but that returns null each time. I hope someone can help a noob out here, thanks in advance!

A: I managed to fix it using xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');


text:
Q: Dynamic name of cron event In my multisite install, I'd like to add a daily cron event for some of the subsites. The cron will import posts via API from another website.
Because importing the content for all sites at once would end in timeout, I'd like to set a cron for each of the subsites.
In my class I did:
    $cron_name = 'import_blog_posts_in_network_daily_'.get_current_blog_id();
    if ( !wp_next_scheduled( $cron_name) ) {
        wp_schedule_event( time(), 'daily', $cron_name );
    }
    add_action( $cron_name, array($this, 'import_blog_posts_in_network') );

That code registers the cron for each of my subsites correctly. But, I don't know, how can I access the name in my import_blog_posts_in_network callback
Is there a way to get the action name in the callback, to get the ID of my site?

A: So no, I can't see a way to grab the name of your action. However, you can pass arguments to your callback:
$blog_id = get_current_blog_id();
$cron_name = 'import_blog_posts_in_network_daily_'.$blog_id;
if ( !wp_next_scheduled( $cron_name) ) {
    wp_schedule_event( time(), 'daily', $cron_name, array($blog_id) );
}
add_action( $cron_name, array($this, 'import_blog_posts_in_network') );
/*
public function import_blog_posts_in_network($blog_id) {
    // do something for blog $blog_id
}
*/

Hope that helps!


text:
Q: Place street view on major street rather than back street Following code places camera on road closest to marker however its an back street and kind of useless for navigation.
Is there way to place camera on nearest major street instead (in this case "Eastern Ave") without changing marker's position rather checking picking programmatically closest major street over just any closest street.
var panorama, myPlace;

function initialize() {

    myPlace = {
        lat: 33.976827,
        lng: -118.163889
    };

    var map = new google.maps.Map(document.getElementById('map'), {
        center: myPlace,
        zoom: 18
    });

    panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'), {
        position: myPlace
    });

    var marker = new google.maps.Marker({
        position: myPlace,
        map: map
    });

    map.setStreetView(panorama);

    var sv = new google.maps.StreetViewService();

    sv.getPanorama({
        location: myPlace,
        radius: 50
    }, processSVData);
}

function processSVData(data, status) {

    if (status === google.maps.StreetViewStatus.OK) {

        var marker_pano = new google.maps.Marker({
            position: myPlace,
            map: panorama
        });

        var heading = google.maps.geometry.spherical.computeHeading(data.location.latLng, marker_pano.getPosition());

        panorama.setPov({
            heading: heading,
            pitch: 0
        });
    }
}

google.maps.event.addDomListener(window, 'load', initialize);

http://jsfiddle.net/0LdqLzt6/

A: Using the answer from Request main road / curbside StreetView panoramas instead of back alleys from API  with your address (to get the address I reverse geocoded your coordinates, then adjusted, as it seemed to want to point to the building next door).

var sv = new google.maps.StreetViewService();
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();
var panorama;
var address = "6327 Eastern Avenue, Bell, CA 90201, USA";
var myLatLng;

function initialize() {
  myPlace = {
    lat: 33.976827,
    lng: -118.163889
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    center: myPlace,
    zoom: 18
  });
  var marker = new google.maps.Marker({
    position: myPlace,
    map: map
  });
  panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"));
  map.setStreetView(panorama);
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      myLatLng = results[0].geometry.location;

      // find a Streetview location on the road
      var request = {
        origin: address,
        destination: address,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
      };
      directionsService.route(request, directionsCallback);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}
google.maps.event.addDomListener(window, 'load', initialize);

function processSVData(data, status) {
  if (status == google.maps.StreetViewStatus.OK) {

    panorama.setPano(data.location.pano);

    var heading = google.maps.geometry.spherical.computeHeading(data.location.latLng, myLatLng);
    panorama.setPov({
      heading: heading,
      pitch: 0,
      zoom: 1
    });
    panorama.setVisible(true);

  } else {
    alert("Street View data not found for this location.");
  }
}

function directionsCallback(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    var latlng = response.routes[0].legs[0].start_location;
    sv.getPanoramaByLocation(latlng, 50, processSVData);
  } else {
    alert("Directions service not successfull for the following reason:" + status);
  }
}
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map,
#pano {
  width: 100%;
  height: 50%;
}


text:
Q: Dialogflow - Get two similar type values in one intent I need to get two addresses in an intent in Dialogflow. When the user enters the first address, there is no problem, but when user enters the second address, it updates the first address and does not fill in the second address. Since the address structures are in certain patterns, the training phrases are similar to each other and therefore one of the addresses currently remains blank.
my structure is:
{FirstAddress - @sys.address - $FirstAddress}
{SecondAddress - @sys.address - $SecondAddress}

A: You may try and consider the below approach to fit in your use case.
You can manually annotate the first address input from your training phrase into your FirstAddress parameter and then the second address input to SecondAddress parameter just like this:

Output would be:


text:
Q: ¿Tiene algún tipo de virus o algo raro para robar archivos esta fuente? Esta fuente está programada para poner contraseña a las carpetas de windows. Y antes de guardar algún tipo de carpeta me gustaría saber si es seguro. La fuente es la siguiente:
cls
@ECHO OFF
title Folder Private
if EXIST "HTG Locker" goto UNLOCK
if NOT EXIST Private goto MDLOCKER
:CONFIRM
echo Are you sure you want to lock the folder(Y/N)
set/p "cho=>"
if %cho%==Y goto LOCK
if %cho%==y goto LOCK
if %cho%==n goto END
if %cho%==N goto END
echo Invalid choice.
goto CONFIRM
:LOCK
ren Private "HTG Locker"
attrib +h +s "HTG Locker"
echo Folder locked
goto End
:UNLOCK
echo Enter password to unlock folder
set/p "pass=>"
if NOT %pass%== CONTRASEÑA goto FAIL
attrib -h -s "HTG Locker"
ren "HTG Locker" Private
echo Folder Unlocked successfully
goto End
:FAIL
echo Invalid password
goto end
:MDLOCKER
md Private
echo Private created successfully
goto End
:End

A: No deberías tener ningún problema en usarlo por temas de seguridad, simplemente asegúrate de asignarle una contraseña al editar el archivo y estará listo para funcionar.

A: En realidad es un fichero por lotes de windows, imagino que con extension .bat o .cmd o similar. Lo que hace ese código es ocultar y marcar una carpeta como de sistema para que no puedas borrarla ni verla y también hacer el proceso inverso si le pasas una contraseña.
Esto no es nada peligroso ni es nada que tu no puedas revertir. La primera instrucción cls lo que hace el limpiar la salida en caso que haya algo escrito en ella así que no es un lenguaje ni nada parecido.
Aqui tienes una descripción paso a paso del algoritmo
limpiar la pantalla
desactiva mostrar los comandos que se están ejecutando
pon el título de la ventana a "Folder Private"
si existe la carpeta "HTG Locker" ve a la etiqueta :UNLOCK
si no existe la carpeta "Private" ve a la etiqueta :MDLOCKER
:CONFIRM
pregunta "Are you sure you want to lock the folder(Y/N)"
establece la variable "cho" con lo que el usario escriba
si escribió "Y" o "y" ve a la etiqueta :LOCK
si escribió "N" o "n" ve a la etiqueta :END
si no es ninguna de las anteriores ve a la etiqueta :CONFIRM
:LOCK
renombre la carpeta "Private" a "HTG Locker"
ponle los atributos oculto y sistema a la carpeta "HTG Locker"
escribe "Folder locked" y termina
:UNLOCK
Escribe "Enter password to unlock folder"
establece la variable "pass" con lo que el usario escriba
si "pass" no es igual a CONTRASEÑA ve a la etiqueta :FAIL
quita los atributos oculto y sistema a la carpeta "HTG Locker"
renombra la carpeta "HTG Locker" a "Private"
escribe "Folder Unlocked successfully" y termina
:FAIL
escribe "Invalid password" y termina
:MDLOCKER
crea una carpeta llamada "Private"
escribe "Private created successfully" y termina

Debes tener cuidado porque el windows puede que no interprete bien la constraseña "CONTRASEÑA" por la "Ñ" y no te deje desbloquear la carpeta en cuyo caso sólo ejecuta
attrib -h -s "HTG Locker"

y toda la supuesta "protección" se le desactiva ;).
Si quieres saber lo que hacen algunos de esos comandos sólo abre la consola en una pc que tenga windows y ejecuta help <comando> o sólo help para listar todos los comandos.


text:
Q: Mysql join with group by query optimization I am using the following query to get the latest articles (article title + author name + total comments) but it takes long time to run:
SELECT article.id, title, username, count( comment.id ) AS total_comments
FROM article
    LEFT JOIN COMMENT ON comment.article_id = article.id
    LEFT JOIN user ON article.user_id = user.id
WHERE STATUS = "open"
    AND section = "mobiles"
GROUP BY article.id
ORDER BY article.id DESC
LIMIT 0 , 30

The output of explain is:
id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  article     ALL     status  NULL    NULL    NULL    77  Using where; Using temporary; Using filesort
1   SIMPLE  comment     ref     article_id  article_id  5   test.article.id     2
1   SIMPLE  user    eq_ref  PRIMARY     PRIMARY     4   test.article.user_id    1

how to re-write the query to avoid creating temporary table?
Storage engine is MyISAM. Here is tables details with indexes:
article
id, title,  body,   user_id,    status,     section
primary key: id
indexes: (user_i),(status,section,id)

comment
id, article_id, user_id,    body
primary key: id
index:(article_id)

user
id, username
primary key: id

A: This execution plan is pretty good.  You really can't avoid creating and sorting the temp table: your query calls for a grouped and sorted summary, which is, ummm, a temporary table. If you give your mySQL server process more RAM you may be able to get it to use an in-memory table rather than an on-disk table.

A: Would using a sub query instead of the grouped join speed up the process.
SELECT article.id, title, username,
      (
       select count(*) from COMMENT
       where comment.article_id = article.id
       ) AS total_comments
FROM article
    LEFT JOIN user ON article.user_id = user.id
WHERE STATUS = "open"
    AND section = "mobiles"
ORDER BY article.id DESC
LIMIT 0 , 30

as per a previous question How to make a nested query?
I hope this helps.


text:
Q: How to use only the column as the parameter in a 1 row to 1 row return pl/sql function in Oracle I have written this functionfexemplo called like this:
select fexemplo(id) from texemplo;

id is the primary key of the table texemplo.
texemplo is as follows:
Name                       Null?    Type
 ----------------------------------------- -------- ----------------------------
 ID                    NOT NULL NUMBER(10)
 TVALUE                         NUMBER(10)

The function adds 10 to the value in tvalue attribute.
So if we have:
select * from texemplo;

    ID     TVALUE
---------- ----------
     1     20
     3     59

Then:
select fexemplo(id) from texemplo;

Is going to return:
FEXEMPLO(ID)
------------
      30
      69

The function code I am using is:
create or replace function fexemplo (pid IN NUMBER)
RETURN NUMBER
IS
    vteste NUMBER(10);
BEGIN
    SELECT tvalue
    INTO vteste
    FROM texemplo
    WHERE id=pid;
    vteste := vteste+10;
    RETURN vteste;
END fexemplo;
/

It works fine - it returns one result for each row as expected. However I want this function to be generic. So, I want it to work with other table like this one:
Name                       Null?    Type
 ----------------------------------------- -------- ----------------------------
 USERID                         VARCHAR2(50)
 AGE                            NUMBER(10)
 PHOTO                          BLOB
 NOFFRIENDS                     NUMBER(10)

I want to add 10 to the NOFFRIENDS column.
I should be able to execute the same function on this other table.
Therefore I cannot use the id as parameter. The function code has to be totaly different.
The parameter I want to use is the NUMBER, so I could execute it on both the tables:
 select fexemplo(tvalue) from texemplo;

OR
select fexemplo(noffriends) from utable;

The return is still 1 row to 1 row.
The tvalue and noffriends column might have repeated values.
The function code is probably tottaly different.
How could I make it?
Another example is: how could I make an ABS function by myself?
How could I make the ABS function on PL/SQL?
The function is explained here:
ABS function
Thanks in advance!

A: You are calling your function like this ...
select fexemplo(id) from texemplo;

... so you can avoid the need to query a table itself. As your question actually says, all you need to do is change the value passed as the input parameter to the column being modified:
  select fexemplo(tvalue) from texemplo;

Not only is this version simpler and more obvious it is also completely generic;
create or replace function fexemplo (pid IN NUMBER)
RETURN NUMBER
is
begin
    return pid + 10;
end;


text:
Q: suppress multiple function triggers with laravel I inherited an old laravel 4.2 codebase that I will be fixing up and migrating to latest version shortly.
In the meantime, there is one bug that needs fixing that is giving me a problem. There is a send mail routine that once triggered sends the same email 3 times...even though it should only send once. Is there a way to send the first email and not the other two? Kind of a cooldown timer?
Thanks!
Piece of code that sends the email
if ($send_emails == true) {
        Mail::send(
            'emails.event_notify',
            json_decode( json_encode( $data ), true ),
            function( $message ) use ($data, $subject, $emailList) {
                $message->to( $emailList );
                $message->from( "email@example.com" );
                $message->subject( $subject );
            }
        );
    }

$emailList is a simple array of 3 emails in this case.


text:
Q: figure before, not after #Discussion - R Markdown I am having an issue positioning a figure.
My header:
\usepackage{amsmath}
\usepackage{pdflscape}
\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

Some of my R Markdown code:
\newpage
\blandscape
```{r finaltable1_1, echo=FALSE}
table1_1
```
\elandscape

\newpage
\blandscape
```{r figone, message=FALSE, warning=FALSE, echo=FALSE, out.width='100%', fig.align='center', fig.cap='description.'}
knitr::include_graphics('./images/figure2.pdf')
```
\elandscape

\newpage
```{r figresults, message=FALSE, warning=FALSE, echo=FALSE, out.width='100%', fig.align='center', fig.cap='description.'}
knitr::include_graphics('./images/figure3.pdf')
```

\newpage
# Discussion

figure3 should go before Discussion, but it is showing after, any ideas about what might be happening?

A: So, you can solve your problem by:
a) reducing the pic's width in this chunk:
```{r figresults, message=FALSE, warning=FALSE, echo=FALSE, out.width='70%', fig.align='center', fig.cap='description.'}
knitr::include_graphics('pic.pdf')
```

b) using another constructions:
![My piccy-pic](pic.pdf){width=90%}

or
\begin{figure}[H]
\centering
\includegraphics[width=0.9\textwidth]{pic.pdf}
\caption{I'm here}
\end{figure}


text:
Q: Flex: Adobe Flash Builder with MXML: HTML Progressive Streaming doesnt work! I am using progressive streaming with VideoDisplay, the HTTP URL provided gets buffered completely even if I have configured it to start playing the video when the buffering reaches 20%, the trace message shows that the playing started(using mozilla / Flashbug+Firebug), but it doesnot show the video till the buffercounter reaches 100%
How can I get the video stream to play at the 20% of stream.
Code Segment where the check takes place
var loadedPct:uint = Math.round(100 * (event.bytesLoaded / event.bytesTotal));
            trace('waiting...');
            mainVideoCanvas.addChild(LoadingImage);
            VidLoadingLabel2.text = loadedPct.toString();
            mainVideoCanvas.addChild(VidLoadingLabel2);

            if (loadedPct >= 20)
            {

                trace(event.bytesLoaded);
                trace(loadedPct);
                player.load();
                player.play();
                trace(player.state);
                trace('Playing');
            }
            if (loadedPct == 100)
            {
                trace('Ready to Complete');
                trace(player.state);
                mainVideoCanvas.removeChild(VidLoadingLabel2);
                mainVideoCanvas.removeChild(LoadingImage);
                mainVideoCanvas.addChild(player);
                player.addEventListener(VideoEvent.COMPLETE, completePlay);

            }

Thanks and regards
deadbrain

A: The web server needs specific support for the variant of HTTP that Flash speaks when it tries to stream a movie. Adobe isn't using bog-standard HTTP for this. If the web server doesn't have this support, you get the behavior you see: complete download before playback begins.
With H.264 and Apache, you can add the support you need for this with CodeShop's mod_h264_streaming plugin.


text:
Q: Dynamically create a link and open it in same iframe I have a link that is being dynamically created with url params and all sort of good stuff in my javascript.
I am then obviously trying to open that page. I would like to open it within the same iframe, but anything I try keeps opening it in a new tab (can't do it this way because I loose all context and data).
I have tried
window.open(url, '#iframeId');
window.open(url);
window.open(url, '_top'); //This kind of worked, but overtook the whole window ignoring the iframe

Any ideas? Most of what I saw when I searched was coming from the html side and I don't have access to changing that.

A: Fist you need to set your <iframe name="test"> name like this and
than use window.open('www.google.co.in', "test") this

A: You have to change the src of the iframe.
$("#iframeId").prop("src", url);

Without jQuery you could go for:
document.getElementById('iframeId').src = url;

Here is a jsfiddle with some kind of the functionality you search for.
JSFIDDLE


text:
Q: Code-First EF Core double column length I'm using EF Core 1.1 and it's doubling the column length at the database.
entityBuilder.Property(t => t.Name)
               .HasMaxLength(200)
               .IsRequired();

The code above generate the following script
Name = table.Column<string>(maxLength: 200, nullable: false)

But when I update the database, it generate the following result

Any ideas ?

A: One char is two bytes in your encoding


text:
Q: How to permanently stop audio in iOS with pressing home button? I've got an application with a navigation tree. Somewhere there is an audio player with an mp3.
UITabViewController // controlled by AppDelegate.m
    -> UINavigationController
        -> UITableViewController // controlled by TableViewController.m
            -> UIViewController // with my AVAudioPlayer controlled by AudioViewController.m

In AudioViewController.m I have all my audio engine so i play/pause/stop it, and even kill it when pressing back button (using viewWillDisappear etc) - it plays only in this one view, not another, and it's good.
However there is an issue when i press home button while playback is on. It stops, but after going back to my app, it plays again from remembered time stamp.
I tried all this:
- (void)viewDidUnload
{
    [super viewDidUnload];
    [self audioStop:self];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self audioStop:self];
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self audioStop:self];
}

- (void)viewWillUnload
{
    [self audioStop:self];
    [super viewWillUnload];
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self audioStop:self];
}

But nothing happens.
Now i know that to manage if home button was pressed, i need to use applicationWillResignActive method from AppDelegate, but i have totally no idea how do i stop my audioplayer from here. I'm quite new to iOS and i'm not familiar with how delegates work, so please help me work this out.

A: Let you  AppDelegate hold a reference for you UIViewcontroller some how and call it. Make sense?
   AppDelegate
        |
        v
    TableViewController (@property)
        |
        v
    UIViewController (@property)
        |
        v
    AudioPlayer (@property) --> [ stop];

Edit:
@interface TableViewController : UIViewController
{
     AudioPlayer * audioPlayer;
}
@property(nonatomic, retain) AudioPlayer * audioPlayer;
... // other stuff
@end

@implementation TableViewController
@synthesize audioPlayer;
... // other stuff
@end

This way you can access the audio player from TableViewController object. If you hold TableViewController object this way it should be easy for you.
[tableViewController.audioPlayer someMethod];

something like that ..

A: When home button was pressed, you need to use applicationWillResignActive method from AppDelegate, How we can use this method , i will show you. You need to use NotificationObeserver in your view controller.
How To add NotificationOberserver
 NotificationCenter.default.addObserver(self, selector: #selector(self.application_resign_active(notification:)), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)

Now You can stop sound in this function : Like This
func application_resign_active(notification : NSNotification)
{

    if my_audio_player.isPlaying{
        print("Stop")
        my_audio_player.stop()
    }

}

my_audio_player is an instance of AudioPlayer
var my_audio_player = AVAudioPlayer()
You can also Check My Video , how i do this : https://www.youtube.com/watch?v=BxmhTAd1SU4


text:
Q: Using Observable to initialize an interface in Angular 2 I have a interface called Users and I am trying to initialize the object like the below:
constructor(private _http: Http) {  }

  getUsers(): Observable<User[]> {
        return this._http.get(this._url)
            .map((response: Response) => response.json())

            .do(data => console.log("User data" + JSON.stringify(data)))
            .catch(this.handleError);
    }

    private handleError(error: Response) {
        console.log(error);
        return Observable.throw(error.json().error || 'Internal Server error');
    }

However I am getting the following errors.
The type argument for type parameter 'T' cannot be inferred from the
usage. Consider specifying the type arguments explicitly. Type
argument candidate 'Response' is not a valid type argument because it
is not a supertype of candidate 'Response'. Types of property 'type'
are incompatible. Type 'string' is not assignable to type  'ResponseType'

The URL is the file path to a JSON file. I am trying to set it up this way so I can easier transition to a real HTTP call but right now I want to use mock data from a JSON file.

A: Import Response object from angular2/http
import { Response } from '@angular/http';

You can read or understand more :
https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data


text:
Q: How to count nodes and get attribute value without using xpath Currently I have a shell script like this:
LOGIN=`curl 'https://www.ponta.jp/u/LWAS900/SLWAS900010.htm' -sS | grep '<input type="hidden" name\|<form\|</form'`

for i in $(seq $(printf "$LOGIN" | xmllint --xpath "count(/form/input)" -))
do
    printf " -d "
    printf "$LOGIN" | xmllint --xpath "string(/form/input[$i]/@name)" -
    printf "="
    printf "$LOGIN" | xmllint --xpath "string(/form/input[$i]/@value)" -
done

I want to do the same thing on a unix environment which doesn't have xpath. Can anyone tell me how to do it?

A: A XML parser based solution is the way to go.
Nevertheless here goes a quick regular expression hack:
LOGIN=...
printf "$LOGIN" |
    perl -nE 'say "-d $1=$2" if /name="(.*?)".*?value="(.*)"/'


text:
Q: Terms clarification for Quotient space related questions. For the following two questions:

a) Determine the quotient space of the torus surface $S^{1}\times S^{1}$ modulo the longitudinal circle $S^{1}\times \{1\}.$
  b) Prove that $S^{2}$ is homeomorphic to the quotient space of the torus surface $S^{1}\times S^{1}$ modulo the 1-point union $S^{1}\vee S^{1}=(S^{1}\times \{1\})\cup (\{1\}\times S^{1})$ of the longitudinal circle $S^{1}\times \{1\}$ and the meridional circle $\{1\}\times S^{1}$.

I don't understand the use of the term modulo and also for part (b), I also don't understand the phrase "1-point union".   I am hoping someone can clarify what they mean mean, and what I need to do the question, in the sense, am I suppose to come up with a homeomorphic mapping or defined some sort of equivalence relation for (a) over the torus, and for (b) over the sphere.
Thank you in advance.


text:
Q: PHP how to explore a multidimentional array I have read the advanced help, sorry but I don't understand this editor!!!
I have created a multidimensional like:
[YYY] => Array
     (
         [0] => 11.12
         [1] => 22.775000000
         [2] => 33.895
         [AABB] => Array
             (
                 [0] => 22.12
                 [1] => 12.23000000
                 [2] => 23.895
             )
     )
[ZZZ] => Array
     (
         [0] => 1.12
         [1] => 33.775000000
         [2] => 44.895
         [NNNN] => Array
             (
                 [0] => 23.30
                 [1] => .000000000
                 [2] => 997.3
             )

The YYY and ZZZ are the main 'records. YYY does have a subrecord AABB and ZZZ does have a subrecord NNNN. In this example they have only one sub record but every main record can have one or more subrecords.
The result should be like this (sorry I don't understand the editor although if I read the advanced help it should work with |s and -s???):

 kolom 1	Kolom 2	Kolom 4	Kolom 4

YYY	11.12	22.775000000	33.895

- AABB	22.12	12.23000000	23.895

ZZZ	1.12	33.775000000	44.895

- NNNN	23.30	.000000000	997.3

I hope that is clear what I want. Sorry for layout but again I don't understand how this editor works.
I'm trying todo with a foreach loop like (I have simplified it, to make it more clear):
foreach($aMarktWaardeExposure as $sLevel3 => $aLevel4) {
        echo ''.$sLevel3.'	'; //main record
        foreach($aLevel4 as $sLevel4) {
                echo $sLevel4.'
'; //Sub record
        }
}

I hope that someone can help me out.
Thanks,
Nico

A: Maybe something like this:
    <?php

$array = [
    'YYY' => [
        0 => 11.12,
        1 => 22.775000000,
        2 => 33.895,
        'AABB' => [
            0 => 22.12,
            1 => 12.23000000,
            2 => 23.895,

        ]
    ],
    'ZZZ' => [
        0 => 1.12,
        1 => 33.775000000,
        2 => 44.895,
        'NNNN' => [
            0 => 23.30,
            1 => .000000000,
            2 => 997.3
        ]
    ]
];
?>

    <?php foreach($array as $row): ?>

            <?php foreach($row as $cell): ?>

                    <?= is_array($cell) ? implode('
', $cell) : $cell ?>

            <?php endforeach; ?>

    <?php endforeach; ?>

Output:

            11.12
            22.775
            33.895
            22.12
12.23
23.895

            1.12
            33.775
            44.895
            23.3
0
997.3


text:
Q: QTableWidget print table on paper I am writing program using Qt. Program result - QTableWidget object. Can I print this table on paper without any conversion to excel, pdf, etc? Is this possible?

A: QPrinter is a paint device, you can render your widget with that.
QPrinter printer;
QPrintDialog printer_dialog(&printer);
if (printer_dialog.exec() == QDialog::Accepted) {
    QPainter painter(&printer);
    your_widget->render(&painter);
}

A: Take of look at QDocument. Use e.g. a QTextstream to construct a html-structure from your table. Use setHtml to set the document content. Now you can use print to print with a QPrinter.


text:
Q: An inequality with binomial coefficients I am looking for a proof for the following inequality:
$$
\sum_{j=0}^k {m k + m - 1\choose j} \leq 2^{m k}
$$
I checked it numerically for all $m,k$ between 1 and 100. Here is a plot of the left-hand side divided by the right-hand side; the darkest tone (at the top and left) represents 1. The other tones are smaller. So I am quite sure this inequality is true. But how can I prove it?

A: Edit: I've changed the rules for how the switches operate according to Erel Segal-Halevi's suggestion; this should now be a full proof.
A combinatorial proof:
Suppose you have $mk$ lights, arranged in $m$ groups of $k$ lights each, and $mk + m-1$ switches. The first $mk$ switches are "normal" switches, and each toggles a single (unique) light; the last $m-1$ switches are "special" switches numbered $1$ through $m-1$, and the switch numbered $i$ toggles the entire group #$i$ as well as the entire group #$m$ (thus toggling a total of $2k$ lights).
All switches begin in the off position. You are allowed to move up to $k$ switches into the on position. How many different light patterns can you generate?
You have $\sum_{j=0}^k\binom{mk+m-1}{j}$ possible switch positions to generate. We need to convince ourselves that each switch position generates a unique light pattern. First, note that if we can determine from the light pattern exactly which special switches were flipped, we can determine the switch position. Thus it will be sufficient to determine which groups were turned on in virtue of the special switches (i.e., which special switches were flipped, plus group #$m$ iff an odd number of special switches were flipped).
We can make use of the following observation: given any pair of groups $i$ and $j$, if group $i$ was turned on by virtue of the special switches and group $j$ was not, then more lights are on in group $i$ than in group $j$. To show this to be true, note that if group $i$ was turned on by virtue of the special switches, at most $k-1$ normal switches have been flipped; letting $\ell_i$ denote the number of lights on in group $i$, if without the normal switches we had $\ell_i-\ell_j = k$, and each flip of a normal switch changes this quantity by at most $1$, then we have at the end of the process $\ell_i-\ell_j \geq k-(k-1) =1>0$.
We can also determine the number of groups turned on in virtue of the special switches. This is always an even number. Let this number be $2n$. If $n>0$, then $2nk$ lights are on, and at most $k-1$ individual switches remain, so the number of lights on is in the interval $[(2n-1)k+1, 2nk+k-1]$. If $n=0$, no special switches were flipped, and the number of lights on is the interval $[0,k]$. None of these intervals overlap, so we can determine $2n$.
From the above observation, we know that the $2n$ groups turned on in virtue of the special switches will have more lights on than the other $m-2n$ groups. So to determine these $2n$ groups, we simply list the groups in decreasing order of number of lights on; the first $2n$ are the groups whose lights were turned on in virtue of the special switches. This will tell us exactly which special switches were flipped, and we can then determine easily which normal switches were flipped. Thus each of the $\sum_{j=0}^k\binom{mk+m-1}{j}$ possible switch positions generates a unique light pattern.
On the other hand, the total number of light patterns possible is $2^{mk}$, so the number of light patterns you can generate is $\leq 2^{mk}$

A: If $k = 0$, the inequality holds obviously. Now consider a fixed $k \geqslant 1$.
For $m = 1$,$$
\sum_{j = 0}^k \binom{mk + m  - 1}{j} = \sum_{j = 0}^k \binom{k}{j} = 2^k = 2^{mk}.
$$
For $m = 2$,$$
\sum_{j = 0}^k \binom{mk + m  - 1}{j} = \sum_{j = 0}^k \binom{2k + 1}{j} = \frac{1}{2} \cdot 2^{2k + 1} = 2^{mk}.
$$
Suppose the inequality holds for $m \ (m \geqslant 2)$. Because for $0 \leqslant j \leqslant k$,\begin{align*}
&\mathrel{\phantom{=}} \left. \binom{(m + 1)k + m}{j} \middle/ \binom{mk + m  - 1}{j} \right.\\
&= \frac{((m + 1)k + m) \cdots ((m + 1)k + m - j + 1)}{(mk + m  - 1) \cdots (mk + m  - j)}\\
&= \prod_{l = 1}^j \frac{(m + 1)k + m - l + 1}{mk + m  - l} = \prod_{l = 1}^j \left( 1 + \frac{k + 1}{mk + m  - l} \right)\\
&\leqslant \left( 1 + \frac{k + 1}{2k + 2  - k} \right)^j = \left( 1 + \frac{k + 1}{k + 2} \right)^j < 2^j \leqslant 2^k,
\end{align*}
then$$
\sum_{j = 0}^k \binom{(m + 1)k + m}{j} \leqslant 2^k \sum_{j = 0}^k \binom{mk + m  - 1}{j} \leqslant 2^k \cdot 2^{mk} = 2^{(m + 1)k}.
$$
By induction on $m$, the inequality holds for all $m \in \mathbb{N}_+$.


text:
Q: Net core Key vault configuration using Azure.Security.KeyVault.Secrets I have found out it is easy to connect to Azure KeyVault using Managed Identity. The documentation shows how to do it :
             var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(
                    azureServiceTokenProvider.KeyVaultTokenCallback));

            config.AddAzureKeyVault(
                $"https://{builtConfig["KeyVaultName"]}.vault.azure.net/",
                keyVaultClient,
                new DefaultKeyVaultSecretManager());

Then I realized it requires the package Microsoft.Azure.KeyVault which is deprecated. So I'm struggling to figure out how to do the above with SDK 4. All the documentation I find is related to SDK 3.

[EDIT]
I have found out the following code works to get the azure KeyVault Secret using Managed Identiy with SDK 4. However I can't see how to add this to my configuration. It used to be done with  config.AddAzureKeyVault() from the Microsoft.Extensions.Configuration.AzureKeyVault Package however it is not compatible with the SDK 4 SecretClient:
  return Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, config) =>
                {
                    var azureCredentialOptions = new DefaultAzureCredentialOptions();

                    var credential = new DefaultAzureCredential(azureCredentialOptions);
                    var secretClient = new SecretClient(new System.Uri("https://mykeyvault.vault.azure.net/"), credential);
                    var secret = secretClient.GetSecret("StorageConnectionString");
                    config.AddAzureKeyVault()
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
        }

A: AS per June 2020
First thing is that Microsoft.Azure.KeyVault is not deprecated but replaced. Using the old nuget package is still a valid option.
I imagine in the future, the Microsoft.Extensions.Configuration.AzureKeyVault nuget package will use the new Azure.Security.KeyVault.Secrets package.
In my experience I would stick with the existing library and wait for future updates.
If you really want to use the Azure.Security.KeyVault.Secrets, you can implement your own custom configuration builder.
I had a look at the existing key vault configuration code on github and here is a simplified/modified version that you could use.
First install these nuget packages Azure.Identity and Azure.Security.KeyVault.Secrets.
The new key vault secrets package uses IAsyncEnumerable so you need to update your project to target C#8.0: update you csproj file with <LangVersion>8.0</LangVersion>.
Azure Key Vault Secret configuration code:
public interface IKeyVaultSecretManager
{
    bool ShouldLoad(SecretProperties secret);

    string GetKey(KeyVaultSecret secret);
}

public class DefaultKeyVaultSecretManager : IKeyVaultSecretManager
{
    public bool ShouldLoad(SecretProperties secret) => true;

    public string GetKey(KeyVaultSecret secret)
        => secret.Name.Replace("--", ConfigurationPath.KeyDelimiter);
}

public class AzureKeyVaultConfigurationProvider : ConfigurationProvider
{
    private readonly SecretClient _client;
    private readonly IKeyVaultSecretManager _manager;

    public AzureKeyVaultConfigurationProvider(SecretClient client, IKeyVaultSecretManager manager)
    {
        _client = client ?? throw new ArgumentNullException(nameof(client));
        _manager = manager ?? throw new ArgumentNullException(nameof(manager));
    }

    public override void Load() => LoadAsync().ConfigureAwait(false).GetAwaiter().GetResult();

    private async Task LoadAsync()
    {
        var data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

        await foreach (var secretProperties in _client.GetPropertiesOfSecretsAsync())
        {
            if (!_manager.ShouldLoad(secretProperties) || secretProperties?.Enabled != true)
                continue;

            var secret = await _client.GetSecretAsync(secretProperties.Name).ConfigureAwait(false);
            var key = _manager.GetKey(secret.Value);
            Data.Add(key, secret.Value.Value);
        }

        Data = data;
    }
}

public class AzureKeyVaultConfigurationSource : IConfigurationSource
{
    public SecretClient Client { get; set; }

    public IKeyVaultSecretManager Manager { get; set; }

    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        return new AzureKeyVaultConfigurationProvider(Client, Manager);
    }
}

public static class AzureKeyVaultConfigurationExtensions
{
    public static IConfigurationBuilder AddAzureKeyVault(
        this IConfigurationBuilder configurationBuilder,
        SecretClient client,
        IKeyVaultSecretManager manager = null)
    {
        if (configurationBuilder == null)
            throw new ArgumentNullException(nameof(configurationBuilder));

        if (client == null)
            throw new ArgumentNullException(nameof(client));

        configurationBuilder.Add(new AzureKeyVaultConfigurationSource()
        {
            Client = client,
            Manager = manager ?? new DefaultKeyVaultSecretManager()
        });

        return configurationBuilder;
    }
}

You can now use this configuration builder in your project like that:
public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
        {
            var azureCredentialOptions = new DefaultAzureCredentialOptions();
            var credential = new DefaultAzureCredential(azureCredentialOptions);
            var secretClient = new SecretClient(new System.Uri("https://mykeyvault.vault.azure.net/"), credential);

            config.AddAzureKeyVault(secretClient);
        })
            .UseStartup<Startup>();
}

A: As it turned out, I found the proper way to do it with SDK 4. I had to install the package  azure.extensions.aspnetcore.configuration.secrets and then the code is simply :
   var credential = new DefaultAzureCredential();

   config.AddAzureKeyVault(new System.Uri("https://mykv.vault.azure.net/"), credential);

then to use it
configuration["StorageConnectionString"]

A: For your info, if you're using Azure Key Vault secrets in your App Service or Azure Functions application settings, you don't have to add extra code to get the key vault value.
You just need to change your app settings values (in azure portal), with your key vault references.
For the steps, look at https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references
Setting example using key vault references:
{
"name": "DatabaseSettings:ConnectionString",
"value": "@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/DatabaseConnectionSettingSecret/ec96f02080254fxxxxxxxxxxxxxxx)",
"slotSetting": false
}
But this doesn't work for a local development, instead you should use plain secret value. But for me it's okay, because your local development uses different secret value and you don't add your local.settings.json to source control.

A: Latest working solution with version 4 library. My stack is .netcore 3.1 and I am using it inside an Azure Web App to access a secret from Azure KeyVault.
First thing first - go through this MS Doc link
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
//..........

 var kvUri = "https://YOURVAULTNAME.vault.azure.net/";
 var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
 KeyVaultSecret secret = client.GetSecret("SECRETNAME");
                       // Can also use await.....GetSecretAsync()

 this.ConnectionString = secret.Value.ToString();
 \\thats my internal variable, secret.Value.ToString() is required value

I assume here that you have

*

*Created keyVault in Azure

*created a Managed identity in App Service(Using 'Identity' option in app service)

*Added above identity in Azure KeyVault('Access policies' option)

A: I am using something like this,
var keyVaultEndpoint = GetKeyVaultEndpoint();
if (!string.IsNullOrEmpty(keyVaultEndpoint))
{
 // Pass appropriate connection string
 var azureServiceTokenProvider = new
 AzureServiceTokenProvider(certThumbprintConnectionString);
 var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(
 azureServiceTokenProvider.KeyVaultTokenCallback));
 config.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
}
private static string GetKeyVaultEndpoint() => "https://<<key-vault-name>>.vault.azure.net";


text:
Q: Get only list of user with latest update by days I am struggling to write a query to display list of users that check-in in a day, but if the same user check-in twice or more, it would take the latest in a day. For example user A check-in in the morning, then check-in again in the evening, then the system will display only his latest check-in in the list of users that check-in in that day.
This is my table:
CHECKIN_TABLE

id | checkin_datetime        | user_id | office_id
1    2020-12-02 09:07:09.290   1         D01
2    2020-12-02 15:13:42.645   1         D02
3    2020-12-02 12:25:12.823   2         D01
4    2020-12-03 13:12:05.523   1         D01

Then I would like to write a query that generate output like this:
date       | user_id | office_id
2020-12-02   1         D02
2020-12-02   2         D01
2020-12-03   1         D01

A: You can use a correlated subquery:
select convert(date, checkin_datetime), user_id, office_id
from CHECKIN_TABLE ct
where ct.checkin_datetime = (select max(ct2.checkin_datetime)
                             from CHECKIN_TABLE ct2
                             where ct2.user_id = ct.user_id and
                                   convert(date, ct2.checkin_datetime) = convert(date, ct.checkin_datetime)
                           );

Or you can use row_number():
select convert(date, checkin_datetime), user_id, office_id
from (select ct.*,
             row_number() over (partition by ct.user_id, convert(date, ct.checkin_datetime)
                                order by ct.checkin_datetime desc
                               ) as seqnum
      from CHECKIN_TABLE ct
     ) ct
where seqnum = 1;

A: You can use NOT EXISTS:
SELECT CONVERT(DATE, c.checkin_datetime) date, c.user_id, c.office_id
FROM CHECKIN_TABLE c
WHERE NOT EXISTS (
  SELECT 1 FROM CHECKIN_TABLE
  WHERE user_id = c.user_id
    AND CONVERT(DATE, checkin_datetime) = CONVERT(DATE, c.checkin_datetime)
    AND checkin_datetime > c.checkin_datetime
)

See the demo.
Results:
> date       | user_id | office_id
> :--------- | ------: | :--------
> 2020-12-02 |       1 | D02
> 2020-12-02 |       2 | D01
> 2020-12-03 |       1 | D01

A: If your [Id] column is uniqe and auto incremental, Try this:
SELECT CONVERT(date, [checkin_datetime]) AS [date]
     , user_id
     , office_id
 FROM CHECKIN_TABLE C
 JOIN
(
    SELECT MAX(id) AS [id]
     FROM CHECKIN_TABLE
    GROUP BY user_id, office_id
)T ON C.id = T.id


text:
Q: Java - Multithreading - volatile I wanted to do make a program that allows to start x threads and all threads are supposed to do a job:

counting average from Math.random() when number > 0.

I started doing it without volatile boolean and it did not work.
But with volatile boolean it works as expected.
Could anyone explain me please why? Would it be possible to make it differently?
public class Worker extends Thread {

    private int number;
    private double average = 0;
    private volatile boolean cancelled;

    public Worker(int number) {
        this.number = number;
        cancelled = false;
    }

    public void run() {
            while (!cancelled) {
                if (number > 0) {
                    for (int i = 0; i < number; i++) {
                        average += Math.random();
                        if (number - 1 == i) {
                            average = average/this.number;
                            number = 0;
                            System.out.println(Thread.currentThread().getName() + " average is: " + average);
                        }
                    }
                }
        }
        System.out.println(Thread.currentThread().getName() + " is cancelled...");
    }

    public void cancel() {
        this.cancelled = true;
    }

    public double getAverage() {
        return this.average;
    }

    public void setNumber(int number) {
        this.number = number;
    }

}

    public class Executor {

    private List<Worker> activeThreads;
    private Double[] array;

    public Executor(){
        activeThreads = new ArrayList<>();
    }

    public void createThreads(int number, int count){
        for(int i = 0; i < number; i++){
            Worker worker = new Worker(count);
            worker.setName("Thread " + i);
            activeThreads.add(worker);
            array = new Double[number];
            worker.start();
        }
    }

    public void cancelThreads(){
        int count = 0;
        for(Worker w : activeThreads){
            w.cancel();
            try {
                  array[count] = w.getAverage();
                  count++;
                  w.join();
            } catch (InterruptedException ex) {
                System.out.println("Interrupted exception");
                Thread.currentThread().interrupt();
            }
        }
        getFinalAverage();
    }

    public void startJob(int num){
        activeThreads.forEach(t -> t.setNumber(num));
    }

    public void getActiveThreads(){
        System.out.println(Thread.getAllStackTraces().keySet().size());
    }

    private void getFinalAverage(){
        double finalAverage = 0;
        for(Double d : Arrays.asList(array)){
            finalAverage += d;
        }
        finalAverage = finalAverage / array.length;
        System.out.println("Final average is " + finalAverage);
    }
}


text:
Q: ng-repeat directive sort the data when using (key, value) I have a code something like this with ng-repeat = "(key,value) in data".
In Controller:
  $scope.Dates = {"Today":"30",
                  "This Week":"42",
                  "This Month": "Oct",
                  "This Quarter" : "Bad",
                  "This Year" : 2013
                                }

and ng-repeat directive as

{{key}} ==> {{value}}

The output comes in sorted order as
This Month ==> Oct
This Quarter ==> Bad
This Week ==> 42
This Year ==> 2013
Today ==> 30

How to get rid of this sorting(strange) as I want keys to be used in code.. I checked google group but there was a fiddle for using two arrays of which one was storing the key values. http://jsfiddle.net/Saulzar/puhML/3/b . Don't want to go with this approach.

A: There is actually an answer:
it's called orderBy and not sort:
https://docs.angularjs.org/api/ng/filter/orderBy
{{ orderBy_expression | orderBy : expression : reverse}}

      {{friend.name}}
      {{friend.phone}}
      {{friend.age}}

Your list just needs to be a list, and you might need an index to know set order
$scope.Dates = [{index:1, "Today":"30"},
                  {index:2,"This Week":"42"},
                  {index:3,"This Month": "Oct"},
                  {index:4,"This Quarter" : "Bad"},
                  {index:5,"This Year" : 2013}]

and then

          {{key}}
          {{value}}

A: This is limitation of JavaScript not Angular.
From ECMAScript Third Edition:

4.3.3 An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive
  value, object, or function. A function stored in a property of an
  object is called a method.

From ECMAScript Language Specification

The [...] order of enumerating the properties [...]
  is not specified.

Angular sorts object keys explicitly in order to provide at least some sort of persistent behavior.
Workaround is to iterate over extracted keys:

  {{key}} ==> {{Dates[key]}}

$scope.keys = function(obj){
  return obj? Object.keys(obj) : [];
}

$scope.Dates = {
  "Today":"30",
  "This Week":"42",
  "This Month": "Oct",
  "This Quarter" : "Bad",
  "This Year" : 2013
};

A: This is fixed as of Angular 1.4.
See details here:

Previously, the order of items when using ngRepeat to iterate over object properties was guaranteed to be consistent by sorting the keys into alphabetic order.
Now, the order of the items is browser dependent based on the order returned from iterating over the object using the for key in obj syntax.
It seems that browsers generally follow the strategy of providing keys in the order in which they were defined...

A: I was able to sort an Object of Strings by Key alphabetically like this with ng-repeat!
In my controller:
$scope.build_config = {
  build_path :  "/x/eng/build",
  arch : "x86",
  variant : "debug",
  run_method : "boot",
};

$scope.get_keys = function (obj) {
  if (obj)
    return Object.keys(obj);
};

In my HTML:

       {{key}}
       {{selected.build_config[key]}}

A: EDIT: I've filed a bug, feel free to +1
ECMAScript does not specify order in which keys should be iterated, however all major browsers implement objects as linked hash map (preserves order) and a lot of js libraries depend on this behavior and so we've got used to it and it's hardly going to change.
Angular on the other hand (which is totally unexpected) sort it alphabetically. I've inspected the source code myself, it is hard-coded there and it would be nice if it got resolved one day. Otherwise the (k, v) in obj feature is completely useless.
You really cant do anything with that, tricking angular to think your result is an array is not useful for anything, because you would need numeric keys then...
If this is okay, you can define getter for length:
Object.defineProperty(yourResultObjectOrPrototype, 'length', {
  get: function(){
    return Object.keys(this).length;
  }
})

Otherwise you'll need some kind of filter which will iterate object using for(var k in obj) and store result in array.

A: Object.keys doesn't reserve the order - FYI
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
// array like object with random key ordering
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(an_obj)); // console: ['2', '7', '100']

I convert it into an array of object
$scope.Dates = [
        { id: "Today",      value:"30" },
        { id: "This Week",  value:"42" },
        { id: "This Month", value: "Oct" },
        { id: "This Quarter", value : "Bad" },
        { id: "This Year",  value : 2013 }
    ];

{{date.id}} -> {{date.value}}

http://jsfiddle.net/2hqew68k/1/

A: Well, as explained in Angular's documentation for ngRepeat
https://docs.angularjs.org/api/ng/directive/ngRepeat#iterating-over-object-properties
when using it to iterate over the properties of an object, it will not work

The built-in filters orderBy and filter do not work with objects, and
  will throw an error if used with one.

The best solution in this case I think that is using arrays instead of an object and its properties. Therefore, just convert it to an array, iterating the properties of your object and pushing to the new array for example. After all, I think that would be the natural choice to a collection, instead of a single object with many properties.


text:
Q: flex-direction в ie11 Не работает flex-direction:column; в IE11. Перепробывала все возможные префиксы, которые только нашла - ничего не помагает. На картинка-скриншот того как отображается в хром и как в ие. В консоле интернет експлорера flex-direction:column; не зачеркнуто.
Вот код
 table{
        width: 100%;
        padding: 10px 0;
        border-collapse: collapse;
    }
        th{
            position: relative;
                padding: 5px 12px;
            font-weight: bold;
            border: 1px solid #f3f3f3;

        }
        th.asg-th_sort:after{
            position: absolute;
            top: calc(50% - 8px);
            right: 3px;
            font-family: FontAwesome;
            content: '\f0dc';
            display: block;
        }
        tr:nth-child(1n){
            background-color: #fff;
        }
        tr:nth-child(2n){
            background-color: #f9f9f9;
        }
        tr{
            min-height: 50px;
        }
        td{
            padding: 5px;
            text-align: center;
            border: 1px solid #f3f3f3;
            position: relative;
        }
        td:before {
                /* Now like a table header */
                position: absolute;
        }
    @media only screen and (max-width: 992px) {

        /* flex-table */
        table{
            width: 100%;
            display: -webkit-flex;
            display: -ms-flex;
            display: flex;
            overflow: hidden;
            background: none;
        }
        thead {
          display: -webkit-flex;
          display: -ms-flex;
          display: flex;
          -ms-flex-negative: 0;
         flex-shrink: 0;
          min-width: min-content;
      }
        tbody {
            display: -webkit-flex;
            display: -ms-flex;
            display: flex;
            position: relative;
            overflow-x: auto;
            overflow-y: hidden;
        }
        tr {
          display: flex;
          -webkit-box-orient:vertical;
          -webkit-box-direction:normal;
              -ms-flex-direction:column;
                  flex-direction:column;
              -ms-flex-negative: 0;
                 flex-shrink: 0;
          }

A: Разобралась с проблемой. Просто в ie некоректно работабт flex-елементы, когда внутри них вложены елементы с дисплеям таблицы - врод table row и table col.


text:
Q: Showing two vertices have same degree under a certain condition Let $L$ be the Laplacian matrix of a simple, connected graph, and $\mathcal{P}_j$ the projector into the vertex $v_j$, represented by the appropriate canonical basis vector $(0,...,1,...,0)^T$. Given the positive real parameters $t$ and $\lambda$, consider the functions $$P_j(n,t,\lambda)=v_j^T e^{-it(\lambda L-\mathcal{P}_j)}s, $$ where $s=\frac{1}{\sqrt{n}}(1,...,1)^T$ is the normalized uniform vector.
My objective is to show that the condition $P_i=P_j$ implies the degrees of the two vertices $v_i$ and $v_j$ are the same. Does anyone have any tips on how to accomplish this?

A: I'll take $\lambda=1$ and use $E_j$ for $\mathcal{P}_j$. The $k$-th time derivative of $e^{-it(L-E_j)}s$ at $t=0$ is
\[
(-i(L-E_j))^k s.
\]
Now $(L-E_j)s = -v_j$ (because $Ls=0$) and, noting that $E_j=v_jv_j^T$, we have
\[
(L-E_j)^2s = -(L-E_j)v_j = -Lv_j +v_j.
\]
Therefore
\[
v_j^T(L-E_j)^2s = -v_j^T Lv_j + 1 = - L_{j,j} + 1.
\]
Since $L_{j,j}$ is the degree of vertex $j$, it follows that if $P_i=P_j$, then $i$ and $j$ have the same degree.
[I am curious as to where this problem is coming from?]


text:
Q: How do i add a button to a youtube video thumbnail? Chrome Extension I want to add a button to each thumbnail in youtube, this means the youtube homepage and the relevant videos column. I tried this in my content script but couldn't get it to work.
function addButtons()
{
    var overlays = document.querySelectorAll('#overlays');
    overlays.forEach(function(overlay,index) {
        var btn = document.createElement("BUTTON");
        var t = document.createTextNode("Heyy");
        btn.appendChild(t);
        overlay.appendChild(btn);
    });
}

I saw that the divs with the id "overlay" in youtube contained other elements such as the video length and progress graphics so i thought it would be smart to insert the button there, but it did not work.
Questions:
To which element should i "add" the buttons for them to show up on one corner of the thumbnails?
Am i adding the buttons the correct way?


text:
Q: I have a question about Lebesgue measure Suppose $A$ is Lebesgue measurable, show that for each $\epsilon>0$, there exists an open set, $O$, such that $A\subset O$, and $\lambda(O-A)<\epsilon$. (note: $\lambda$ is the Lebesgue measure in $\mathbb R$).
If we just deal with the finite case first, then $\lambda(A)<\infty$, since $A\subset\mathcal{M}$, we have that $\lambda(A)=\lambda^{*}(A) = \inf\{\sum_{n=1}^\infty l(I_n) \ | \ \{I_n\}_{n=1}^\infty\text{ is a sequnce of open intervals s.t. }A\subset\cup_{n=1}^\infty I_n\}$, So I guess my question is how do I reference this sequence of open intervals? Can I just say that we have the "smallest" such $I_n$(call it $O$) that covers A, and the sum of the lengths of the intervals is the outer measure of A so, $\lambda(O-A)=\lambda(O)-\lambda(A)=\lambda^*(O)-\lambda^*(A)=0<\epsilon$. Any comments would greatly be appreciated.

A: Assume $\lambda(A)<\infty$.
First off, we know that the Lebesgue measure is only a restriction of the outer measure to measurable sets, i.e. as you also wrote $\lambda(A)=\lambda^*(A)$ for measurable $A$. We do not need to prove that. This is the definition of $\lambda$.
You cannot pick a smallest covering by intervals because the infimum may not be taken.
This is like if you take the infimum of the set $\{1/n\,:\,n\in\mathbb{N}\}$ (which is $0$): $1/n$ will get really, really close to $0$ as $n$ gets really, really large, but it will never quite reach zero. The minute you pick one of the $1/n$'s and declare it the "smallest" you lose because you're still infinitely many $n$'s far from $0$. But you can pick an $\epsilon>0$ and decide that's how far you want to approximate $0$ and then the definition of the infimum gives you an $n$ such that $1/n-0<\epsilon$.
Now let us do the same here. Choose $\epsilon>0$. By the definition of the infimum, there exists a sequence of open intervals $(I_n)_n$ covering $A$ such that
$$\sum_{n=1}^\infty l(I_n)-\lambda(A)<\epsilon$$
Now write $O=\bigcup_{n=1}^\infty I_n$. $O$ is open as union of open intervals. By the subadditivity of the Lebesgue measure
$$\lambda(O)\le \sum_{n=1}^\infty l(I_n)$$
All of this we could have done also without assuming measurability of $A$, since also the outer measure $\lambda^*$ is subadditive.
The crucial step now, which you also already did, uses measurability of $A$ (this follows literally from the classical Carathéodory definition of measurability, though I don't know if you used that to define measurability, so look it up if not!):
$$\lambda(O)=\lambda(A)+\lambda(O- A)$$
This implies
$$\lambda(O-A)=\lambda(O)-\lambda(A)\le \sum_{n=1}^\infty l(I_n) - \lambda(A)<\epsilon$$
which is what we wanted to prove. The interesting part is that you can actually also use this property (called outer regularity of the Lebesgue measure) to define measurability and derive the Carathéodory definition back from it (there may be some subleties with all sets of measure $0$ being measurable or not, but let's not go into this now).
Edit:
All this was for the case $\lambda(A)<\infty$. If $\lambda(A)=\infty$, we need to choose an exhaustion of $A$ by compact sets, i.e.
$$A_k=\{x\in A\,:\,|x|\le k\}$$
then $\lambda(A_k)<\infty$ and $\bigcup_{k=1}^\infty A_k=A$. We apply the above argument to obtain a sequence of open sets $(O_k)_k$ with the property
$$\lambda(O_k-A_k)\le \frac{\epsilon}{2^k}$$
Now define $O=\bigcup_{k=1}^\infty O_k$. Then
$$\lambda(O-A)=\lambda\left(\bigcup_{k=1}^\infty (O_k-A)\right)\le \sum_{k=1}^\infty \lambda(O_k-A)\le \sum_{k=1}^\infty \lambda(O_k-A_k)\le \epsilon$$


text:
Q: InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_8' with dtype float I try to run a python program for CNN training, the following error message is thrown, my Python version is Python 3.5.3 :: Anaconda 4.1.1 (64-bit) and tensorflow version is 1.0.1,
Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\client\session.py", line 1022, in _do_call return fn(*args)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\client\session.py", line 1004, in _run_fn status, run_metadata)
  File "C:\anaconda\Anaconda3_411\lib\contextlib.py", line 66, in __exit__ next(self.gen)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_8' with dtype float [[Node: Placeholder_8 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\anaconda\Anaconda3_411\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
    execfile(filename, namespace)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "C:/development/workspace/tensorflow_ws/cmf_ts18.py", line 109, in <module>
    sess.run(train_step, feed_dict={xs:batch_xs, ys:batch_ys})
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\client\session.py", line 767, in run
    run_metadata_ptr)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\client\session.py", line 965, in _run
    feed_dict_string, options, run_metadata)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\client\session.py", line 1015, in _do_run
    target_list, options, run_metadata)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\client\session.py", line 1035, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_8' with dtype float
     [[Node: Placeholder_8 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op 'Placeholder_8', defined at:
  File "<stdin>", line 1, in <module>
  File "C:\anaconda\Anaconda3_411\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
    execfile(filename, namespace)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "C:/development/workspace/tensorflow_ws/cmf_ts18.py", line 54, in <module>
    keep_prob = tf.placeholder(tf.float32, shape=None)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\ops\array_ops.py", line 1502, in placeholder
    name=name)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 2149, in _placeholder
    name=name)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 763, in apply_op
    op_def=op_def)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\framework\ops.py", line 2327, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\anaconda\Anaconda3_411\lib\site-packages\tensorflow\python\framework\ops.py", line 1226, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_8' with dtype float
     [[Node: Placeholder_8 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

The program sources,
import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={xs:v_xs, keep_prob:1})
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs:v_xs, ys:v_ys, keep_prob:1})
    return result

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')

xs = tf.placeholder(tf.float32, shape=[None, 784])
ys = tf.placeholder(tf.float32, shape=[None, 10])
keep_prob = tf.placeholder(tf.float32, shape=None)
x_image = tf.reshape(xs, [-1,28,28,1])

W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

init = tf.global_variables_initializer()
sess = tf.Session()

sess.run(init)

for i in range(500):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs:batch_xs, ys:batch_ys})
    if i % 50 == 0:
        print(compute_accuracy(mnist.test.images, mnist.test.labels))

A: In this line, you need to feed keep_prob:
sess.run(train_step, feed_dict={xs:batch_xs, ys:batch_ys})

to
sess.run(train_step, feed_dict={xs:batch_xs, ys:batch_ys, keep_prob: 0.5})


text:
Q: Cloud Foundry over Google Cloud. Missing API target endpoint I've succesfully deployed "Cloud Foundry" on "Google Cloud".
Now I've installed the "Cloud Foundry CLI" on my laptop and I want to manage my instance of "Cloud Foundry" on "Google Cloud".
I've launched the following command
cf login -a

but this command requires also the IP address of a target API endpoint.
I don't understand how to get the IP address I need.

A: The API endpoint is the IP of a load balancer, or a DNS name that resolves to the load balancer. CF comes with an HAProxy that can serve this purpose for development environments (it is not horizontally scalable).
To get started quickly, identify the public IP of the HAProxy VM in your deployment.
e.g.
cf login -a http://10.100.0.34 -u admin


text:
Q: How can I use a drawn rectangle by myself as a button You know that if we want to use a button in android, we use the following code:
        button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, B.class);
startActivity(intent);
        }
    });

Now my question is if I draw a rectangle by myself, can I use the MotionEvent class for this purpose? If it is possible so how is it? I wrote the following code to draw a rectangle. Now I want that the rectangle behaviors like the button in the above code.
public class B extends View {
  Paint paint;
B(Context context) {
   super(context);
    paint = new Paint();
    }
@Override
 protected void onDraw(Canvas canvas) {
paint.setColor(Color.RED);
canvas.drawRect(10,20,40,100,paint);

}
@Override
public boolean onTouchEvent(MotionEvent event){
    return true; // I am a little confused in this section in spite of searching in internet.
}
}

A: You can assign on OnClickListener to any View, not just Buttons. You don't need to override onTouchEvent().
Alternatively, you can use a regular Button (or just a View even) and just give a solid rectangle as a background drawable.


text:
Q: examples of continuous, bounded function What are the examples for a continuous vector valued function $f:\mathbb{R}^2\times \mathbb{R}\rightarrow \mathbb{R}^2$ which is also bounded on it's entire domain?

A: Pick any continuous from $\mathbb{R}^3$ to $\mathbb{R}^2$ whose image is fully contained inside some disk and it will do. There are infinitely many such functions.
As mentioned by David in the comments any constant function will do. For a slightly more complicated example consider the the following continuous function $f:\mathbb{R}^2 \to \mathbb{R}^2$
$$f(x,y) =
\begin{cases}
      \langle x,y \rangle & x^2+y^2\leq 1 \\
      \frac{\langle x,y \rangle}{\sqrt{x^2+y^2}} & x^2+y^2>1
   \end{cases}
$$
Since $f$ maps the whole $\mathbb{R}^2$ into the unit disk, composing it with any continuous function from $\mathbb{R}^2\times\mathbb{R}$ to $\mathbb{R}^2$ will yield a continuous bounded function.
For example if $g_1(\langle x,y \rangle,z)= \langle x,y \rangle$ then $f\circ g_1$ will be continuous and bounded. For other functions to compose you can try:
\begin{align}
g_2(\langle x,y \rangle,z) &= \langle x+z,y-z \rangle\\
g_3(\langle x,y \rangle,z) &= \langle xz,yz \rangle\\
g_4(\langle x,y \rangle,z) &= \langle y,-x \rangle\\
g_5(\langle x,y \rangle,z) &= \langle e^{x+y}\cos{z}, e^{x-y}\sin{z} \rangle\\\end{align}


text:
Q: Funny Django Session Behaviour In my settings.py I have SESSION_EXPIRE_AT_BROWSER_CLOSE = True. I am not sure if that is the right place to do that and if need to import anything first. But it wasn't working on Chrome Version 37.0.2062.124 m as it persists the session data. My session-dependent page still opens even after closing and re-opening the browser.
So, I manually cleared the session data (csrftoken, sessionid and Database Data in Chrome's Settings session is no longer working at all. Even if I login and try to open home page in another tab of the same browser (Chrome, Firefox, IE, Safari) I get redirected to login page.
def index(request): #login page.
    if 'id' in request.session:
        Proceed to Home Page
    if request.method == 'POST':
        Do the needful
        set request.session['id']
        proceed to Home Page
    return render(request, 'myapp/index.html')

def home(request): #homp page
    if 'id' not in request.session:
        redirect to login page
    return render(request, 'myapp/home.html')

How do I go about making this work?

A: I think, set_expiry(0) will do the job. here the doc
def index(request): #login page.
  if 'id' in request.session:
      Proceed to Home Page
  if request.method == 'POST':
      Do the needful
      set request.session['id']
      request.session.set_expiry(0)#<---
      proceed to Home Page
  return render(request, 'myapp/index.html')


text:
Q: Filtering/accessing date in Bio Entrez pubmed pulls with python I have a list of criteria (names and date ranges of when papers were published) to obtain a list of published papers. I'm using Biopython's Bio Entrez to obtain papers from Entrez.
I can query and get results by author name but I'm not figuring out how to deal with the data to get the dates in there. This is what I've done:
handle = Entrez.esearch(db="pubmed", term = "" )
result = Entrez.read(handle)
handle.close()
ids = result['IdList']
print ids
#for each ids go through it and pull the summary
for uid in ids:
     handle2 = Entrez.esummary(db="pubmed", id=uid, retmode= "xml")
     result2 = Entrez.read(handle2)
     handle2.close()

Now the output looks like this
 [{'DOI': '10.1016/j.jmoldx.2013.10.002', 'Title': 'Validation of a next-generation sequencing assay for clinical molecular oncology.', 'Source': 'J Mol Diagn', 'PmcRefCount': 7, 'Issue': '1', 'SO': '2014 Jan;16(1):89-105', 'ISSN': '1525-1578', 'Volume': '16', 'FullJournalName': 'The Journal of molecular diagnostics : JMD', 'RecordStatus': 'PubMed - indexed for MEDLINE', 'ESSN': '1943-7811', 'ELocationID': 'doi: 10.1016/j.jmoldx.2013.10.002', 'Pages': '89-105', 'PubStatus': 'ppublish+epublish', 'AuthorList': ['Cottrell CE', 'Al-Kateb H', 'Bredemeyer AJ', 'Duncavage EJ', 'Spencer DH', 'Abel HJ', 'Lockwood CM', 'Hagemann IS', "O'Guin SM", 'Burcea LC', 'Sawyer CS', 'Oschwald DM', 'Stratman JL', 'Sher DA', 'Johnson MR', 'Brown JT', 'Cliften PF', 'George B', 'McIntosh LD', 'Shrivastava S', 'Nguyen TT', 'Payton JE', 'Watson MA', 'Crosby SD', 'Head RD', 'Mitra RD', 'Nagarajan R', 'Kulkarni S', 'Seibert K', 'Virgin HW 4th', 'Milbrandt J', 'Pfeifer JD'], 'EPubDate': '2013 Nov 6', 'PubDate': '2014 Jan', 'NlmUniqueID': '100893612', 'LastAuthor': 'Pfeifer JD', 'ArticleIds': {'pii': 'S1525-1578(13)00219-5', 'medline': [], 'pubmed': ['24211365'], 'eid': '24211365', 'rid': '24211365', 'doi': '10.1016/j.jmoldx.2013.10.002'}, u'Item': [], 'History': {'received': '2013/02/04 00:00', 'medline': ['2014/08/30 06:00'], 'revised': '2013/08/23 00:00', 'pubmed': ['2013/11/12 06:00'], 'aheadofprint': '2013/11/06 00:00', 'accepted': '2013/10/01 00:00', 'entrez': '2013/11/12 06:00'}, 'LangList': ['English'], 'HasAbstract': 1, 'References': ['J Mol Diagn. 2014 Jan;16(1):7-10. PMID: 24269227'], 'PubTypeList': ['Journal Article'], u'Id': '24211365'}]

I tried looking at using Efetch which doesn't always have xml output from what I understand. I thought I could filter for dates by parsing through xml as so
proj_start = '2009 Jan 01'
proj_start = time.strptime(proj_start, '%Y %b %d')
for paper in results2:
    handle = open(paper)
    record = Entrez.read(handle)
    pub_dat=time.strptime(record["EPubDate"], '%Y %b %d')

I get the error:
       Traceback (most recent call last):
   File "<ipython-input-39-13bcded12392>", line 2, in <module>
    handle = open(paper)

  TypeError: coercing to Unicode: need string or buffer, ListElement found

I feel like I'm missing something and I should be able to feed this directly into the query. I also don't understand why this method doesn't work even though it seems a harder way to do this. Is there a better way to do this?  I tried to do this using xml.etree but I also got a similar like error.

A: You don't need to open(paper) : paper is a already Python dict (basically JSON). If you want the accepted date you can access it like this:
paper['History']['accepted']
'2013/10/01 00:00'


text:
Q: How to correctly implement upshot's deleteEntity function on a child record I have a Parent Child table structure.
I am trying to delete a child record. Here is my Simplified View Model.
MyNameSpace.ParentViewModel = function () {
    var self = this;
    self.dataSource = upshot.dataSources.GetRecords.refresh();
    self.jobs = self.dataSource.getEntities();

    self.removeChild1 = function (child) {
        $.each(self.jobs(), function() {
            this.JobStep.remove(jobStep);
        });
    };

    self.removeChild2 = function (child) {
        self.dataSource.deleteEntity(child);
    };
};

MyNameSpace.Parent = function (data) {
    var self = this;

    self.Id = ko.observable(data.Id);
    self.SomeProperty = ko.observable(data.SomeProperty);

    upshot.addEntityProperties(self, "Parent:#MyNameSpace.Models");
};

MyNameSpace.Child = function (data) {
   var self = this;

    self.Id = ko.observable(data.Id);
    self.ParentId = ko.observable(data.ParentId);
    self.Parent = ko.observable(data.Parent ? new MyNameSpace.Parent(data.Parent) : null);
    self.SomeChildProperty = ko.observable(data.SomeChildProperty );
    upshot.addEntityProperties(self, "Child:#MyNameSpace.Models");
};

When I try to delete a child record using removeChild1 I get the error:
Use 'deleteEntity' to delete entities from your array.  Destructive delete is not yet implemented.

When I try to delete a child record using removeChild2 I get an error:
'Entity not cached in data context. '

Obviously in the first version I am referencing the child record's ObservableArray collection and removing it from there. The correct object is removed but the non-implementation error kills it.
In the second version I am using upshot and EF magic and I'm not sure what is going wrong.
Any ideas?


text:
Q: How can I charge Macbook Air M1 and still use the Thunderbolt port? The Macbook Air M1 has two Thunderbolt ports.  One of them is used by the charger.  I have a Thunderbolt to dual DisplayPort dongle which works well and I'd like to continue using.  But that leaves nowhere to plug in a keyboard or other wired devices.
Since the port used for power delivery isn't doing anything else, surely I could use the data connectors on that port for USB?  I would need some kind of 'splitter', probably a passive device, which allows both a power cable and a data cable to connect to the same port.  Does that exist?
I could get a Thunderbolt dock, but that seems like overkill somehow.  And not all Thunderbolt docks provide dual DisplayPort outputs.  Is there some simpler alternative?  If there really isn't, I would be interested in dock recommendations that meet the minimum requirement of dual DP.  Or perhaps if the dock itself provides a Thunderbolt port, I could connect the display dongle into that.
(The Thunderbolt-to-DisplayPort dongle drives a older 5k monitor which requires dual DisplayPort connections.  Although the M1 does not support two external monitors, it does work with this single monitor connected over two cables.  So I cannot replace it with something that only gives a single DisplayPort output.  And not all TB-to-dual-DP converters will work, I had to hunt for this one, so I'd like to keep using it if possible.)


text:
Q: Doctrine - Undefined clas const JSON_ARRAY I got this message error: On stack trace I cant find the file that produces it. I'm using symfony 5 and doctrine.
Undefinied class constant 'JSON_ARRAY'

I search in all project for JSON_ARRAY with out results.
Stack Trace:

A: I had this issue because I was using Symfony 5.2 and doctrine/dbal 3.
The thing is Symfony 5.2 is only compatible with  doctrine/dbal 2.
So I set dbal to v2:
$ composer require doctrine/dbal:^2
$ composer install

Then everything worked fine
Issue: https://github.com/symfony/symfony/pull/43994

A: I find it was an update on composer json file that produce that error. After looked for a solution I find that symfony got an update that produces that error on the new versions. My solution was going to last checkpoint I did for composer json file.


text:
Q: How to handle overlapping dates in MySQL? Im attempting to build a reservation system with items (ie Beamers), now I want to check with AJAX wheter the given item_id is available during the users given start and enddate
edit: was a bit unclear, I want to do it with MySQL and PHP, the AJAX is just the way I request the result (available yes/no)
How would I go with this?
My table looks 'like' this:
reservation_id int PK
reservation_createDate datetime
reservation_startDate datetime
reservation_endDate datetime
item_id int FK(items.item_id)

Let's say I have the following already 'reserved' in the DB:
(for convienience, all item_id = 1)
reservation_id 1, item_id 1, from 2011-7-10 till 2011-7-14
reservation_id 2, item_id 1, from 2011-7-14 till 2011-7-16
reservation_id 3, item_id 1, from 2011-7-16 till 2011-7-20

And the user wants to reserve item_id 1 from 2011-7-12 till 2011-7-18, which as you can see wont go due to all 3 reservations being in the way for that..
How would I do this with MySQL ?

A: SELECT COUNT(*)<1 AS Available FROM `TABLE` WHERE (`startDate`>CHECKING_START_TIME AND `startDate`<CHECKING_END_TIME) OR (`endDate`>CHECKING_START_TIME AND `endDate`<CHECKING_END_TIME) OR (`startDate`<CHECKING_START_TIME AND `endDate`>CHECKING_END_TIME)

If the result is greater than 0, then there is an overlap


text:
Q: Pass value to colorbox on same page Hello Guys please help me out,
I want pass Data-id value to Color Box Popup
so what sholud i have to do..please help me
or is there any other way to do the same..
JS

HTML CODE

ABC

DEF

XYZ

Color Box Popup
This is pop window on same page.

   Data-id = "" // Here I want to display data-id of clicked Post, Like if we click ABC Post than in Popup data-id is equal to 1, if click XYZ tha data-id equql to 3 in Popup

A: Try this code..

..

above for html..
   $(document).ready(function(){
     $('#popupdiv').hide();
    $('.inline').click(function(){
       var data_id = $(this).data('id');
       $('#popupdiv').show();
       $('#inline_content').html("Data-id ="+data_id);
    });
   });

and you have to give an id to that div which contains style="display:none"; so that by using that id you can change the css to block or else