text:
Q: Show and hide div on check and uncheck of checkbox I want to hide and show div on check and uncheck of checkbox. I am getting the parent and finding the div which I want to hide. But code is not running
Jquery is:
$('.show-check').click(function() {
    if (this.checked) {
        $(this).parent().find('.div-check').fadeIn('slow');
    } else
        $(this).parent().find('.div-check').fadeOut('slow');
});

HTML:

  Logo:

      <input type="checkbox" class="show-check" checked>

        <input type="text" class="file-input" placeholder="No file" readonly>

             UPLOAD <input type="file" style="display: none;">

A: Why your code does not work :
$(this).parent() will give you label - and find('.div-check') won't return anything.

Use closest() - to get a common parent which has the desired child element,
$(this).closest('.type-details').find('.div-check').fadeIn('slow');

Also, I'd suggest you use change() event instead of click() on checkbox in the below,
$('.show-check').click(function() {

A: Use this script instead

$('.show-check').click(function() {
  if ($(this).prop('checked')) {
    $(this).parents('.type-details').find('.div-check').fadeIn('slow');
  } else
    $(this).parents('.type-details').find('.div-check').fadeOut('slow');
});

  Logo:

      <input type="checkbox" class="show-check" checked>

        <input type="text" class="file-input" placeholder="No file" readonly>

            UPLOAD <input type="file" style="display: none;">

A: Use $('input').is(':checked')
In your example: $(this).is(':checked')
You have to use parents() to select the correct wrapper to find your element div-check
var $check = $(this).parents('.type-details').find('.div-check');
$('.show-check').click(function() {
   if ($(this).is(':checked')) {
       $check.fadeIn('slow');
   } else
       $check.fadeOut('slow');
});

A: Use  $(this).closest(".type-details").find('.div-check') to get the div-check div and hide/show it.

$('.show-check').click(function() {
    if (this.checked) {
        $(this).closest(".type-details").find('.div-check').fadeIn('slow');
    } else {
        $(this).closest(".type-details").find('.div-check').fadeOut('slow');
      }
});

  Logo:

      <input type="checkbox" class="show-check" checked>

        <input type="text" class="file-input" placeholder="No file" readonly>

            UPLOAD <input type="file" style="display: none;">

A: $('.show-check').click(function() {
    if ($(this).is(":checked")) {

        $(this).closest('.type-details').find('.div-check').fadeIn('slow');
    } else
        $(this).closest('.type-details').find('.div-check').fadeOut('slow');
});

A: Try this code :
$('.show-check').click(function() {
    $(this).toggleClass('checked unchecked');
    if ($(this).hasClass('checked')) {
        $(this).parents('.type-details').find('.div-check').fadeIn('slow');
    } else {
        $(this).parents('.type-details').find('.div-check').fadeOut('slow');
    }
});

 <input type="checkbox" class="show-check checked" checked>


text:
Q: new user powershell get-service What is wrong with this code?
Clear-Host

$num1 = Read-Host "Please choose"

1 = service
2 = process
3 = pinging
4 = multiplying a number

$num1 = Read-Host " Please enter a number for service "
Snumber = 1
Get-Service

$num2 = Read-Host " Please enter a number for process"
$Number = 2
Get-Process

$num3 = Read-Host " Please enter a number to ping"
$Number = 3
$ComputerName = Read-Host "enter the FQDN of the target computer"
Test-Connection $ComputerName FQDN

$num4 = Read-Host " Please enter a number for double the number"
$Number = 4
$num4 = Read-Host "Pleas enter number 5"
Write_Host "Your original number was 5, now it's 10"`enter code here`

why is the script not respecting the user choice?
why is it looping?
The script is not pinging.
 I want the user to choose one number then the task is completed and the cursor is back to the question please choose a number? so on
I don't want it to go to the next question after it complete the task

A: There is so much wrong with your code block so I just re-wrote 90% of it with what I believe you are trying to accomplish.
# Sets up the visual choices for the user
Function Choose-Selection {
    Clear-Host

    Write-Host "1: Service"
    Write-Host "2: Process"
    Write-Host "3: Pinging"
    Write-Host "4: Multiplying a number"
    Write-Host "Q: Quit" -ForegroundColor Red
}

# Displays those choices
Choose-Selection
# Enters loop
Do{
    # Checks for a selection from the user
    $selection = Read-Host "Please make a selection"
    # Switches take the input from the user and runs code based on the switch
    Switch($selection) {
        '1' {
            $num1 = Read-Host " Please enter a number for service"
            (Get-Service)[$num1]
            Sleep -Seconds 5
            Choose-Selection
        } '2' {
            $num2 = Read-Host " Please enter a number for process"
            (Get-Process)[$num2]
            Choose-Selection
        } '3' {
            $ComputerName = Read-Host "enter the FQDN of the target computer"
            Test-Connection -ComputerName $ComputerName
            Sleep -Seconds 5
            Choose-Selection
        } '4' {
            $num4 = Read-Host " Please enter a number for double the number"
            # Checks to see if input is an int. If not an int, terminates script
            If($num4 -match '^[0-9]+$') {
                "Your original number was $num4, now it's $([int]$num4*2)"
            } Else {
                Throw "You have not entered a valid number. Menu terminated."
            }
            Sleep -Seconds 5
            Choose-Selection
        } 'q'  {

            'Leaving Menu...'
            Return
        }
    }
 }

Until($response -eq 'Q')

Your problems as I see them.
# This section does nothing except cause errors
1 = service
2 = process
3 = pinging
4 = multiplying a number

# What is SNumber? Variables need a $ in front of them
$num1 = Read-Host " Please enter a number for service "
Snumber = 1
# What are you doing with the number they give you? You are retrieving all services
Get-Service

$num2 = Read-Host " Please enter a number for process"
$Number = 2
# What are you doing with the number they give you? You are retrieving all Processed
Get-Process

$num3 = Read-Host " Please enter a number to ping"
# What is this variable used for?
$Number = 3
$ComputerName = Read-Host "enter the FQDN of the target computer"
Test-Connection $ComputerName FQDN

$num4 = Read-Host " Please enter a number for double the number"
# What is this variable used for?
$Number = 4
$num4 = Read-Host "Pleas enter number 5"
# What if I chose the number 200, it will still say I chose 5
# Well it would if it didn't error out. The command is Write-Host
Write_Host "Your original number was 5, now it's 10"`enter code here`

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap v3 nav-justified witdh not actually equal Quoting from http://www.w3schools.com/bootstrap/bootstrap_ref_comp_navs.asp

.nav-justified    Makes navigation tabs/pills equal widths of their parent, at screens wider than 768px. On smaller screens, the nav tabs/pills are stacked

I reckon that each <li> element inside the nav-justified <ul> should have the same width.
However this seem to not be the case as pills widths stretch to accomodate the contained text, at least in this example: http://www.bootply.com/0pEQ2iml8q# (on chrome 46)
The pills all have different widths, and there seems to be no justification.
What am I missing there?

A: 366 days later and I stumble upon more or less the same issue. I had an issue with the pictures inside the nav-pills, the end pill being smaller in both height and width than the other two pills I included.
I noticed too that the text was the culprit of the last pill's size, however the longest text was in the first pill which confused me as this was perfect size. (maybe due to the pills being formatted inside containers rows and columns)
I fixed my issue by simply implementing the answer in this question : Same height for nav tabs
Though do note, I found this removes the 'stacking' functionality of the pills when resized down to xs. Chuck the css into a Media Query like so, and all should be fine:
@media screen and (min-width: 480px) {
.nav-pills{
    display: flex;
}
.nav-pills li {
    display: flex;
    flex: 1;
}

.nav-pills li  a {
    flex: 1;
}
}


text:
Q: I get a signing error when I add an image to Assets in the SwiftUI Tutorial I get a signing error when I add an image to Assets in the SwiftUI Tutorial
I'm working on the SwiftUI Tutorial, but when I add an image or JSON file to Assets, I get the following Sign Error.
CodeSign /Users/k~~/Library/Developer/Xcode/DerivedData/SwiftUIPractice-ctdnfoihimrfqeejvxgheakcfzfv/Build/Products/Debug-iphonesimulator/SwiftUIPractice.app (in target 'SwiftUIPractice' from project 'SwiftUIPractice')
    cd /Users/~~/project/SwiftUIPractice
    export CODESIGN_ALLOCATE\=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate

    Signing Identity:     "-"

    /usr/bin/codesign --force --sign - --entitlements /Users/~~/Library/Developer/Xcode/DerivedData/SwiftUIPractice-ctdnfoihimrfqeejvxgheakcfzfv/Build/Intermediates.noindex/SwiftUIPractice.build/Debug-iphonesimulator/SwiftUIPractice.build/SwiftUIPractice.app.xcent --timestamp\=none --generate-entitlement-der /Users/~~/Library/Developer/Xcode/DerivedData/SwiftUIPractice-ctdnfoihimrfqeejvxgheakcfzfv/Build/Products/Debug-iphonesimulator/SwiftUIPractice.app

/Users/~~/Library/Developer/Xcode/DerivedData/SwiftUIPractice-ctdnfoihimrfqeejvxgheakcfzfv/Build/Products/Debug-iphonesimulator/SwiftUIPractice.app: replacing existing signature
/Users/~~/Library/Developer/Xcode/DerivedData/SwiftUIPractice-ctdnfoihimrfqeejvxgheakcfzfv/Build/Products/Debug-iphonesimulator/SwiftUIPractice.app: code object is not signed at all
In subcomponent: /Users/~~/Library/Developer/Xcode/DerivedData/SwiftUIPractice-ctdnfoihimrfqeejvxgheakcfzfv/Build/Products/Debug-iphonesimulator/SwiftUIPractice.app/Assets.car
Command CodeSign failed with a nonzero exit code


text:
Q: What is the origin of the phrase "knock-down, drag-out"? I can find this phrase in a few dictionaries:

knock-down, drag-out — marked by extreme violence or bitterness and by the showing of no mercy knock–down, drag–out political debates

But I don't fully understand why these two phrases became such a common saying. Why did this particular combination come to mean a particularly terrible fight or war? Is there something in each phrase that brings a particular meaning? Or does it just something that sounds catchy?
If it helps, here are the notes from etymonline that points toward the 1800s as the time of origin:

knock — Knock-down, drag-out is from 1827.
drag — Drag-out "violent fight" is from c.1859

"Drag-out" came to mean "violent fight" but almost 30 years after the phrase "knock-down, drag-out" was recorded. So why did the phrase include "drag-out"? What did it mean in the 1820s?

A: Bartlett's Dictionary of Americanisms, 1848, s.v. Drag out says 'A "knock down and drag out" is a fight carried to extremities [my emphasis]. The term drag out seems also to be used, at the South, to denote a bully, a tearer', and gives an instance:

Set to your partner, Dolly,—Cut him out, Jim, —Sald does put her foot down good. The yellow roan's up! He a rael [sic] stormer, ring clipper, snow belcher, and drag out —Southern Sketches

I have always taken the phrase in more or less Chris' sense: that a drag-out fight is one in which the defeated party is not only unable to rise for thirty seconds but remains indefinitely unconscious, so that he must be dragged out of the ring.
Early uses, however, show that drag out is an action performed by a fighter on his opponent:

A few days since, says the Rochester Republican, a clever good-for-nothing fellow came to our village, from the country, and being somewhat taken with its appearance, and feeling "pretty cute," took too much of "the creature;" the consequence of which was, a little zig-zag in his movements, and a design to "knock down and drag out." —Ladies Museum, Providence [, R.I.], Jan 21, 1826
... one of those dashing blades, so frequently to be encountered in the southern country, who, despising the humdrum monotony of regular life, are ready for adventure—lads of the turf—the muster-ground—the general affray—the men who can whip their weight in wild cats—whose general rule it is to knock down and drag out. —W. Gilmore Simms, Guy Rivers: A Tale of Georgia, 1834
"Once, my son, old Jim could knock down, drag out, whip, lift, or throw any man in all Sangamon" —Edmund Flagg, The far West, 1838
I can knock down and drag out a whole regiment, whip my weight in Indians, swallow a buffalo whole, and pick my teeth with the bones. —"A Duel in Georgia", The London Journal, No.172, Vol.VII, June 10, 1848

The grisly character of that performance—and the 'extremities' to which a fight might be carried—is suggested in Richard Penn Smith's Colonel Crockett's Exploits and Adventures in Texas ... Written by Himself (1837). On the road to Texas Crockett hears a fight in the distance, and arrives at the last moment:

I saw the uppermost one (for I could not see the other) make a heavy plunge with both his thumbs, and at the same instant I heard a cry in the accent of keenest torture, "Enough! My eye is out."
   [...]
   "Now blast your corn-shucking soul," said the victor, a lad about eighteen, as he rose from the ground, "come cutt'n your shines 'bout me agin, next time I come to the Court House, will you! —Get our owl-eye in agin if you can.

It turns out that the 'fight' was no such thing, but a solo affair in which "the young man had played all the parts for his own amusement"; and the author says that

All that I had heard and seen was nothing more or less than what is called a rehearsal of a knock-down and drag-out fight.

Unlikely as it may seem, the notion that drag-out originally signified mutilation appears to be corroborated in a US House of Representatives speech defying certain proposals by members from Kentucky:

These men never had a meeting some few years ago, as travellers in these two districts relate, either for sacred or secular purposes, but that, when the service was over, they always took a set to, a knock down and drag out. It has been said to be a fact, that twenty years ago, in either of those districts, whenever such a festival had happened over night, boys might, in the morning, gather up several baskets full of eyes, noses, ears, and other members subjected to depredation by the established laws of combat.  —Speech of Mr. Burges, of Rhode Island..., 1828.

I find it interesting that the two earliest instances of drag-out I have found, from 1826 and 1828, both originate with Rhode Island sources.

A: It's a fight. It's violent enough that one opponent is knocked out. They easiest way to remove an unconscious person from the pub (arena/venue/other) where the fight took place is to drag him out to the street. There would be no dragging out without the knockdown, so that may be why the shorter phrase came after the longer one was already in use.

A: It comes from boxing; a knock-down, drag-out fight is a lengthy one, where both opponents are closely matched in size, skill, and weight, so they manage to knock each other down (but not out), and extend the fight.


text:
Q: 'Invoke-WebRequest -Body Get-Content' breaking JSON I am trying to send the content of a JSON file to an API using Invoke-WebRequest. I have validated the JSON file and it's healthy. I can also send the JSON file successfully using a REST Client (Postman and Insomnia), so I know the JSON data and API are fine.
When I send the file using PowerShell, I get a 400 response 400: "The Request Content is not a valid JSON string".
I am loading the content of the file using Get-Content $File.FullName -Raw, this seems to be where the issue is.
function Send-JSONFiles(){

    $FilesToUpload = @(Get-ChildItem -Path "$ProgramPath\Uploads" -filter *.json)
    $Target = "https://theapi.com/api"

    Foreach ($File in $FilesToUpload){

        if($Dev){Write-host "Sending" $File.FullName "to" $Target$URI}

        Try{

            Invoke-WebRequest -uri "$Target" -Method Post -ContentType "application/json" -Headers @{ "Authorization" = "bearer " + $Global:token; "Cache-Control" = "no-cache"; } -Body (Get-Content $File.FullName -Raw)

        }Catch{
            Write-host $_
            Write-host $_.Exception.Response.StatusCode.Value__
            Write-host ($_.ErrorDetails.Message).error
        }
    }
}

I would expect this to work the same as my REST clients. GEt the JSON data from the file and POST it to the target - I'm not sure why this would be breaking the JSON?


text:
Q: Prefix length with a value 0 In IPv6, the prefix length can range from 0-128. What is the significance of the prefix length with a value 0? Does it suggest that there is no network?
Thanks!

A: A prefix length of 0 (usually written as ::/0) means that no bits of the prefix are fixed and all 128 bits can be 0 or 1. So basically it includes all IPv6 addresses. This ranges from :: (same as 0000:0000:0000:0000:0000:0000:0000:0000) to ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff.
When specifying the default route you define the route as ::/0 (every IPv6 address).


text:
Q: SQL updating table col1 | col2 | col3
-----------------------------
1    |  1   |  somestring 12
1    |  2   |  somestring sd
2    |  1   |  somestring gvr
2    |  2   |  somestring 46
3    |  1   |  somestring sdf
3    |  2   |  somestring 4

....
i want to UPDATE col3 WHERE col2 = 2
to be a CONCAT of col1 with col3
and REPLACE all ' ' with '-'.
Also if col1 < 10 add a leading '0' so '1' would be '01'
in total the value of col3 should be '01-somestring-sd'
can someone please help me with the statement?

A: Create data/insert data
CREATE TABLE Table1
    (`col1` INT, `col2` INT, `col3` VARCHAR(255))
;

INSERT INTO Table1
    (`col1`, `col2`, `col3`)
VALUES
    (1, 1, 'somestring 12'),
    (1, 2, 'somestring sd'),
    (2, 1, 'somestring gvr'),
    (2, 2, 'somestring 46'),
    (3, 1, 'somestring sdf'),
    (3, 2, 'somestring 4')
;

Query
UPDATE
 Table1
SET
   col3 =
     CASE
         WHEN col1 < 10
         THEN REPLACE(CONCAT('0', col1, '-', col3), ' ', '-')
         ELSE REPLACE(CONCAT(col1, '-', col3), ' ', '-')
     END
WHERE
 col2 = 2

Result
1 queries executed, 1 success, 0 errors, 0 warnings

Query: UPDATE Table1 SET col3 = CASE WHEN col1 < 10 THEN REPLACE(CONCAT('0', col1, '-', col3), ' ', '-') ELSE REPLACE(CONCAT(col1, '-',...

3 row(s) affected

Query
SELECT * FROM Table1

Result
  col1    col2  col3
------  ------  ------------------
     1       1  somestring 12
     1       2  01-somestring-sd
     2       1  somestring gvr
     2       2  02-somestring-46
     3       1  somestring sdf
     3       2  03-somestring-4

A: UPDATE TABLE1 SET COL3=CONCAT(IF(COL1 < 10,0,''),COL1,REPLACE(COL3, ' ', '-' )) WHERE COL2=2

Try above code.
Hope this will helps.

A: just use Concat and Replace
update table_name as t set t.col3 =
CONCAT(if(t.col1<10,0,''),t.col1,REPLACE(t.col3,' ','-')) where
t.col2 =2;

A: Try this
Update table1
set
col3 = concat((case when col1>10 then '0'+col1 else col1 end),'-',REPLACE(COL3, ' ','-' ))
where col2=2


text:
Q: Clustering data by averaging where the gradient is small My data that is fairly continuous but has different regions. I'm trying to detect the center of each such cluster (approximately).
Basically, the data is a list of 2D vectors, in a (N,2) numpy array. The data has a characteristic structure that looks like this:

You can see the two clusters appear (partially) in the list and I would like to detect their centers (say, by averaging). I have computed the L2 norm of the gradient and it seems to correlate very well with the boundaries between clusters (of course).
Next, I'd like to average out all the data points that belong to each cluster, as defined by the magnitude of the gradient (unless someone has a better idea, of course). I'd like to avoid looping over the data and use vectorized operations instead so that it runs fast. This is the difficulty for me.
Thanks!
Constraints:

*

*I can't use any library besides numpy and opencv.

A: I found a way that uses a for loop, but it iterates over the clusters rather than over the values so you still have the benefits of vectorized operations.
I set up my test case in accordance to your problem description like so:
data = np.ndarray((30,2))
data[:10] = np.random.random((10,2)) * 4 + 60
data[10:20] = np.random.random((10,2)) * 4 + 70
data[20:30] = np.random.random((10,2)) * 4 + 80
norms = np.linalg.norm(np.gradient(data,axis=0), axis=1)

And I found the centers like this:
threshold = 5 # Specify how much greater the gradient is at the threshold

# get cluster boundaries by finding the indexes at which
# the next gradient norm is significantly smaller
boundaries = np.where(norms[:-1] > norms[1:] + threshold)
# add start and end boundaries
boundaries = np.hstack((0,*boundaries,None))

centers = np.ndarray((boundaries.size-1,2)) # empty array for centers
# calulate the mean between each set of boundaries
for i in range(boundaries.size-1):
  centers[i] = np.mean(data[boundaries[i]:boundaries[i+1]],axis=0)

print(centers)

Which for my test case got me these centers:
[[62.34829355 62.46226224]
 [71.70243459 72.23661627]
 [81.54729804 82.25504445]]

A: If you are allowed to use OpenCV, I think that the easiest way to get the job done would be using cv2.kmeans:
import numpy as np
import cv2
import matplotlib.pyplot as plt

vectors = np.array([[64, 20],
                    [64, 21],
                    [65, 19],
                    [65, 20],
                    [66, 20],
                    [68, 19],
                    [74, 4],
                    [74, 7],
                    [74, 8],
                    [75, 3],
                    [75, 4]], dtype=np.float32)

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)
flags = cv2.KMEANS_RANDOM_CENTERS
_, labels, centers = cv2.kmeans(data=vectors,
                                K=2,
                                bestLabels=None,
                                criteria=criteria,
                                attempts=100,
                                flags=flags)

plt.scatter(vectors[:, 0], vectors[:, 1], s=30)
for x, y in centers:
    plt.scatter(x, y, s=300, marker='s')

Your data are represented as small dots while cluster centers are displayed as large squares.


text:
Q: Fetch Timestamp for last 12am in specific Timezone The problem at hand is to find out the generic timestamp last time it was 12 am in a specific timezone.
e.g. I want timestamp when it was last 12 am in India (IST).
Tried the following:
var IST = new Date(new Date().getTime() + 330*60*1000)
IST.setHours(0);
IST.setMinutes(0);
IST.setSeconds(0);
IST.setMilliseconds(0);

Turns out it returns the last time it was 12 am in GMT.

A: When you use
new Date()

this gives the date in the current timezone.
When you change your code to:
var UTC = new Date();
UTC.setUTCHours(UTC.getUTCHours());
UTC.setUTCMinutes(UTC.getUTCMinutes());
UTC.setUTCSeconds(UTC.getUTCSeconds());
UTC.setUTCMilliseconds(UTC.setUTCMilliseconds());

now UTC is set to current UTC time. Add time difference for eventual changes in date and set time to 00:00:00
UTC = new Date(UTC.getTime() + 330*60*1000);
UTC.setUTCHours(0);
UTC.setUTCMinutes(0);
UTC.setUTCSeconds(0);
UTC.setUTCMilliseconds(0);

you will get the last UTC 12 am. Add to this the time difference with the required timezone, and you should get the right time.
var IST = new Date(UTC.getTime() + 330*60*1000);


text:
Q: Open Terminal Window using Java I want to know how to open the Linux Terminal in a Java app.
Further explanation: I have a java app. There is a button inside my java app. When you click that button, the Linux Terminal must pop open. I won't run or do anything on the Terminal, I just want to open it.
I've been searching for few hours but found none that suites what I want to do.
Please write the code itself and don't answer by giving links like "this may help".

A: you can  do something like this:
try {
Runtime r = Runtime.getRuntime();
String myScript = .....
String[] cmdArray = {"xterm", "-e", myScript + " ; le_exec"};
r.exec(cmdArray).waitFor();
} catch (InterruptedException ex){
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}

A: I got the answer from the post
import java.io.*;

class TerminalLauncher
{
    public static void main(String args[]) throws IOException
    {
        String command= "/usr/bin/xterm";
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec(command);
    }
}

Hope this helps


text: Q: Principal Component analysis with netcdf data I would like to run PCA for different variables from ERA5. I have 4 different variables, 30 years of hourly data and longitude, latitude. How should I transform the data to run PCA?


text:
Q: AWS Rekognition gives an InvalidS3Exeption error Every time I run the command
aws rekognition detect-labels --image "S3Object={Bucket=BucketName,Name=picture.jpg}" --region us-east-1

I get this error.
InvalidS3ObjectException: An error occurred (InvalidS3ObjectException) when calling the DetectLabels operation: Unable to get image metadata from S3.  Check object key, region and/or access permissions.

I am trying to retrieve labels for a project I am working on but I can't seem to get past this step. I configured aws with my access key, secret key, us-east-1 region, and json as my output format.
I have also tried the code below and I receive the exact same error (I correctly Replaced BucketName with the name of my bucket.)
import boto3

BUCKET = "BucketName"
KEY = "picture.jpg"

def detect_labels(bucket, key, max_labels=10, min_confidence=90, region="eu-west-1"):
    rekognition = boto3.client("rekognition", region)
    response = rekognition.detect_labels(
        Image={
            "S3Object": {
                "Bucket": bucket,
                "Name": key,
            }
        },
        MaxLabels=max_labels,
        MinConfidence=min_confidence,
    )
    return response['Labels']

for label in detect_labels(BUCKET, KEY):
    print "{Name} - {Confidence}%".format(**label)

I am able to see on my user account that it is calling Rekognition.
Image showing it being called from IAM.
It seems like the issue is somewhere with my S3 bucket but I haven't found out what.

A: Region of S3 and Rekognition should be the same for stability reasons.
More info: https://forums.aws.amazon.com/thread.jspa?threadID=243999

A: Kindly check your IAM Role Policies/Permissions, Also check the same for the role created for the lambda function. It's better to verify the policy using IAM Policy Checker.
I am facing a similar issue, This might due to the Permissions and Policy attached with the IAM Roles and with S3 Bucket. Need to check the metadata as well for the objects in S3 bucket.
My S3 bucket Policy:
{
"Version": "2012-10-17",
"Id": "Policy1547200240036",
"Statement": [
    {
        "Sid": "Stmt1547200205482",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::459983601504:user/veral"
        },
        "Action": [
            "s3:GetObject",
            "s3:PutObject"
        ],
        "Resource": "arn:aws:s3:::esp32-rekognition-459983601504/*"
    }
]
}

Cross-origin resource sharing (CORS):
[
{
    "AllowedHeaders": [
        "*"
    ],
    "AllowedMethods": [
        "PUT",
        "POST",
        "GET",
        "DELETE"
    ],
    "AllowedOrigins": [
        "*"
    ],
    "ExposeHeaders": []
}
]

A: If you use Server Side encryption for the bucket via KMS, remember to also have/give access to IAM role to decrypt using the KMS


text:
Q: Formatting MM/DD/YYYY dates in textbox in VBA I'm looking for a way to automatically format the date in a VBA text box to a MM/DD/YYYY format, and I want it to format as the user is typing it in. For instance, once the user types in the second number, the program will automatically type in a "/". Now, I got this working (as well as the second dash) with the following code:
Private Sub txtBoxBDayHim_Change()
    If txtBoxBDayHim.TextLength = 2 or txtBoxBDayHim.TextLength = 5 then
    txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/"
End Sub

Now, this works great when typing. However, when trying to delete, it still enters in the dashes, so its impossible for the user to delete past one of the dashes (deleting a dash results in a length of 2 or 5, and the sub is then run again, adding in another dash). Any suggestions on a better way to do this?

A: I too, one way or another stumbled on the same dilemma, why the heck Excel VBA doesn't have a Date Picker. Thanks to Sid, who made an awesome job to create something for all of us.
Nonetheless, I came to a point where I need to create my own. And I am posting it here since a lot of people I'm sure lands on this post and benefit from it.
What I did was very simple as what Sid does except that I do not use a temporary worksheet. I thought the calculations are very simple and straight forward so there's no need to dump it somewhere else. Here's the final output of the calendar:

How to set it up:

*

*Create 42 Label controls and name it sequentially and arranged left to right, top to bottom (This labels contains greyed 25 up to greyed 5 above). Change the name of the Label controls to Label_01,Label_02 and so on. Set all 42 labels Tag property to dts.

*Create 7 more Label controls for the header (this will contain Su,Mo,Tu...)

*Create 2 more Label control, one for the horizontal line (height set to 1) and one for the Month and Year display. Name the Label used for displaying month and year Label_MthYr

*Insert 2 Image controls, one to contain the left icon to scroll previous months and one to scroll next month (I prefer simple left and right arrow head icon). Name it Image_Left and Image_Right
The layout should be more or less like this (I leave the creativity to anyone who'll use this).

Declaration: We need one variable declared at the very top to hold the current month selected.
Option Explicit
Private curMonth As Date

Private Procedure and Functions:
Private Function FirstCalSun(ref_date As Date) As Date
    '/* returns the first Calendar sunday */
    FirstCalSun = DateSerial(Year(ref_date), _
                  Month(ref_date), 1) - (Weekday(ref_date) - 1)
End Function

Private Sub Build_Calendar(first_sunday As Date)
    '/* This builds the calendar and adds formatting to it */
    Dim lDate As MSForms.Label
    Dim i As Integer, a_date As Date

    For i = 1 To 42
        a_date = first_sunday + (i - 1)
        Set lDate = Me.Controls("Label_" & Format(i, "00"))
        lDate.Caption = Day(a_date)
        If Month(a_date) <> Month(curMonth) Then
            lDate.ForeColor = &H80000011
        Else
            If Weekday(a_date) = 1 Then
                lDate.ForeColor = &HC0&
            Else
                lDate.ForeColor = &H80000012
            End If
        End If
    Next
End Sub

Private Sub select_label(msForm_C As MSForms.Control)
    '/* Capture the selected date */
    Dim i As Integer, sel_date As Date
    i = Split(msForm_C.Name, "_")(1) - 1
    sel_date = FirstCalSun(curMonth) + i

    '/* Transfer the date where you want it to go */
    MsgBox sel_date

End Sub

Image Events:
Private Sub Image_Left_Click()

    If Month(curMonth) = 1 Then
        curMonth = DateSerial(Year(curMonth) - 1, 12, 1)
    Else
        curMonth = DateSerial(Year(curMonth), Month(curMonth) - 1, 1)
    End If

    With Me
        .Label_MthYr.Caption = Format(curMonth, "mmmm, yyyy")
        Build_Calendar FirstCalSun(curMonth)
    End With

End Sub

Private Sub Image_Right_Click()

    If Month(curMonth) = 12 Then
        curMonth = DateSerial(Year(curMonth) + 1, 1, 1)
    Else
        curMonth = DateSerial(Year(curMonth), Month(curMonth) + 1, 1)
    End If

    With Me
        .Label_MthYr.Caption = Format(curMonth, "mmmm, yyyy")
        Build_Calendar FirstCalSun(curMonth)
    End With

End Sub

I added this to make it look like the user is clicking the label and should be done on the Image_Right control too.
Private Sub Image_Left_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
                                 ByVal X As Single, ByVal Y As Single)
    Me.Image_Left.BorderStyle = fmBorderStyleSingle
End Sub

Private Sub Image_Left_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)
    Me.Image_Left.BorderStyle = fmBorderStyleNone
End Sub

Label Events:  All of this should be done for all 42 labels (Label_01 to Lable_42) Tip: Build the first 10 and just use find and replace for the remaining.
Private Sub Label_01_Click()
    select_label Me.Label_01
End Sub

This is for hovering over dates and clicking effect.
Private Sub Label_01_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)
    Me.Label_01.BorderStyle = fmBorderStyleSingle
End Sub

Private Sub Label_01_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)
    Me.Label_01.BackColor = &H8000000B
End Sub

Private Sub Label_01_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
                             ByVal X As Single, ByVal Y As Single)
    Me.Label_01.BorderStyle = fmBorderStyleNone
End Sub

UserForm Events:
Private Sub UserForm_Initialize()
    '/* This is to initialize everything */
    With Me
        curMonth = DateSerial(Year(Date), Month(Date), 1)
        .Label_MthYr = Format(curMonth, "mmmm, yyyy")
        Build_Calendar FirstCalSun(curMonth)
    End With

End Sub

Again, just for the hovering over dates effect.
Private Sub UserForm_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)

    With Me
        Dim ctl As MSForms.Control, lb As MSForms.Label

        For Each ctl In .Controls
            If ctl.Tag = "dts" Then
                Set lb = ctl: lb.BackColor = &H80000005
            End If
        Next
    End With

End Sub

And that's it. This is raw and you can add your own twist to it.
I've been using this for awhile and I have no issues (performance and functionality wise). No Error Handling yet but can be easily managed I guess. Actually, without the effects, the code is too short.  You can manage where your dates go in the select_label procedure. HTH.

A: I never suggest using Textboxes or Inputboxes to accept dates. So many things can go wrong. I cannot even suggest using the Calendar Control or the Date Picker as for that you need to register the mscal.ocx or mscomct2.ocx and that is very painful as they are not freely distributable files.
Here is what I recommend. You can use this custom made calendar to accept dates from the user
PROS:

*

*You don't have to worry about user inputting wrong info

*You don't have to worry user pasting in the textbox

*You don't have to worry about writing any major code

*Attractive GUI

*Can be easily incorporated in your application

*Doesn't use any controls for which you need to reference any libraries like mscal.ocx or mscomct2.ocx

CONS:
Ummm...Ummm... Can't think of any...
HOW TO USE IT (File missing from my dropbox. Please refer to the bottom of the post for an upgraded version of the calendar)

*

*Download the Userform1.frm and Userform1.frx from here.

*In your VBA, simply import Userform1.frm as shown in the image below.

Importing the form

RUNNING IT
You can call it in any procedure. For example
Sub Sample()
    UserForm1.Show
End Sub

SCREEN SHOTS IN ACTION

NOTE: You may also want to see Taking Calendar to new level

A: This is the same concept as Siddharth Rout's answer. But I wanted a date picker which could be fully customized so that the look and feel could be tailored to whatever project it's being used in.
You can click this link to download the custom date picker I came up with. Below are some screenshots of the form in action.

To use the date picker, simply import the CalendarForm.frm file into your VBA project. Each of the calendars above can be obtained with one single function call. The result just depends on the arguments you use (all of which are optional), so you can customize it as much or as little as you want.
For example, the most basic calendar on the left can be obtained by the following line of code:
MyDateVariable = CalendarForm.GetDate

That's all there is to it. From there, you just include whichever arguments you want to get the calendar you want. The function call below will generate the green calendar on the right:
MyDateVariable = CalendarForm.GetDate( _
    SelectedDate:=Date, _
    DateFontSize:=11, _
    TodayButton:=True, _
    BackgroundColor:=RGB(242, 248, 238), _
    HeaderColor:=RGB(84, 130, 53), _
    HeaderFontColor:=RGB(255, 255, 255), _
    SubHeaderColor:=RGB(226, 239, 218), _
    SubHeaderFontColor:=RGB(55, 86, 35), _
    DateColor:=RGB(242, 248, 238), _
    DateFontColor:=RGB(55, 86, 35), _
    SaturdayFontColor:=RGB(55, 86, 35), _
    SundayFontColor:=RGB(55, 86, 35), _
    TrailingMonthFontColor:=RGB(106, 163, 67), _
    DateHoverColor:=RGB(198, 224, 180), _
    DateSelectedColor:=RGB(169, 208, 142), _
    TodayFontColor:=RGB(255, 0, 0), _
    DateSpecialEffect:=fmSpecialEffectRaised)

Here is a small taste of some of the features it includes. All options are fully documented in the userform module itself:

*

*Ease of use. The userform is completely self-contained, and can be imported into any VBA project and used without much, if any additional coding.

*Simple, attractive design.

*Fully customizable functionality, size, and color scheme

*Limit user selection to a specific date range

*Choose any day for the first day of the week

*Include week numbers, and support for ISO standard

*Clicking the month or year label in the header reveals selectable comboboxes

*Dates change color when you mouse over them

A: Just for fun I took Siddharth's suggestion of separate textboxes and did comboboxes.  If anybody's interested, add a userform with three comboboxes named cboDay, cboMonth and cboYear and arrange them left to right.  Then paste the code below into the UserForm's code module.  The required combobox properties are set in UserFormInitialization, so no additional prep should be required.
The tricky part is changing the day when it becomes invalid because of a change in year or month.  This code just resets it to 01 when that happens and highlights cboDay.
I haven't coded anything like this in a while.  Hopefully it will be of interest to somebody, someday.  If not it was fun!
Dim Initializing As Boolean

Private Sub UserForm_Initialize()
Dim i As Long
Dim ctl As MSForms.Control
Dim cbo As MSForms.ComboBox

Initializing = True
With Me
    With .cboMonth
        '        .AddItem "month"
        For i = 1 To 12
            .AddItem Format(i, "00")
        Next i
        .Tag = "DateControl"
    End With
    With .cboDay
        '        .AddItem "day"
        For i = 1 To 31
            .AddItem Format(i, "00")
        Next i
        .Tag = "DateControl"
    End With
    With .cboYear
        '        .AddItem "year"
        For i = Year(Now()) To Year(Now()) + 12
            .AddItem i
        Next i
        .Tag = "DateControl"
    End With
    DoEvents
    For Each ctl In Me.Controls
        If ctl.Tag = "DateControl" Then
            Set cbo = ctl
            With cbo
                .ListIndex = 0
                .MatchRequired = True
                .MatchEntry = fmMatchEntryComplete
                .Style = fmStyleDropDownList
            End With
        End If
    Next ctl
End With
Initializing = False
End Sub

Private Sub cboDay_Change()
If Not Initializing Then
    If Not IsValidDate Then
        ResetMonth
    End If
End If
End Sub

Private Sub cboMonth_Change()
If Not Initializing Then
    ResetDayList
    If Not IsValidDate Then
        ResetMonth
    End If
End If
End Sub

Private Sub cboYear_Change()
If Not Initializing Then
    ResetDayList
    If Not IsValidDate Then
        ResetMonth
    End If
End If
End Sub

Function IsValidDate() As Boolean
With Me
    IsValidDate = IsDate(.cboMonth & "/" & .cboDay & "/" & .cboYear)
End With
End Function
Sub ResetDayList()
Dim i As Long
Dim StartDay As String

With Me.cboDay
    StartDay = .Text
    For i = 31 To 29 Step -1
        On Error Resume Next
        .RemoveItem i - 1
        On Error GoTo 0
    Next i
    For i = 29 To 31
        If IsDate(Me.cboMonth & "/" & i & "/" & Me.cboYear) Then
            .AddItem Format(i, "0")
        End If
    Next i
    On Error Resume Next
    .Text = StartDay
    If Err.Number <> 0 Then
        .SetFocus
        .ListIndex = 0
    End If
End With
End Sub

Sub ResetMonth()
Me.cboDay.ListIndex = 0
End Sub

A: For a quick solution, I usually do like this.
This approach will allow the user to enter date in any format they like in the textbox, and finally format in mm/dd/yyyy format when he is done editing. So it is quite flexible:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If TextBox1.Text <> "" Then
        If IsDate(TextBox1.Text) Then
            TextBox1.Text = Format(TextBox1.Text, "mm/dd/yyyy")
        Else
            MsgBox "Please enter a valid date!"
            Cancel = True
        End If
    End If
End Sub

However, I think what Sid developed is a much better approach - a full fledged date picker control.

A: You could use an input mask on the text box, too. If you set  the mask to ##/##/#### it will always be formatted as you type and you don't need to do any coding other than checking to see if what was entered was a true date.
Which just a few easy lines
txtUserName.SetFocus
If IsDate(txtUserName.text) Then
    Debug.Print Format(CDate(txtUserName.text), "MM/DD/YYYY")
Else
    Debug.Print "Not a real date"
End If

A: Add something to track the length and allow you to do "checks" on whether the user is adding or subtracting text. This is currently untested but something similar to this should work (especially if you have a userform).
'add this to your userform or make it a static variable if it is not part of a userform
private oldLength as integer

Private Sub txtBoxBDayHim_Change()
    if ( oldlength > txboxbdayhim.textlength ) then
        oldlength =txtBoxBDayHim.textlength
        exit sub
    end if

    If txtBoxBDayHim.TextLength = 2 or txtBoxBDayHim.TextLength = 5 then
    txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/"
    end if
    oldlength =txtBoxBDayHim.textlength
End Sub

A: While I agree with what's mentioned in the answers below, suggesting that this is a very bad design for a Userform unless copious amounts of error checks are included...
to accomplish what you need to do, with minimal changes to your code, there are two approaches.

*

*Use KeyUp() event instead of Change event for the textbox. Here is an example:
Private Sub TextBox2_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

    Dim TextStr As String
    TextStr = TextBox2.Text

    If KeyCode <> 8 Then ' i.e. not a backspace

        If (Len(TextStr) = 2 Or Len(TextStr) = 5) Then
            TextStr = TextStr & "/"
        End If

    End If
    TextBox2.Text = TextStr
End Sub

*Alternately, if you need to use the Change() event, use the following code. This alters the behavior so the user keeps entering the numbers, as
12072003

while the result as he's typing appears as
    12/07/2003

But the '/' character appears only once the first character of the DD i.e. 0 of 07 is entered. Not ideal, but will still handle backspaces.
    Private Sub TextBox1_Change()
        Dim TextStr As String

        TextStr = TextBox1.Text

        If (Len(TextStr) = 3 And Mid(TextStr, 3, 1) <> "/") Then
            TextStr = Left(TextStr, 2) & "/" & Right(TextStr, 1)
        ElseIf (Len(TextStr) = 6 And Mid(TextStr, 6, 1) <> "/") Then
            TextStr = Left(TextStr, 5) & "/" & Right(TextStr, 1)
        End If

        TextBox1.Text = TextStr
    End Sub

A: Private Sub txtBoxBDayHim_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii >= 48 And KeyAscii <= 57 Or KeyAscii = 8 Then 'only numbers and backspace
    If KeyAscii = 8 Then 'if backspace, ignores + "/"
    Else
        If txtBoxBDayHim.TextLength = 10 Then 'limit textbox to 10 characters
        KeyAscii = 0
        Else
            If txtBoxBDayHim.TextLength = 2 Or txtBoxBDayHim.TextLength = 5 Then 'adds / automatically
            txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/"
            End If
        End If
    End If
Else
KeyAscii = 0
End If
End Sub

This works for me. :)
Your code helped me a lot. Thanks!
I'm brazilian and my english is poor, sorry for any mistake.


text:
Q: Proper structure of array for the test POST request im making a new post page in which I`ll be sending data to API.
The POST body parameter is this:
{
    "user": "some user",
    "hashTag": "some hashtag",
    "description": "some text",
    "images": [{
        "postImageURL": "some url",
        "tag": [{
            "tagId": "some id",
            "name": "some name",
            "xPosition": "",
            "yPosition": ""
        }]
    }]
}

Right now Im sending this array:
 func postTap() {
        let parameters: [String:Any] = ["user": "some user",
                                        "hashTag": "somehashtag",
                                        "description": "some text",
                                        "images": []]

// Some code... JSONSerialization and etc...
}

How do I add images, postImageUrl, tag and other properties to the parameter array?
And it would be great if you could share the essential source for learning json structures (nested/flat) and how to parse them correctly. Thank you in advance

A: I find the easiest way to do this is to create an Encodable struct, and populate it with the values you want. You can serialise this to JSON in one go:
struct Tag: Encodable {
    let id: String
    let name: String
    let xPosition: String
    let yPosition: String
}

struct Image: Encodable {
    let postImageURL: String
    let tags: [Tag]
}

struct PostItem: Encodable {
    let user: String
    let hashTag: String
    let description: String
    let images: [Image]
}


text:
Q: Create React with Yarn enter image description here
I want to create react app with yarn but I have error like this and I can not find why I am doing this error

A: You should use yarn cache clean or update yarn to the latest version


text:
Q: Updating elements in a QAbstractListModel from C++ I have a simple QML application.
This application contains a class ObjectModel : public QAbstractListModel, which holds a   ParesisObjectList* mList containing the data displayed on the GUI.
QML snippet:
ListView {
    width: parent.width
    height: parent.height

    model: ObjectModel {
        list: paresisObjectList
    }
    delegate: Text {
        text: type + ": " + identifier + " " + latitude
    }
}

The application connects via UDP to a server, which constantly sends new and updated data fields to be displayed on the GUI.
However, there is my problem. I have no issue to insert a new object using the following method which is called whenever a new item was received via UDP:
void ParesisObjectList::appendItem(ObjectModelItem item)
{
    emit preItemAppended();
    mItems.append(item);
    emit postItemAppended();
}

However, I'm not sure how to update an Item already existing in mItems. I mean, its no issue to change the values, however, I have to notify my GUI somehow to create make sure the value is updated in the GUI as well.
I know, that I have to emit the dataChanged(...) signal in the ObjectModel, but it is requiring the QModelIndex of the position of the updated element.
However, as the update is coming from the C++ side and not trough QML (while calling bool ObjectModel::setData(const QModelIndex &index, const QVariant &value, int role)) I have no clue how to get the QModelIndex to update the specific value.
Thus, my question is: How can I update the elements in the ParesisObjectlist from C++?
Edit:
ParesisObjectList.h
struct ObjectModelItem
{
    QString type;
    double longitude;
    double latitude;
    int identifier;
};

class ParesisObjectList : public QObject
{
    Q_OBJECT
public:
    explicit ParesisObjectList(QObject *parent = nullptr);

    QVector<ObjectModelItem> items() const;

    bool setItemAt(int index, const ObjectModelItem& item);
    bool setItem(const ObjectModelItem& item);

signals:
    void preItemAppended();
    void postItemAppended();

    void preItemRemoved(int inex);
    void postItemRemoved();

    void objectUpdated(ObjectModelItem&, int position);

public slots:
    void appendItem(ObjectModelItem);
    void removeItem(int identifier);

private:
    QVector<ObjectModelItem> mItems;
};

ParesisObjectList.cpp:
ParesisObjectList::ParesisObjectList(QObject *parent) : QObject(parent)
{
}

QVector<ObjectModelItem> ParesisObjectList::items() const
{
    return mItems;
}

bool ParesisObjectList::setItemAt(int index, const ObjectModelItem &item)
{
    if(index < 0 || index >= mItems.size()) {
        return false;
    }
    const ObjectModelItem& oldItem = mItems.at(index);
    if(item.identifier == oldItem.identifier) {
        return false;
    } else {
        mItems[index] = item;
        return true;
    }
}

void ParesisObjectList::appendItem(ObjectModelItem item)
{
    emit preItemAppended();
    mItems.append(item);
    emit postItemAppended();
}

void ParesisObjectList::removeItem(int identifier)
{
    for(int i = 0; i < mItems.size(); i++) {
        if(mItems.at(i).identifier == identifier) {
            emit preItemRemoved(i);
            mItems.removeAt(i);
            emit postItemRemoved();
        }
    }
}

To add an Item to my ParesisObjectList I just call appendItem which emits the correct signals. However, I have no clue how to update an already existing Item. Eg. if I just want to change the latitude or the longitude of the object.

A: QAbstractListModel gives you a helper function index() that creates a QModelIndex based on the row number. So you should be able to use this signal:
int rowThatChanged = <whatever>
emit dataChanged(index(rowThatChanged), index(rowThatChanged));


text:
Q: Splash screen iOS only shown on simulator and at wrong size When I use the code mentioned below, I get the desired splash screen with fade out on the iPhone simulator, but the picture seems to be zoomed with factor 2: I only get the upper left quarter of my initial picture (= launch image), zoomed to full screen. The launch image itself is shown in correct size at startup, before the splash screen kicks in.
Code is entered in didFinishLaunchingWithOptions in AppDelegate.
// Splash screen
    UIImageView*imageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"IMG_1357.png"]];
    [[navigationController view] addSubview:imageView];
    [[navigationController view] bringSubviewToFront:imageView];

    // as usual
    [self.window makeKeyAndVisible];

    //now fade out splash image
    [UIView transitionWithView:self.window duration:4.0f options:UIViewAnimationOptionTransitionNone animations:^(void){imageView.alpha=0.0f;} completion:^(BOOL finished){[imageView removeFromSuperview];}];

Furthermore the splash screen doesn't seem to appear on the device (iPhone 4S (Retina) with iOS 6.0), only on the simulator: when run on iPhone, it only displays the launch image.
What could be the cause and solution to both issues?
Thanks in advance!

A: *

*Setup frame for imageView, otherwise it has the same sizes as an image

*Setup correct contentMode

*Try to use self.window, instead of [navigationController view]

Example:
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"IMG_1357.png"]];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.frame = self.window.bounds;
[self.window addSubview:imageView];
[imageView release];

[self.window makeKeyAndVisible];

//now fade out splash image
[UIView transitionWithView:self.window
                  duration:4.0f
                   options:UIViewAnimationOptionTransitionNone
                animations:^(void) {
                    imageView.alpha = 0.0f;
                }
                completion:^(BOOL finished ){
                    [imageView removeFromSuperview];
                }];

To add a 1 second pause before the fade out:
int64_t delayInSeconds = 1.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [UIView transitionWithView:self.window
                      duration:4.0f
                       options:UIViewAnimationOptionTransitionNone
                    animations:^(void) {
                        imageView.alpha=0.0f;
                    }
                    completion:^(BOOL finished ){
                        [imageView removeFromSuperview];
                    }];
});

or
[self performSelector:@selector(_hideSplash:) withObject:imageView afterDelay:1.0];

- (void) _hideSplash:(UIView *)view
{
    [UIView transitionWithView:self.window
                      duration:4.0f
                       options:UIViewAnimationOptionTransitionNone
                    animations:^(void) {
                        view.alpha=0.0f;
                    }
                    completion:^(BOOL finished ){
                        [view removeFromSuperview];
                    }];
}


text:
Q: Compiler confused about mock object I'm using OCMock to aid in Test Driven Development I am doing for an iPad application using Xcode. I have test code like this:
id mock = [OCMockObject mockForProtocol:@protocol(SomeProtocol)];
Vector direction = { 1.0f, 2.0f, 3.0f };
[[mock expect] setDirection:direction];

When I try to compile, I'm getting warnings and errors like this:

warning: multiple methods named 'setDirection:' found
error: sending'Vector' to parameter of incompatible type
'UISwipeGestureRecognizerDirection' (aka 'enum
UISwipeGestureRecognizerDirection')

Obviously the compiler is not able to determine what type of object the mock is supposed to be. I'm not sure how to specify that it should deal with the setDirection method from the SomeProtocol protocol instead of a setDirection method from another class.
What can be done to make a test case like this build successfully?

A: Qualifying the mock with a cast will eliminate the ambiguity:
[(id<SomeProtocol>)[mock expect] setDirection:direction];

A: For the OCMock 3 modern syntax:
id protocolMock = OCMProtocolMock(@protocol(MYProtocol));
OCMExpect([(id <MYProtocol>)protocolMock ambiguousMethod]);


text:
Q: How to shorten time of refused connection? Sometimes my server doesn't work and HttpClient tries to connect about 180 seconds before connection is refused. Is there any way to shorten this time?

A: This should work on android:
int socketTimeoutMS = 120000;
new DefaultHttpClient().getParams().setIntParameter("SO_TIMEOUT", socketTimeoutMS);

A: Try setting the timeout value?
Integer timeoutMs = new Integer(5 * 1000);
messageSender.getHttpClient().getParams().setSoTimeout(timeoutMs);


text:
Q: vkAPI. Как получить counters всем привет. пишу бота на python который по id  страницы вк выдавал информацию. так вот.
Получаю по апи такой ответ

Там есть counters. так вот.
url = f"https://api.vk.com/method/users.get?user_ids={id}&fields=verified,status,screen_name,counters,friend_status,online,blacklisted&access_token={atoken}&v=5.131"
response = requests.get(url, verify=True)
r = response.json()
print('{r["response"]["counters"][0]["audios"]}')

При данном коде вылазит ошибка KeyError: 0 .

A: При обращении к элементу r["response"]["counters"] вы получите словарь, ибо значение ключа "counters" в словаре r["response"] - это словарь.
Далее вы пытаетесь получить значение по ключу 0, а данный ключ отсутствует в словаре, о чем интерпретатор и выдает вам ошибку.
Корректный код:
url = f"https://api.vk.com/method/users.get?user_ids={id}&fields=verified,status,screen_name,counters,friend_status,online,blacklisted&access_token={atoken}&v=5.131"
response = requests.get(url, verify=True)
r = response.json()
print(r["response"][0]["counters"]["audios"])


text:
Q: Custom function for length of a list in Scheme? My lecturer has provided the following code:
(define (length list)
(cond (( null ? list) 0 )
(( atom ? list) 1 )
( else
( + 1 ( length (cdr list))))

However it wouldn't compile and Scheme kept waiting for input, so I rewrote it in  a way that looks tider to me and noticed it had 2 missing brackets (please note this is the first time I've touched Scheme, I'm not sure of the correct way of laying it out and writing it):
(define
    (hello list)
    (cond
        (( null ? list) 0 )
        (( atom ? list) 1 )
        (else
            (+1
                ( hello (cdr list))
            )
        )
    )
)

I also renamed it to hello just to make it obvious that this is my code executing.
Running it however gets the following error:
]=> (hello '(a b c))

;Unbound variable: ?

What's wrong with my function?

A: Your hello procedure suffers from an excessive amount of white space :P . I understand you were trying to improve its readability, but in doing so you introduced a couple of errors. Also notice that in Scheme, the usual way to write closing parenthesis is all in the same line, not in separate lines (unlike what's done with curly braces in other programming languages).
Here's the recommended way to format your code, also fixing the syntax errors:
(define (hello lst)
  (cond ((null? lst) 0)
        ((atom? lst) 1)
        (else (+ 1 (hello (cdr lst))))))

Be aware that:

*

*There must not be a white space between null and ?, same thing for atom and ?: the procedures are called null? and atom?, not null and atom, and a single ? means nothing

*There must be an space between + and 1, the procedure for addition is called + not +1

*It's a bad idea to call a parameter list, that name clashes with the built-in procedure list, so I renamed it to lst
As a side note: the procedure as written is unnecessarily complex, noting that the length as defined does not take in consideration the nested lists, it could have been expressed as simple as this:
(define (hello lst)
  (cond ((null? lst) 0)
        (else (+ 1 (hello (cdr lst))))))

A: (null ? list)

This calls the function null with the arguments ? and list. However, as the error message states, there is no variable named ? (nor is there a function named null, but Scheme didn't get that far, so the error message didn't mention it).
There is however a function named null?, which is almost certainly the function you meant to call. So:
(null? list)

Note that the ? in null? is simply part of the function name and you can't put a space in the middle of a name.
The same applies to (atom ? list) on the next line.

A: Firstly, the names of the functions are "null?" and "atom?". Since you've separated the "?" from them with a space, Scheme is treating the question marks as if they are separate symbols instead of being part of the function names.
Also, you will want to use "+ 1" separated with a space instead of "+1" for the same reason. The name of the function is "+" and "1" is its first argument.


text:
Q: express.js trouble with connect modules I am unable to use express.js submodules and I think I'm missing something basic vis a vis npm. I'm trying to follow this tutorial to build a simple authentication system.
Path to express in app dir:
./node_modules/express/lib/express.js

My app:
var express = require('express');
var app = express.createServer();
app.use(express.bodyDecoder()); // problems happen here

and here's what happens:
meeeeee$ node app.js

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
TypeError: Object #<Object> has no method 'bodyDecoder'
    at Object.<anonymous> (/Users/nflacco/Projects/santorinillc/js/auth-demo/app.js:3:17)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:40)

Also for reference, my package.json file:
{
    "name" : "my dirty little app",
    "version" : "0.0.1",
    "dependencies" :
    {
        "express" : "2.5.9",
        "connect" : "1.8.7",
        "optimist" : "0.3.4"
    }
}

A: The tutorial is using express 1.0.0rc4 and you're using 2.5.9. The earlier version of express has a dependency on a pre-1.x version of connect.
bodyDecoder() was renamed to bodyParser() in connect 1.x. Change your problematic line of code to:
app.use(express.bodyParser());
You may also want to take a look at the 1.x to 2.x Migration Guide for express to account for any other differences between the version used in the tutorial and the one you are developing against.


text:
Q: How to make additional data available to ApiController method via Attribute (AuthorizeAttribute) Our Web API will require consumers of the API to provide an API key we assign to them. The API key will be used for authorization and will be used to add data (somewhere, somehow) so that the ApiController's methods will have access to them.
I'm considering creating an AuthorizationAttribute that

*

*checks that the API key is present

*verifies the supplied API key is valid for the incoming request (referrer)

*If the API key is present and valid, it will be used to get data such as ClientId and ClientName and add it to the incoming Request's Properties collection for use by methods in the ApiController. We might encode the ClientId, etc. into the API key and decode it server-side or retrieve it from the database.
In my dummied-up custom AuthorizationAttribute, if authorization succeeds, I add clientId and clientName to the current Request by doing the following:
actionContext.Request.Properties.add("clientId", 1234);
actionContext.Request.Properties.add("clientName", "Super Client");

Then within a method in the ApiController I grab the data by using:
int clientId = (int)Request.Properties["clientId"];
string clientName = (string)Request.Properties["clientName"];

This works, but it assumes that "clientId" and "clientName" exists in Request.Properties. We can do checks with Request.Properties.ContainsKey but I don't want to repeat this checking code in every method in our Web API. I suppose I can have yet another attribute that does the check and if it fails to find them in Request.Properties returns a 500 Internal Server Error (Bad Request 400?).
Or we could have the AuthorizationAttribute perform the authorization and then make a single call - in each ApiController method - to return an Client object with the data required given the API key supplied in the JSON payload. At this point we know the API key is valid so we'll get data the controller requires to process the request.
What is a recommended approach for adding data to the Request for access by our ApiController's methods? Data that is required but is based off a valid API key being supplied (either we'll grab the data from the database or it'll be encoded into the public API key and decoded on our server). And that will:

*

*preferably not violate DRY (checking that the data the ApiController requires has been added and their respective values the right type)

*ensures that the values are present and the methods can execute without raising an exception

*should this be broken into two attributes? One that does the authorization, the next that gets the data needed based on the supplied API key?

We are running Visual Studio 2010, MVC 4, .NET 4. The API key is to be supplied as part of a JSON payload to the web api.
Magic strings will go away  ;-)

A: One approach would be to give your client a public shared key and a private key. For each request made, the client is required to include their public key as a parameter along with an expiration date. The reason for the expiration date is so the values contributing to their authorization token  will vary per request. Since the client will know the resource they are attempting to access and have their public key handy they only need to be sure the expiration date they send is within an allowance threshold of what the server thinks the time is in utc. Both the server and client can create a secure hash using those values and their supposed private key. You can then validate if the client making the request  -->public key, is who they say they are by using their private key to decrypt the message.
Require a signature for each incoming message. If on the query string it could theoretically look something like this note: you can also use the http header:
Signature=<UrlEncode(Base64(HMAC-MD5(LowerCase( AbsolutePath(ResourceURL)) + UTCDate(ExpirationDate,"yyyyMMddHHmmss")))> &Expires=<UTCDate(ExpirationDate ,"yyyyMMddHHmmss")>&AccessKey=<PublicAccessKey>

For each secure method you define that requires authorization you can let the call go through if the hash is valid, else return a unauthorized http status code.

A: Instead of using ActionFilters, I would suggest using a MessageHandler.  The MessageHandler can look into the request, extract the ClientId and ClientName if they are there and add them to the properties.   Then in the controllers that where you need to pull out that information you can use ApiController extension methods to access the controller.Request.Properties.  This will encapsulate all your magic strings.
I would also suggest putting the APIKey in the Authorization header instead of in a JSON payload as that is exactly what the Authorization header is designed for.


text:
Q: How do i set Linkbutton1 to my propertie MyData
 protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {

            if (DropDownListFeeds.SelectedItem.Value == "All")
            {
                SPWeb web = SPContext.Current.Web;

                SPSiteDataQuery query = new SPSiteDataQuery();

                query.Lists = "<Lists>" +
                              "<List ID=" + web.Lists.TryGetList("StaffNews").ID.ToString() + " />" +
                              "<List ID=" + web.Lists.TryGetList("CompanyNews").ID.ToString() + " />" +
                              "<List ID=" + web.Lists.TryGetList("ManagementNews").ID.ToString() + " />" +
                              "</Lists>";

                query.ViewFields = "<FieldRef Name=\"Title\" />" +
                                   "<FieldRef Name=\"Date\" Nullable=\"TRUE\"/>";
                query.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE'></FieldRef></OrderBy>";
                query.Webs = "<Webs Scope=\"SiteCollection\" />";

                query.RowLimit = 10;

                DataTable dt = web.GetSiteData(query);
                DataView dv = new DataView(dt);

                GridViewNewsFeed.DataSource = dv;
                GridViewNewsFeed.DataBind();

            }
        }

        catch (Exception x)
        {

            Label1.Text = x.Message;
        }

    }

Abowe Date and Title i have a Dropdownlist and a Button the code above are for the button.
the code for what happens when i press linkbutton in the first grinview and display it in the other grindview looks like this.
protected void LinkButton1_Click(object sender, EventArgs e)
    {

        SPWeb web = SPContext.Current.Web;

        SPSiteDataQuery query = new SPSiteDataQuery();

        query.Lists = "<Lists>" +
                      "<List ID=" + web.Lists.TryGetList("StaffNews").ID.ToString() + " />" +
                      "<List ID=" + web.Lists.TryGetList("CompanyNews").ID.ToString() + " />" +
                      "<List ID=" + web.Lists.TryGetList("ManagementNews").ID.ToString() + " />" +
                      "</Lists>";

        query.ViewFields = "<FieldRef Name=\"Title\" />" +"<FieldRef Name=\"Authors\" />"+"<FieldRef Name=\"Links\" />"+"<FieldRef Name=\"Contents\" />"+
                           "<FieldRef Name=\"Date\" Nullable=\"TRUE\"/>";
        query.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE'></FieldRef></OrderBy>";
        query.Webs = "<Webs Scope=\"SiteCollection\" />";

        query.RowLimit = 10;

        DataTable dt = web.GetSiteData(query);
        DataView dv = new DataView(dt);

        GridViewShowMore.DataSource = dv;
        GridViewNewsFeed.DataBind();

    }

A: This is a ASP.Net Question more than a Sharepoint one. You dont have to use Connected web parts as that is used for something completely different. (Passing rows of data using a consumber/subcriber type of model).
Anyways, coupld of ways to do this, and the shortest would be:
<asp:LinkButton Text="text" runat="server" ID="LinkButton1"
    onclick="LinkButton1_Click" />

protected void LinkButton1_Click(object sender, EventArgs e)
{
    TypeOfYourOtherWebpart Ctrl = this.Page.FindControl("YourOtherControlID") as TypeOfYourOtherWebpart;
    TypeOfYourOtherWebpart.MyData = "SomeValue";
}


text:
Q: How to get all the recent session for a user I'm using the spring-session project and I find it quite awesome. My requirement is to show the customer a list of his latest logins (IP address, date/time of his latest logins). I'm looking at the SessionRepository but I can't seem to find such a method. Is it possible to introduce such a method to return a org.springframework.data.domain.Page of latest sessions for a given customer? If not could anyone suggest how to tackle this problem?

A: We want to keep SessionRepository as simple as possible, so it will not be introduced into that API. Instead, we will likely create an extension to the interface when resolving gh-7 is resolved.
In the meantime, you can extend the existing implementation to provide additional methods that map the additional necessary information.

A: for org.springframework.web.context.request.RequestContextHolder
example usage:
public static HttpSession session() {
ServletRequestAttributes attr = (ServletRequestAttributes)    RequestContextHolder.currentRequestAttributes();
return attr.getRequest().getSession(true); // true == allow create
}


text:
Q: Is there a Gfortran flag similar to intel ifort's -ipo-c, that would generate single optimized object from all compiled files? Intel Fortran compiler/linker has the optional flag -ipo-c or /Qipo-c which enables the generation of a single interprocedurally-optimized object file from all files, which can be later used for linking. Is there an equivalent flag to Intel's -ipo-cin gfortran?

A: GCC has -fwhole-program, does that work for gfortran?
Or if you don't want to pass all the Fortran source files on one giant command line, there's -flto link-time optimization which uses a linker "plugin" to run the optimizer on GIMPLE stored in .o files (instead of or as well as machine code).
LTO means you should pass all your optimization options to the invocation of gfortran that does the linking, as well as the gfortran -c that compiles to .o.
So you might use gfortran -ffast-math -O3 -march=native -flto to compile and link, assuming gfortran supports the same options as gcc.  (And that -march=native is what you want: make an executable optimized for the computer you compiled on, which might SIGILL on other computers without all the ISA extensions this one supports.)


text:
Q: ASP.NET MVC - DataAnnotations for Client Validation If an ASP.NET MVC application using Data Annotations...
<%= Html.ValidationSummary("Things broke...") %>
<% Html.EnableClientValidation(); %>

And we post to the server.  Won't we still hit the action, check the ModelState.IsValid and come back to the original view with the validation error.  Is it still considered client side validation if we're hitting the server (via a post)?

A: No, what you just said is not considered client side validation.
Client side validation is considered anything that validates the form in the browser (client), usually with JavaScript.  Once the post is sent to the server (ASP.net), then you are in server side validation mode.
I believe what you are really asking though is whether the new asp.net mvc 2.0 validation is client side or not.
EnableClientValidation enables your data annotated models to use the jquery validate plugin to do true client side validating.  It should not be posting back to the server to do the validating, but when it does post back it will probably validate on the server as well since client side validation is not 100% reliable.

A: Yes, that would be server side validation. If you do the validation on the client side and avoid the form to be posted when any of the fields are invalid, then it's client side validation.

A: If you add these libraries it will take care of the client validation.
<script type="text/javascript" src="MicrosoftAjax.js"></script>
<script type="text/javascript" src="MicrosofMVCValidation.js"></script>

These libraries will generate the javascript code for validation.
But for this you need to use Dataannotations
Here is an example about it


text:
Q: How to inject a dialog view using Roboguice? It seems that roboguice can only inject views from the contentView defined in onCreate(...) of the activity. Outside onCreate(), for example, if I have my custom dialog, which has also a content view (e.g. dialog.setContentView(R.layout.dialog_layout);), how can I inject views from this dialog_layout in my activity? (I got null when I directly inject the dialog views in the activity)

A: Currently roboguice does not support injecting views for things like Dialogs or Adapters.  The code to handle it is fairly straightforward and patches to the roboguice project are certainly welcome.
Here is a link to adding some support for adapters, doing something with a dialog should be fairly similar.
https://groups.google.com/d/topic/roboguice/dJqcGJTcTzs/discussion

A: You can use RoboDialogFragment in RoboGuice 2.0


text:
Q: Any proper way of sending byte data to Unity3D from a C plugin? Just a question of curiosity here.
When you write plugins for Unity on the iOS platform, the plugins have a limited native-to-managed callback functionality (from the plugin and then to Unity). Basically this documentation:
iOS plugin Unity documentation
states that the function signature you are able to call back to is this:

Only script methods that correspond to the following signature can be called from native code: function MethodName(message:string)

The signature defined in C looks like this:

void UnitySendMessage(const char* obj, const char* method, const char* msg);

So this pretty much means I can only send strings back to Unity.
Now in my plugin I'm using protobuf-net to serialize objects and send them back to unity to be deserialized. I have gotten this to work, but by a solution I feel is quite ugly and not very elegant at all:
Person* person = [[[[[Person builder] setId:123]
                    setName:@"Bob"]
                   setEmail:@"bob@example.com"] build];
NSData* data = [person data];

NSString *rawTest = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

UnitySendMessage("GameObject", "ReceiveProductRequestResponse", [rawTest cStringUsingEncoding:NSUTF8StringEncoding]);

Basically I simply encode the bytestream into a string. In Unity I then get the bytes of the string and deserialize from there:
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
Byte[] bytes = encoding.GetBytes(message);

This does work. But is there really no other way of doing it? Perhaps someone have an idea of how it could be done in some alternative way?

A: Base-64 (or another similar base) is the correct way to do this; you cannot use an encoding here (such as UTF8) - an encoding is intended to transform:
arbitrary string <===encoding===> structured bytes

i.e. where the bytes have a defined structure; this is not the case with protobuf; what you want is:
arbitrary bytes <===transform===> structured string

and base-64 is the most convenient implementation of that in most cases. Strictly speaking, you can sometimes go a bit higher than 64, but you'd probably have to roll it manually - not pretty. Base-64 is well-understood and well-supported, making it a good choice. I don't know how you do that in C, but in Unity it should be just:
string s = Convert.ToBase64String(bytes);

Often, you can also avoid an extra buffer here, assuming you are serializing in-memory to a MemoryStream:
string s;
using(var ms = new MemoryStream()) {
    // not shown: serialization steps

    s = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}

A: Example based on Marc Gravell's answer:
On the ios side:
-(void)sendData:(NSData*)data
{
    NSString* base64String = [data base64Encoding];
    const char* utf8String = [base64String cStringUsingEncoding:NSUTF8StringEncoding];
    UnitySendMessage("iOSNativeCommunicationManager", "dataReceived", utf8String);
}

and on the unity side:
public delegate void didReceivedData( byte[] data );
public static event didReceivedData didReceivedDataEvent;

public void dataReceived( string bytesString )
{
    byte[] data = System.Convert.FromBase64String(bytesString);

    if( didReceivedDataEvent != null )
        didReceivedDataEvent(data);
}


text:
Q: How can I find a basis for the kernel of a homomorphism on a free abelian group? Let $\phi\colon F\to G$ be a homomorphism of finitely generated abelian groups. If $F$ is free, then $\ker(\phi)$ is also free and thus admits a basis.
Question: Is there a general procedure to find a basis for $\ker(\phi)$?

As an example, consider the homomorphism $\phi\colon\mathbb Z^3\to (\mathbb Z/2)^2$ given by the matrix
$$
\begin{pmatrix}
1&1&0\\0&1&1
\end{pmatrix}.
$$
After playing around, I guess that the elements $\begin{pmatrix}0\\2\\0\end{pmatrix}$, $\begin{pmatrix}1\\1\\0\end{pmatrix}$ and $\begin{pmatrix}0\\1\\1\end{pmatrix}$ form a basis. Is this true? How could I see this in a systematic way?

A: One way is to proceed recursively, by considering subgroups of $\mathbb{Z}^k$ as $k$ increases.
For $k=1$, you are considering subgroups of $\mathbb{Z}$, which are straightforward: they are generated by the least positive element in the subgroup (if there is one; otherwise, they are the zero subgroup).
Now, for subgroups of $\mathbb{Z}^{k+1}$, given a subgroup $H$, consider
$$\begin{align*}
H_1 &= \{ a\in H \mid a = (a_1,\ldots,a_k,0)\text{ for some }a_i\in\mathbb{Z}\};\\
H_2 &= \{ (0,0,\ldots,0,a_{k+1})\mid (a_1,\ldots,a_k,a_{k+1})\in H\text{ for some }a_i\in\mathbb{Z}\}.
\end{align*}$$
They are both subgroups; $H_2$ is isomorphic to a subgroup of $\mathbb{Z}$, and $H_1$ is isomorphic to a subgroup of $\mathbb{Z}^{k}$. Assuming you already know how to find bases for subgroups of $\mathbb{Z}^k$, let $\beta$ be a basis for $H_1$; if $H_1$ is trivial, $\beta=\emptyset$. Since $H_2$ is isomorphic to a subgroup of $\mathbb{Z}$, there exists $a\geq 0$ such that $H_2 = \langle(0,0,\ldots,0,a)\rangle$. If $a=0$, then $H=H_1$ and we are done, with basis $\beta$. If $a\neq 0$, find $h\in H$, $h=(a_1,\ldots,a_{k},a)$.
Then $\beta\cup\{h\}$ is a basis for $H$. Indeed, if $(b_1,\ldots,b_k,b_{k+1})\in H$, then $(0,0,\ldots,0,b_{k+1})\in H_2$, so there exists $\alpha\in\mathbb{Z}$ such that $(b_1,\ldots,b_k,b_{k+1})-\alpha h\in H_1$, and therefore we can express $(b_1,\ldots,b_{k},b_{k+1})-\alpha h$ in terms of $\beta$. So $\beta\cup\{h\}$ generates. To show it is linearly independent, suppose
$$\alpha_1 v_1+\cdots+\alpha_k v_k + \alpha h = \mathbf{0}$$
with $v_i\in\beta$. This requires $\alpha=0$ by looking at the last coordinate, and so since $\beta$ is linearly independent, $\alpha_1+\cdots+\alpha_k = 0$ as well.

To see this in action for your example, you are looking for the kernel of the matrix. The kernel of the matrix, call it $K$, consists of all elements $(a,b,c)\in\mathbb{Z}^3$ such that $a\equiv b\pmod{2}$ and $b\equiv c\pmod{2}$ (reading off the matrix); that is, all vectors in which all three components are odd, or all three components are even.
The set of all vectors of the form $(a,b,0)$ that are in $K$ are the vectors that have $a$ and $b$ both even. The set of integers that can be the last coordinate of a vector in $K$ is all of $\mathbb{Z}$. So
$$\begin{align*}
K_1 &= \{(a,b,0)\in \mathbb{Z}^3 \mid a\equiv b\equiv 0\pmod{2}\},\\
K_2 &=\{0\}\times\{0\}\times \mathbb{Z}
\end{align*}
$$
$K_2$ is generated by $(0,0,1)$, so we pick a vector from $K$ that has last coordinate equal to $1$. One such is $k=(1,1,1)$.
So now we want to find a basis for $K_1$. Note that since we need all components to be congruent, and the last is congruent to $0$ modulo $2$, then in fact
$$K_1 = \{ (a,b,0)\in\mathbb{Z}^3\mid a,b\in 2\mathbb{Z}\}.$$
At this point it is easy to find a basis (e.g., $(2,0,0)$ and $(0,2,0)$), but let's continue the process. Look at the subgroup $H$ of $\mathbb{Z}^2$ isomorphic to $K_1$,
$$H = \{ (a,b)\in\mathbb{Z}^2 \mid a,b\in2\mathbb{Z}\}.$$
We have
$$\begin{align*}
H_1 &= \{ (a,0)\in \mathbb{Z}^2\mid a\in 2\mathbb{Z}\},\\
H_2 &= \{(0,b)\in H\}.
\end{align*}$$
The elements of $\mathbb{Z}$ that can be second coordinates of vectors in $H$ are $2\mathbb{Z}$. The ideal is generated by $2$, so we find a vector $h\in H$ with second coordinate equal to $2$. One such vector is $h=(0,2)$ (which corresponds to $(0,2,0)$ in $K$).
And then we want a basis for $H_1$. A basis is clearly given by $h_1=(2,0)$ (which corresponds to $(2,0,0)$ in $K$). This gives $\{(2,0), (0,2)\}$ as a basis for $H$.
Going back to $K$, we have that $\beta=\{(2,0,0), (0,2,0)\}$, and $k=(1,1,1)$.
So a basis for $K$ is $\bigl\{(2,0,0), (0,2,0), (1,1,1)\bigr\}$.

The process above is in fact the proof that a submodule of a finitely generated free module over any PID is free, applied to the case of $\mathbb{Z}$. There are other methods, of course.
Added. Smith Normal Form, mentioned by lhf, is a way of doing the above without first trying to figure out the kernel; it requires you to keep track of the operations in question.
Here, you would start as with usual Gauss-Jordan reduction, but without multiplying a row by anything other than $1$ or $-1$. First, we would subtract the second row from the first via multiplication on the left by an elementary matrix:
$$\left(\begin{array}{rr}
1& -1\\0&1\end{array}\right)\left(\begin{array}{ccc}1&1&0\\0&1&1\end{array}\right) = \left(\begin{array}{ccr}1 & 0 & -1\\0 & 1 & 1\end{array}\right).$$
Then we eliminate the nonzero entries in columns to the right of the pivots, via multiplication on the right: we want to add the first column to the third, and subtract the second column from the third. This is the same as:
$$\left(\begin{array}{ccr}1 & 0 & -1\\0 & 1 & 1\end{array}\right)\left(\begin{array}{rrr}1 & 0 & 1\\0 & 1 & -1\\0 & 0 & 1\end{array}\right) = \left(\begin{array}{ccc}1 & 0 & 0\\0 & 1 & 0
\end{array}\right).$$
Putting it all together, you have:
$$\left(\begin{array}{ccc}
1 & 0 & 0\\
0 & 1 & 0
\end{array}\right) = \left(\begin{array}{cr} 1&-1\\0 & 1\end{array}\right)\left(\begin{array}{ccc}1 & 1 &0\\0 & 1 & 1\end{array}\right)\left(\begin{array}{rrr}1 & 0 & 1\\0 & 1 & -1\\0 & 0 & 1\end{array}\right).$$
Now you want to interpret this as linear transformations and change-of-bases matrix. The matrix on the far right tells you to you take the basis of $\mathbb{Z}^3$ given by its columns, $(1,0,0)$, $(0, 1, 0)$, and $(1,-1,1)$; the matrix on the left end of the right hand side tells you to take the basis for $\mathbb{Z}^2$ given by the columns of its inverse
$$\left(\begin{array}{cr}1& -1\\0 & 1\end{array}\right)^{-1} = \left(\begin{array}{cc}1 & 1\\0  & 1\end{array}\right),$$
that is, $(1,0)$, $(1,1)$. Then $A$ is the linear transformation $\mathbb{Z}^3\to\mathbb{Z}^2$ that sends $(1,0,0)$ to $(1,0)$; $(0,1,0)$ to $(1,1)$; and $(1,-1,1)$ to $(0,0)$. So the kernel is generated by $(1,-1,1)$.
Now look at the map $\mathbb{Z}^2\to(\mathbb{Z}/2\mathbb{Z})^2$ given by reduction of coordinates. The kernel is $2\mathbb{Z}^2$, so it has basis given by $2(1,0) = (2,0)$ and $2(1,1)=(2,2)$. Pulling these back to $\mathbb{Z}^3$ along $A$ gives $2(1,0,0) = (2,0,0)$ (preimage of $(2,0)$ in the basis), $2(0,1,0)= (0,2,0)$ (preimage of $(2,2)$ in the basis), plus the kernel. So we get that the kernel of the composite map has basis $(2,0,0)$, $(0,2,0)$, and $(1,-1,1)$.
So another basis for the kernel is $(2,0,0)$, $(0,2,0)$, and $(1,-1,1)$.

A: Try also the Smith normal form.


text:
Q: Memory Difference between actual from task manager and Manual Calculated in c++ singly linked list I run a c++ singly linked list append operation for 100000000 nodes the node take random number each time between 0-10 , In centos 64bit, it takes size of 16 for each node so it will be 1600000000 but according to task manager shown as 30.53mb for each node.
The node Class contains int data and node* next, thats it.
My Questions:
1.Why this different?
2.Is any specific way to obtain the equal size?

A: All "lumps" of memory being allocated have an overhead, which is typically 16-64 bytes per allocation.
If you make two memory allocations in a row, how far apart are those. E.g.
char *a = new char;
char *b = new char;

std::cout << b-a << std::endl;

delete a;
delete b;

(And yes, before someone else points it out: Technically this code is undefined behaviour. But on a x86-64 machine, the memory is a flat memory model, so subtracting one pointer from another should give you the distance between the two objects. One of the reasons that the standard doesn't allow for the "difference between memory of different allocations" is that it's possible that the architecture uses segmented memory a'la 16-bit OS/2, where each allocation has it's own segment, and a segment has it's own base-address, where the base-address is not known by the user-mode application, so it's impossible to use this sort of trick)

A: How do you create the nodes for your list? new? malloc?
All those memory allocation functions consume some extra space to allow the memory management (e.g. deallocation and reclaiming the memory). This overhead is most apparent when you allocate a lot of small pieces of memory.
I think that is the reason of this memory overhead you are seeing.
You can try the following:

*

*If you only allocate small pieces of the same size - try using a fixed array (or just allocated-once array) and then use pointers to the array elements as next member of your list node.

*You can also try alternative implementations of malloc, for example tcmalloc


text:
Q: IBM .NET Data Provider Connection String issue with Library List I am trying to use the DB2 .Net Data Provider in a C# program rather than relying on ODBC.  The connection string below works, but only for one library (say my libraries are test1 and test2).
Data Source=xxx.xxx.xxx.xxx;User Id=testuser;Password=testpassword;
Naming=SQL;Default Collection=test1;

If I add "Library List=test1, test2;" (I have tried several variations of that) to the connection string, it does not allow me access additional libraries, only what is defined in defaultcollection.  I have also tried not specifying default collection as well, but that causes the query to not work at all.  What do I need to do to be able to run a query that can access both of these libraries on the same connection?

A: The library list only works when using the system naming convention.

SQL_NAMING
  Specifies that tables are qualified by the collection name in the form:

collection.table

  where collection is the name of the collection and table is the table name. The default qualifier is the user ID running the process that executes the SQL statement and is used when the table name is not explicitly qualified and the default collection name is not specified.
SYSTEM_NAMING
  Specifies that files are qualified by library name in the form:

library / file

  where library is the name of the library and file
  is the table name. The default search path is the
  library list (*LIBL) for the unqualified table name, if the table name (file) is not explicitly qualified
  and a default collection name (library) is not specified.

A: With Naming=SQL, if you specify libraries inside your library list, don't need to use Default Collection.  Just add something like:
;LibraryList=lib1,lib2,lib3,lib4;SchemaSearchList=lib1,lib2,lib3,lib4;

or to use the default library list on the connection job, which is most likely defined on the user profile.
;LibraryList=*USRLIBL;SchemaSearchList=*USRLIBL;

A: You can follow lamLam answer, I use it for example to change between Test Libraries and Production Libraries.
But check the iSeries SO version. Some older versions don't support the SchemaSearchList.
Versions V6R1 and V7R1 support it.


text:
Q: LED blinking with timer interrupt I'm trying to make two LEDs blink with a timer interrupt, but for some reason when the last function called before the while loop returns, the code seems to enter a loop (which is not the while loop obviously) from which it never exits
I'm using a STM32 Nucleo-144 for STM32H743ZI with ARM Corte-M7 core at 400MHz;
I used CubeMX for initializing the board and the desired pin. Also from CubeMX I set the timer TIM6 with a prescaler of 399999 and a period of 499 so the blinking period would be of 0.5s; The IDE I'm using is Atollic True Studio
Here's the code I'm trying to run
ETH_TxPacketConfig TxConfig;

ETH_HandleTypeDef heth;

TIM_HandleTypeDef htim6;

UART_HandleTypeDef huart3;

PCD_HandleTypeDef hpcd_USB_OTG_FS;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_ETH_Init(void);
static void MX_USART3_UART_Init(void);
static void MX_USB_OTG_FS_PCD_Init(void);
static void MX_TIM6_Init(void);
void TIM6_IRQHandler(void);
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
     IRQn_Type TIM6_IRQn = 0;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_ETH_Init();
  MX_USART3_UART_Init();
  MX_USB_OTG_FS_PCD_Init();
  MX_TIM6_Init();
  /* USER CODE BEGIN 2 */
  __HAL_RCC_TIM6_CLK_ENABLE();  //Enable the TIM6 peripheral

  HAL_NVIC_SetPriority(TIM6_IRQn, 0, 0);  //Enable the peripheral IRQ
  HAL_NVIC_EnableIRQ(TIM6_IRQn);

  HAL_TIM_Base_Start_IT(&htim6); //Start the timer
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1) //While loop free for other simultaneous operation
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

Here are some other functions used for intercepting the interrupt and managing it
void TIM6_IRQHandler(void) {
    // Pass the control to HAL, which processes the IRQ
    HAL_TIM_IRQHandler(&htim6);
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
    // This callback is automatically called by the HAL on the UEV event
    if(htim->Instance == TIM6) {
        HAL_GPIO_TogglePin(GPIOB,GPIO_PIN_14); //Function that trigger a PIN
        HAL_GPIO_TogglePin(GPIOB,GPIO_PIN_7);
    }
}

Here is the function that initialize the timer
static void MX_TIM6_Init(void)
{

  /* USER CODE BEGIN TIM6_Init 0 */

  /* USER CODE END TIM6_Init 0 */

  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM6_Init 1 */

  /* USER CODE END TIM6_Init 1 */
  htim6.Instance = TIM6;
  htim6.Init.Prescaler = 399999;
  htim6.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim6.Init.Period = 499;
  htim6.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim6) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim6, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM6_Init 2 */

  /* USER CODE END TIM6_Init 2 */

}

I compile without errors or warning, but the LEDs don't blink; what am I doing wrong?
EDIT
Here is the code for the MX_GPIO_Init()
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOG_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0|LD3_Pin|LD2_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(USB_PowerSwitchOn_GPIO_Port, USB_PowerSwitchOn_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : USER_Btn_Pin */
  GPIO_InitStruct.Pin = USER_Btn_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(USER_Btn_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : PA5 */
  GPIO_InitStruct.Pin = GPIO_PIN_5;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pins : PB0 LD3_Pin LD2_Pin */
  GPIO_InitStruct.Pin = GPIO_PIN_0|LD3_Pin|LD2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pin : USB_PowerSwitchOn_Pin */
  GPIO_InitStruct.Pin = USB_PowerSwitchOn_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(USB_PowerSwitchOn_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : USB_OverCurrent_Pin */
  GPIO_InitStruct.Pin = USB_OverCurrent_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(USB_OverCurrent_GPIO_Port, &GPIO_InitStruct);

}


text:
Q: Facebook Graph API Object_id I need to send a URL to list of selected friends. I am using following code:
// Use FB.ui to send the Request(s)
   FB.ui({method: 'apprequests',
   to: sendUIDs,
   action_type:'send',
   title: 'testing',
   message: 'testing send.',
   **object_id: 'YOUR_OBJECT_ID'**
   }, callback);

I am not sure what is object_id here. Can any one please explain?
Thanks in advance.

A: As per the conversion here there is no way to get full list of users. You can either get invitable_friends who are not using the app or friends who are using the app.
At a point I thought of combining both the list results and use it, but invitable_friends doesn't return the actual id of the user. It sends a temporary token for each user which can be used to send only apprequest.
I hope this will help someone in future.
Thanks for the support @ CBroe.


text:
Q: how to inherit some variables from parent class to child class in java Is it possible to inherent some of the property from the parent class to child class in java.
In one of my situation i have to take only 3 properties from the parent while my parent has 100 property.
If yes then what is the way.?
Thanks in advance.

A: I recommend you either refactor your code, or simply don't use the 97 properties you don't need.
Your super-class shouldn't be more complex than your subclass. The purpose of your subclass should be to implement or add functionality. Inserting a lot of properties that you won't use defeats the point of inheritance and class hierarchies.
Perhaps you can divide the many properties of your super-class and instead put them in sub-classes.

A: Yes, We can do it.
Just Extend the parent class
 class Teacher {
       String designation = "Teacher";
       String collegeName = "Beginnersbook";
       void does(){
        System.out.println("Teaching");
       }
    }

public class PhysicsTeacher extends Teacher{
   String mainSubject = "Physics";
   public static void main(String args[]){
    PhysicsTeacher obj = new PhysicsTeacher();
    System.out.println(obj.collegeName);
    System.out.println(obj.designation);
    System.out.println(obj.mainSubject);
    obj.does();
   }
}

Java Inheritance
you can check out this link to learn more.


text:
Q: Bundling external SWFs into a single master SWF A client has asked me to bundle together a bunch of swfs into a single master one which can load/play them on command. Simple enough to do using loader to fetch external swfs; however, the adserver they're using doesn't support multiple files.
My question is: is it possible to bundle those sub-swfs into the main one so that they are no longer "external files" and the ad-server can be given a single swf?
Importing them to the library doesn't work because it strips scripts (right...?).
Thanks!

A: No no no no no no no no no (to all the other answers/comments/whatever)!!!!
[Embed(source='someswf.swf', mimeType='application/octet-stream')]
public class SomeSWF extends flash.utils.ByteArray {
}

then:
var loader:Loader = new Loader();
// add your listeners as such.
loader.loadBytes(new SomeSWF());

Then you can just use the standard compiler to bundle your files together.  One caveat here is that all the main files MUST have different names, Flash uses the main sprite to deal with applicationDomain -- therefore, if you go this route, make sure to name all your stage classes differently:
class SomeSprite_XXXXXXXX extends Sprite {

   // GENERATE YOURLOADER SWFS HERE

   public SomeSprite_XXXXXXXXXXXX() {

      // load manifest file
      // provide api to the ad to load swfs

   }

}


text:
Q: How to refresh my HttpWebRequest I'm creating a Windows Phone 7 app which allow to listen a web radio. But I also want to get the cover of the song and I want it to be refreshed every 3 minutes for example.
When I start debugging my app, I've no problem but I've no idea how to call back my code to refresh the cover.
Thanks a lot.
Aymeric.

A: I found a solution not really the one I looked for but my mates used a timer to refresh the same application for Android and iOS since there is no push notification from the server.
So I used this code
DispatcherTimer refreshTimer = new DispatcherTimer();
refreshTimer.Interval = TimeSpan.FromSeconds(30);
refreshTimer.Tick += new EventHandler(refreshTimer_Tick);
refreshTimer.Start();

Thank you all for the time you spent on this question.
Aymeric.