问:
Native Code coverage with android soong build system
I'm trying to generate code coverage report for my native components with AOSP source code using soong build system.

I have extended aosp vhal but unit test cases are same as in below link.
http://androidxref.com/8.1.0_r33/xref/hardware/interfaces/automotive/vehicle/2.0/default/tests/

Tried adding below to cc_test, cc_binary in Android.bp

```<code>native_coverage : true,

    cflags: [
         "-g",
         "-O0",
         "-fprofile-arcs",
         "-ftest-coverage",
    ],

     ldflags : [
        "-fprofile-arcs",
        "-ftest-coverage",
    ],
</code>```

Native binary unit-tests-coverage is generated in out/target/product but I can't find gcno intermediates for this.

Running below command gives me *.gcda files for each test files.

```<code>adb shell \
    GCOV_PREFIX=/data/local/tmp \
    GCOV_PREFIX_STRIP=`echo $ANDROID_BUILD_TOP | grep -o / | wc -l` \
    /data/local/tmp/unit-tests-coverage
</code>```

I have tried below links but not sure how to proceed :(

http://logan.tw/posts/2015/04/28/check-code-coverage-with-clang-and-lcov/
https://android.googlesource.com/platform/bionic.git/+/master-soong
https://android.googlesource.com/platform/build/soong/+/581341d%5E%21/
https://android.googlesource.com/platform/external/e2fsprogs/+/fedfb27%5E%21/
https://android.googlesource.com/platform/development/+/master/scripts/acov#23
http://androidxref.com/9.0.0_r3/xref/bionic/README.md#293

I'm not sure if google's vts framework can be used here to generate native code coverage.
https://codelabs.developers.google.com/codelabs/android-vts-8/#6

"gcnodir" is generated but not sure how to make use of it.
/coverage/data/nativetest64/vehicle-unit-tests-coverage/unit-tests-coverage.gcnodir

答:
Posting answer to my question for other users on SO.

Install coverage tool :

sudo apt-get install lcov (This should install lcov-1.12)

sudo apt-get install gcc-4.6 (Clang generates .gcno approximately equal to gcc 4.2 that aren't compatible
with gcov-4.8. Installing gcc-4.6 to get gcov-4.6 and invoking lcov with '--gcov-tool /usr/bin/gcov-4.6')

Download LLVM 3.8 for llvm-cov to work : http://releases.llvm.org/download.html

All native unit test cases i.e instrumented binary needs to be executed on target. To build and emit clang's instrumentation based profiling. Example: http://androidxref.com/9.0.0_r3/xref/hardware/interfaces/automotive/vehicle/2.0/default/Android.bp#82 (Renamed to vehicle-manager-unit-test for shorter name)

export NATIVE_COVERAGE=true

Add native_coverage: true to test module in Android.bp

Go to: module-name/test

Use mm or make command to build native binary

Ex: For hardware/interfaces/automotive/vehicle/2.0/default/tests/  :
mma or make vehicle-manager-unit-test -j32

Copy coverage enabled instrumented binary to target

adb push out/target/product/product_name/data/nativetest64/vendor/vehicle-manager-unit-test /data/nativetest64/vehicle-manager-unit-test
adb shell chmod +x /data/nativetest64/vehicle-manager-unit-test

Run test cases and generate .gcda files

adb shell \
 GCOV_PREFIX=/data/local/tmp \
 GCOV_PREFIX_STRIP=echo $ANDROID_BUILD_TOP | grep -o / | wc -l \
 /data/nativetest64/vehicle-manager-unit-test

adb shell find -iname *.gcda

adb pull /data/local/tmp/proc/self/cwd/out/soong/.intermediates/hardware/interfaces/automotive/vehicle/2.0/default/vehicle-manager-unit-test/android_x86_64_silvermont_vendor_cov/obj/hardware/interfaces/automotive/vehicle/2.0/default/tests/ .(Destination folder)

Extract GCNO files from GCNODIR (archive file generated at
out/overage/data/nativetest64/vendor/vehicle-manager-unit-test ) to
same folder with GCDA files

llvm-cov gcov -f -b *.gcda (https://llvm.org/docs/CommandGuide/llvm-cov.html  )

lcov --directory . --base-directory . --gcov-tool /usr/bin/gcov-4.6 --capture -o cov.info (http://ltp.sourceforge.net/coverage/lcov.php)

genhtml cov.info -o output

Here's the script which wraps all these commands:
https://gist.github.com/pankajgangwar/f070b8b54e83543f8e3638dcd2cae1b8

Body:
I'm trying to generate code coverage report for my native components with AOSP source code using soong build system.

I have extended aosp vhal but unit test cases are same as in below link.
http://androidxref.com/8.1.0_r33/xref/hardware/interfaces/automotive/vehicle/2.0/default/tests/

Tried adding below to cc_test, cc_binary in Android.bp

native_coverage : true,

    cflags: [
         "-g",
         "-O0",
         "-fprofile-arcs",
         "-ftest-coverage",
    ],

     ldflags : [
        "-fprofile-arcs",
        "-ftest-coverage",
    ],

Native binary unit-tests-coverage is generated in out/target/product but I can't find gcno intermediates for this.

Running below command gives me *.gcda files for each test files.

adb shell \
    GCOV_PREFIX=/data/local/tmp \
    GCOV_PREFIX_STRIP=`echo $ANDROID_BUILD_TOP | grep -o / | wc -l` \
    /data/local/tmp/unit-tests-coverage

I have tried below links but not sure how to proceed :(

http://logan.tw/posts/2015/04/28/check-code-coverage-with-clang-and-lcov/
https://android.googlesource.com/platform/bionic.git/+/master-soong
https://android.googlesource.com/platform/build/soong/+/581341d%5E%21/
https://android.googlesource.com/platform/external/e2fsprogs/+/fedfb27%5E%21/
https://android.googlesource.com/platform/development/+/master/scripts/acov#23
http://androidxref.com/9.0.0_r3/xref/bionic/README.md#293

I'm not sure if google's vts framework can be used here to generate native code coverage.
https://codelabs.developers.google.com/codelabs/android-vts-8/#6

"gcnodir" is generated but not sure how to make use of it.
/coverage/data/nativetest64/vehicle-unit-tests-coverage/unit-tests-coverage.gcnodir


来源: stackexchange

问:
Trying to turn multiple spaces into one space
I am trying to print back the user's input with the modification that anytime there are more than one spaces in a row in the user input, the output will only show one space.  For instance, if I wrote

```<code>Hey,     I love Stack Overflow
</code>```

I would want my output to be

```<code>Hey, I love Stack Overflow
</code>```

I saw some answers on this but they weren't in C and weren't following my logic which I feel like could work.

```<code>int c, count;
c = 0;
count = 0;
printf("Enter a string of characters, please: ");
while ((c = getchar()) != EOF)
{
    if (c == ' ')
        ++count;
    if ((count == 1) && c == ' ')
        continue;
    else
        count--;
    putchar(c);
}
</code>```

The output when I run this code, though, does not remove excess spaces, it just outputs the exact same message.

答:
to turn multiple spaces into one space

Consider simply noting the previous character.

```<code>int previous = 0;
int c;

printf("Enter a string of characters, please: ");
while ((c = getchar()) != EOF) {
  if (c != ' ' || previous != ' ')
    putchar(c);
  }
  previous = c;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to print back the user's input with the modification that anytime there are more than one spaces in a row in the user input, the output will only show one space.  For instance, if I wrote

Hey,     I love Stack Overflow

I would want my output to be

Hey, I love Stack Overflow

I saw some answers on this but they weren't in C and weren't following my logic which I feel like could work.

int c, count;
c = 0;
count = 0;
printf("Enter a string of characters, please: ");
while ((c = getchar()) != EOF)
{
    if (c == ' ')
        ++count;
    if ((count == 1) && c == ' ')
        continue;
    else
        count--;
    putchar(c);
}

The output when I run this code, though, does not remove excess spaces, it just outputs the exact same message.

Body:
to turn multiple spaces into one space

Consider simply noting the previous character.

int previous = 0;
int c;

printf("Enter a string of characters, please: ");
while ((c = getchar()) != EOF) {
  if (c != ' ' || previous != ' ')
    putchar(c);
  }
  previous = c;
}


问:
How to check if dark mode is enabled on iOS/Android using Flutter?
How can I check if dark mode is enabled in Android Q with Flutter?
 I know how to set the dark mode, but I didn't find a way to check the background theme.

Here is the code to set the dark theme.

```<code>darkTheme: ThemeData.dark(),
</code>```

答:
I found the way. Here it is.

```<code>  bool _darkModeEnabled = false;

  void _checkIfDarkModeEnabled() {
    final ThemeData theme = Theme.of(context);
    theme.brightness == appDarkTheme().brightness
        ? _darkModeEnabled = true
        : _darkModeEnabled = false;
  }
</code>```

Update 27.02.23:

```<code>final brightness = WidgetsBinding.instance.platformDispatcher.platformBrightness;
</code>```

Body:
How can I check if dark mode is enabled in Android Q with Flutter?
 I know how to set the dark mode, but I didn't find a way to check the background theme.

Here is the code to set the dark theme.

darkTheme: ThemeData.dark(),

Body:
I found the way. Here it is.

  bool _darkModeEnabled = false;

  void _checkIfDarkModeEnabled() {
    final ThemeData theme = Theme.of(context);
    theme.brightness == appDarkTheme().brightness
        ? _darkModeEnabled = true
        : _darkModeEnabled = false;
  }

Update 27.02.23:

final brightness = WidgetsBinding.instance.platformDispatcher.platformBrightness;


问:
is there a way to print (to console) and run input as Beautiful soup page extension -Python
background:

I am learning about web scraping and decided to use python and
beautiful soup to scrape, this program will ask the user for a link
and will narrow down their HTML search in the webpage.

problem:

When I ask the user to define their own extension for soup page( EX .div.div.a ) and I append this to the whole string and try and execute it in a print function it always returns None. How would I go about running the extension and printing it from the gathered user input?
for this example, I am scraping a Newegg search for graphics cards.

example link:https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphics%20cards

keep in mind from the code below, I had already used findAll for div class="item-info", so it would be searching the extension in that code block.

I have already tried exec() the string but this does not seem to work

isdone = ""
while isdone != "done":
    try:
        route = "container"
        userinput = input("what extensions would you like to search for?\n seperate each denotion with a space \n ex: div div img[\"title\"]\n: ")
        inputRoute = userinput.split(' ')
        for i in range(len(inputRoute)):
            route += "." + inputRoute[i]
        print("---\n"+route+"\n---")
        print("Current Route ^\n---")
        print("output:\n", exec(route),"\n---")#actual resaults if user had inputed a
        print(container.a) # what i actually want to output (if the user only inputed a)
        #add the abilitie to add extensions ex: container.div.a.img["foo"] -ignore this stackoverflow
        isdone = input("are you happy with these extensions? \n type 'done' when happy\n or enter to change extension\n: ")
    except Exception as e:
        print(e)
        input("Make sure their is no leftover spaces\npress enter to continue")
```

<p>'#' are my comments throughout output
THIS IS CONSOLE OUTPUT:</p>

```'what extensions would you like to search for?
 seperate each denotion with a space
 ex: div div img["title"]
: a                 #  <--what I put in the input
---
container.a #what
---
Current Route ^
---
output:
 None               #  <-- what actually outputs when i use exec()
---

are you happy with these extensions?
 type 'done' when happy
 or enter to change extension
:'
```

答:
If container is your BeautifulSoup object, then eval('container.a') will return a list of all the  tags.
Using eval or exec is probably not a good idea in your case, however, see Why should exec() and eval() be avoided?

I recommend using find_all and its attrs parameter instead, though parsing the input will probably turn out to be a good deal harder than you currently anticipate.

Body:
background:

I am learning about web scraping and decided to use python and
beautiful soup to scrape, this program will ask the user for a link
and will narrow down their HTML search in the webpage.

problem:

When I ask the user to define their own extension for soup page( EX .div.div.a ) and I append this to the whole string and try and execute it in a print function it always returns None. How would I go about running the extension and printing it from the gathered user input?
for this example, I am scraping a Newegg search for graphics cards.

example link:https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphics%20cards

keep in mind from the code below, I had already used findAll for div class="item-info", so it would be searching the extension in that code block.

I have already tried exec() the string but this does not seem to work

isdone = ""
while isdone != "done":
    try:
        route = "container"
        userinput = input("what extensions would you like to search for?\n seperate each denotion with a space \n ex: div div img[\"title\"]\n: ")
        inputRoute = userinput.split(' ')
        for i in range(len(inputRoute)):
            route += "." + inputRoute[i]
        print("---\n"+route+"\n---")
        print("Current Route ^\n---")
        print("output:\n", exec(route),"\n---")#actual resaults if user had inputed a
        print(container.a) # what i actually want to output (if the user only inputed a)
        #add the abilitie to add extensions ex: container.div.a.img["foo"] -ignore this stackoverflow
        isdone = input("are you happy with these extensions? \n type 'done' when happy\n or enter to change extension\n: ")
    except Exception as e:
        print(e)
        input("Make sure their is no leftover spaces\npress enter to continue")

'#' are my comments throughout output
THIS IS CONSOLE OUTPUT:

'what extensions would you like to search for?
 seperate each denotion with a space
 ex: div div img["title"]
: a                 #  <--what I put in the input
---
container.a #what
---
Current Route ^
---
output:
 None               #  <-- what actually outputs when i use exec()
---

are you happy with these extensions?
 type 'done' when happy
 or enter to change extension
:'

Body:
If container is your BeautifulSoup object, then eval('container.a') will return a list of all the <a> tags.
Using eval or exec is probably not a good idea in your case, however, see Why should exec() and eval() be avoided?

I recommend using find_all and its attrs parameter instead, though parsing the input will probably turn out to be a good deal harder than you currently anticipate.


问:
Unable to publish non-monolithic script module to local PowerShell Gallery with 7 or more functions
Problem:

I am unable to successfully publish a non-monolithic script module to my local PowerShell Gallery when using PowerShell 5.1 and my module contains 7 or more functions. Publishes fine with 6 or less functions.

Example: FunctionsToExport = 'Get-Test1', 'Get-Test2 ', 'Get-Test3', 'Get-Test4', 'Get-Test5', 'Get-Test6', 'Get-Test7'

The publish always hangs at 'VERBOSE: Performing the operation "Publish-Module" on target…', but never completes.

I am not seeing any errors, so I am not sure why it is hanging.

What does work:

I can successfully publish my non-monolithic script module to my local PowerShell Gallery when it contains 6 or less functions.

Example: FunctionsToExport = 'Get-Test1', 'Get-Test2 ', 'Get-Test3', 'Get-Test4', 'Get-Test5', 'Get-Test6'

This works fine: VERBOSE: Successfully published module…

If I simply add one more function and update the manifest, I can no longer publish without it hanging again at the same place.

I am pretty sure I am missing a step, but I am having trouble figuring out what I missed.

I am learning the non-monolithic script module design from Mike F Robbins by reading his blog posts and watching his presentations. The gist of this design is each function is in a separate PS1 file that is dot sourced from the PSM1 file.

Summary of how I build my script modules:

Create new script module scaffolding using custom Plaster template.

Add functions to the folder named Public.

Update module version and FunctionsToExport section in manifest.

Use PsDeploy or Publish-Module to deploy to a local PowerShell Gallery.

The local PowerShell Gallery is just a folder on my data drive G:\JnPowerShellGallery.

This is how I am publishing my module to my local PSGallery.

Publish-Module -Path 'G:\_temp\JnTestModule' -Repository JnPowerShellGallery -NuGetApiKey 'AnyStringWillDo' -Verbose -InformationAction Continue
```

<p>Here is a OneDrive link to my test module.<br>
https://1drv.ms/f/s!AlsrG1Yfr5pHgts0RCM--SmRnUf3AA</p>

<p>Output of $PSVersionTable                                                                                </p>

```PSVersion                      5.1.17134.590
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17134.590
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
```

I am so close to building my first release pipeline for my PowerShell modules, but I am stuck at this point.

Does anyone know what might be causing this issue?

答:
Ok, I just found out I can publish my module successfully using PowerShell Core 6.2.0!

Joel on  http://slack.poshcode.org/ powershell-help channel suggested to change the .psd1 file encoding to UTF8 with BOM. He said PowerShell 5  doesn't like .psd1 files that don't have BOM. They are encoded with UTF8 by default in vscode. I did try changing the encoding, but this did not fix my problem.

Thanks to his suggestion, I thought of trying to publish my module with PowerShell Core 6.2.0 and it worked!

This does not exactly solve the problem with PowerShell 5.1, but I don't mind switching to PowerShell Core 6.2.0  to publish my modules. This solves my problem.

Body:
Problem:

I am unable to successfully publish a non-monolithic script module to my local PowerShell Gallery when using PowerShell 5.1 and my module contains 7 or more functions. Publishes fine with 6 or less functions.

Example: FunctionsToExport = 'Get-Test1', 'Get-Test2 ', 'Get-Test3', 'Get-Test4', 'Get-Test5', 'Get-Test6', 'Get-Test7'

The publish always hangs at 'VERBOSE: Performing the operation "Publish-Module" on target…', but never completes.

I am not seeing any errors, so I am not sure why it is hanging.

What does work:

I can successfully publish my non-monolithic script module to my local PowerShell Gallery when it contains 6 or less functions.

Example: FunctionsToExport = 'Get-Test1', 'Get-Test2 ', 'Get-Test3', 'Get-Test4', 'Get-Test5', 'Get-Test6'

This works fine: VERBOSE: Successfully published module…

If I simply add one more function and update the manifest, I can no longer publish without it hanging again at the same place.

I am pretty sure I am missing a step, but I am having trouble figuring out what I missed.

I am learning the non-monolithic script module design from Mike F Robbins by reading his blog posts and watching his presentations. The gist of this design is each function is in a separate PS1 file that is dot sourced from the PSM1 file.

Summary of how I build my script modules:

Create new script module scaffolding using custom Plaster template.

Add functions to the folder named Public.

Update module version and FunctionsToExport section in manifest.

Use PsDeploy or Publish-Module to deploy to a local PowerShell Gallery.

The local PowerShell Gallery is just a folder on my data drive G:\JnPowerShellGallery.

This is how I am publishing my module to my local PSGallery.

Publish-Module -Path 'G:\_temp\JnTestModule' -Repository JnPowerShellGallery -NuGetApiKey 'AnyStringWillDo' -Verbose -InformationAction Continue

Here is a OneDrive link to my test module.

https://1drv.ms/f/s!AlsrG1Yfr5pHgts0RCM--SmRnUf3AA

Output of $PSVersionTable

PSVersion                      5.1.17134.590
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17134.590
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

I am so close to building my first release pipeline for my PowerShell modules, but I am stuck at this point.

Does anyone know what might be causing this issue?


问:
How to process binary data from API Gateway in Lambda and vice-versa?
I'm currently have the following setup:
1. S3 Bucket
2. API Gateway with GET/POST resource
3. Two Lambda Functions (one for getting data from s3, one for storing data to s3)

For example the GET Resource, i pass a key parameter, which is used in the lambda function to get the object from s3 bucket. then i want to return the retrieved object to api gateway and to client as a binary.

In the POST resource, i want to send a binary payload, eg.: pdf or zip file, save it to s3 and return generated key.

So on one hand i want my api gateway and lambda to be able return binary data in GET request, on the other hand i want it to accept binary payload in POST request.

In api gateway settings, i've set Binary-Media-Types to application/octet-stream. Also i have lambda proxy integration activated.

My question is: How can I process binary data in api gateway/lambda?

I tried messing around with Headers and Content-Types but more or less i didn't know what I was doing :(

Example store-luggage lambda for storing data from POST request in S3

```<code>import boto3
import json
import uuid
import logging
from botocore.exceptions import ClientError

def lambda_handler(event, context):

    #data = <binary data from POST request>?

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    bucket = 'bucket1'

    uniqueid = str(uuid.uuid4())
    logger.info("Generated UUID: " + uniqueid)

    s3 = boto3.resource('s3')

    logger.info("Trying to save file '" + uniqueid + "' to bucket '" + bucket + "'")

    savedObj = None

    try:
        savedObj = s3.Bucket(bucket).put_object(Key=uniqueid, Body=<here should be my binary payload from POST request>)
    except ClientError as e:
        logger.error("Saving of object has failed: " + str(e.response['Error']['Message']))

    if savedObj is None:
        return {
            'statusCode': 500,
            'body': json.dumps({
                'message': 'Saving of object has failed!'
            })
        }

    return {
        'statusCode': 200,
        'body': json.dumps({
            'token': uniqueid
        })
    }
</code>```

get-luggage lambda for retrieving object from s3 by given key and return binary payload in response

```<code>import boto3
import json
from pprint import pprint
from botocore.exceptions import ClientError
import logging

def lambda_handler(event, context):

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    bucket = 'bucket1'
    token = event["queryStringParameters"]["token"]

    s3 = boto3.client('s3')

    objectFromS3 = None

    try:
        objectFromS3 = s3.get_object(Bucket=bucket, Key=token)
    except ClientError as ex:
        if ex.response['Error']['Code'] == 'NoSuchKey':
            logger.info('No object found - returning empty')
        else:
            raise ex

    if objectFromS3 is None:
        return {
            'statusCode': 404,
            'body': json.dumps({
                'message': 'Cannot retrieve object from storage!'
            })
        }

    pprint(objectFromS3)
    #ContentType application/octet-stream

    return {
        'statusCode': 200,
        'body' : <binary data from retrieved s3 object here?>,
        'headers': {
            'content-type': 'application/octet-stream'
        },
        'isBase64Encoded': True
    }
</code>```

I expected to retrieve binary payload in GET response and expected api gateway to pass binary payload from POST request to lambda, but none of this was achieved with the stuff i tried.

I hope i descriped my problem well enough, if any clearification is needed let me know.

best wishes,
an aws noob

答:
get-luggage:

If your file is already in S3, you can redirect the user to the file link in S3 by adding the Location attribute on the API-Gateway headers, reducing Gateway data traffic.

example:

exports.handler = (event, context, callback) => {
  return callback(null, {
    statusCode: 301,
    headers: {
      Location: 'https://<...S3...>',
    }
  });
}
```

Body:
I'm currently have the following setup:
1. S3 Bucket
2. API Gateway with GET/POST resource
3. Two Lambda Functions (one for getting data from s3, one for storing data to s3)

For example the GET Resource, i pass a key parameter, which is used in the lambda function to get the object from s3 bucket. then i want to return the retrieved object to api gateway and to client as a binary.

In the POST resource, i want to send a binary payload, eg.: pdf or zip file, save it to s3 and return generated key.

So on one hand i want my api gateway and lambda to be able return binary data in GET request, on the other hand i want it to accept binary payload in POST request.

In api gateway settings, i've set Binary-Media-Types to application/octet-stream. Also i have lambda proxy integration activated.

My question is: How can I process binary data in api gateway/lambda?

I tried messing around with Headers and Content-Types but more or less i didn't know what I was doing :(

Example store-luggage lambda for storing data from POST request in S3

import boto3
import json
import uuid
import logging
from botocore.exceptions import ClientError

def lambda_handler(event, context):

    #data = <binary data from POST request>?

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    bucket = 'bucket1'

    uniqueid = str(uuid.uuid4())
    logger.info("Generated UUID: " + uniqueid)

    s3 = boto3.resource('s3')

    logger.info("Trying to save file '" + uniqueid + "' to bucket '" + bucket + "'")

    savedObj = None

    try:
        savedObj = s3.Bucket(bucket).put_object(Key=uniqueid, Body=<here should be my binary payload from POST request>)
    except ClientError as e:
        logger.error("Saving of object has failed: " + str(e.response['Error']['Message']))

    if savedObj is None:
        return {
            'statusCode': 500,
            'body': json.dumps({
                'message': 'Saving of object has failed!'
            })
        }

    return {
        'statusCode': 200,
        'body': json.dumps({
            'token': uniqueid
        })
    }

get-luggage lambda for retrieving object from s3 by given key and return binary payload in response

import boto3
import json
from pprint import pprint
from botocore.exceptions import ClientError
import logging

def lambda_handler(event, context):

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    bucket = 'bucket1'
    token = event["queryStringParameters"]["token"]

    s3 = boto3.client('s3')

    objectFromS3 = None

    try:
        objectFromS3 = s3.get_object(Bucket=bucket, Key=token)
    except ClientError as ex:
        if ex.response['Error']['Code'] == 'NoSuchKey':
            logger.info('No object found - returning empty')
        else:
            raise ex

    if objectFromS3 is None:
        return {
            'statusCode': 404,
            'body': json.dumps({
                'message': 'Cannot retrieve object from storage!'
            })
        }

    pprint(objectFromS3)
    #ContentType application/octet-stream

    return {
        'statusCode': 200,
        'body' : <binary data from retrieved s3 object here?>,
        'headers': {
            'content-type': 'application/octet-stream'
        },
        'isBase64Encoded': True
    }

I expected to retrieve binary payload in GET response and expected api gateway to pass binary payload from POST request to lambda, but none of this was achieved with the stuff i tried.

I hope i descriped my problem well enough, if any clearification is needed let me know.

best wishes,
an aws noob


问:
How to duplicate elements in a js array without creating "dependent elements"?
I am trying to modify a single element from an array whose elements were previously duplicated n times. To perform the array duplication I just relied on a custom function duplicateElements(array, times)from this post (see @Bamieh answer). As shown in the exemple below, the problem is I can't modify a single element from the array without modifying other elements:

function duplicateElements(array, times) {
  return array.reduce((res, current) => {
    return res.concat(Array(times).fill(current));
  }, []);
}

var myvar = duplicateElements([{ a: 1 }, { a: 2 }], 2);
myvar[0].a = 3;

console.log(myvar);
// (4) [{…}, {…}, {…}, {…}]
// 0: {a: 3}
// 1: {a: 3}
// 2: {a: 2}
// 3: {a: 2}
// length: 4
```

As you can see myvar[1].a was also modified although this wasn't intended. How can I avoid this issue?

答:
The main reason for this as specified in the Array.fill documentation is that when dealing with objects it will copy by reference:

When fill gets passed an object, it will copy the reference and fill
  the array with references to that object.

With lodash (and _.cloneDeep) that is one line like this:

let dubFn = (arr, t=1) =>
  _.concat(arr, _.flatMap(_.times(t, 0), x => _.cloneDeep(arr)))

let r1 = dubFn([{a:1},{b:3}])            // no parameter would mean just 1 dub
let r2 = dubFn([{a:1},{b:3},5,[1]], 2)  // 2 dublicates

r1[0].a = 3
r2[0].a = 3

console.log(r1)
console.log(r2)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script></code>```

Note that this now works with arrays/objects and primitives.

The idea is to use _.concat to return a new concatenated version of the input array with a combination of few functions which on the end return an array of cloned objects. We use _.times to return an array of in this case t elements and then for each of those elements we replace with a deep clone of the array. _.flatMap is needed to flatten the end result since we end up having array of arrays after the _.times call.

With ES6 you can do something like this:

let dubElements = (arr, t) =>
  [...arr, ...new Array(t).fill().flatMap(x => arr.map(y => ({...y})))]

let r1 = dubElements([{a:1},{b:3}])
let r2 = dubElements([{a:1},{b:3}],2)

r1[0].a = 3
r2[0].a = 3

console.log(r1)
console.log(r2)```
</div>
</div>
</p>

<p>Where we concat arrays via the spread operator and we use <code>new Array(t)</code> to create the new duplicates array and make sure we <code>fill</code> it with <code>undefined</code> in this case after which we <code>flatMap</code> the results (which we map through the <code>clone</code> via the spread operator again.</p>

<p>Note that this works <code>for your use case specifically</code>. If you want to make it more generic you have to expand more in the last map function etc.</p>

<p>If you want to preserve the order of the elements you can do something like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let dubElements = (arr, t=1) => {
  let _result = []
  arr.forEach(x => {
    for(let i=0; i<t+1; i++) {
      _result.push({...x})
    }
  })
  return _result
}

let result = dubElements([{a:1},{b:3}],2)

result[0].a = 3

console.log(result)</code>```

Body:
I am trying to modify a single element from an array whose elements were previously duplicated n times. To perform the array duplication I just relied on a custom function duplicateElements(array, times)from this post (see @Bamieh answer). As shown in the exemple below, the problem is I can't modify a single element from the array without modifying other elements:

function duplicateElements(array, times) {
  return array.reduce((res, current) => {
    return res.concat(Array(times).fill(current));
  }, []);
}

var myvar = duplicateElements([{ a: 1 }, { a: 2 }], 2);
myvar[0].a = 3;

console.log(myvar);
// (4) [{…}, {…}, {…}, {…}]
// 0: {a: 3}
// 1: {a: 3}
// 2: {a: 2}
// 3: {a: 2}
// length: 4

As you can see myvar[1].a was also modified although this wasn't intended. How can I avoid this issue?

Body:
The main reason for this as specified in the Array.fill documentation is that when dealing with objects it will copy by reference:

When fill gets passed an object, it will copy the reference and fill
  the array with references to that object.

With lodash (and _.cloneDeep) that is one line like this:

let dubFn = (arr, t=1) =>
  _.concat(arr, _.flatMap(_.times(t, 0), x => _.cloneDeep(arr)))

let r1 = dubFn([{a:1},{b:3}])            // no parameter would mean just 1 dub
let r2 = dubFn([{a:1},{b:3},5,[1]], 2)  // 2 dublicates

r1[0].a = 3
r2[0].a = 3

console.log(r1)
console.log(r2)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Note that this now works with arrays/objects and primitives.

The idea is to use _.concat to return a new concatenated version of the input array with a combination of few functions which on the end return an array of cloned objects. We use _.times to return an array of in this case t elements and then for each of those elements we replace with a deep clone of the array. _.flatMap is needed to flatten the end result since we end up having array of arrays after the _.times call.

With ES6 you can do something like this:

let dubElements = (arr, t) =>
  [...arr, ...new Array(t).fill().flatMap(x => arr.map(y => ({...y})))]

let r1 = dubElements([{a:1},{b:3}])
let r2 = dubElements([{a:1},{b:3}],2)

r1[0].a = 3
r2[0].a = 3

console.log(r1)
console.log(r2)

Where we concat arrays via the spread operator and we use new Array(t) to create the new duplicates array and make sure we fill it with undefined in this case after which we flatMap the results (which we map through the clone via the spread operator again.

Note that this works for your use case specifically. If you want to make it more generic you have to expand more in the last map function etc.

If you want to preserve the order of the elements you can do something like this:

let dubElements = (arr, t=1) => {
  let _result = []
  arr.forEach(x => {
    for(let i=0; i<t+1; i++) {
      _result.push({...x})
    }
  })
  return _result
}

let result = dubElements([{a:1},{b:3}],2)

result[0].a = 3

console.log(result)


问:
Need help removing None rows from a dask object for multiple large json files
Hi I am trying to flatten and parse only 7 out of many keys:value pairs from 30 nested large .json.gz files (4GB each before unzipping). I am trying doing the standard pandas and json combo but reading the rows one row at a time for 30 large json files didn't seem like the best idea so upon some searching I found dask that made this very fast. I am using this function I was able to flatten out and swiftly 7 fields I care about for each json object.

image of jupyter notebook code and along with the result

The goal is to grab all json objects that have key:screen and value:CAMERA. The problem is not all json objects in these files have key=screen. To override that key error for rows where there is no key=screen, I do something I know is not recommended; try and catch block. While this works, it just creates a bunch of None rows and there is no way to swiftly remove them. For more clarity, the None rows are created in places where there was nothing to flatten because that particular json object had no screen key. I want to find
either a) a way to filter out and flatten json files based on key and not just value.
OR
*b)*Find a swift dropna() equivalent for dask bags so I can get rid of all these None rows in one command.

End goal is to do this for all files for march 2018 and compile them into one dataframe for further analysis.

I have tried using other commands and methods that don't involve using dask like the module ijson and the whole prefix, value thing(check commented out part of following code screenshot). None of the alternatives seem as swift and efficient as the dask.bag method given the size of my files. An ideal solution would be finding a way to get rid of the None rows issues.

```<code>import dask.bag as db
import json
import gzip
import pandas as pd
import ijson as ij
path="etl/mar2018/mongo-feedback-2018-03-05.json.gz"
# pd.read_json(path)
# b=ij.parse(path)
# print(b)

# def parse_json(json_filename):
#     with gzip.open(path,'rt', encoding='utf-8') as input_file:
# #     with open(json_filename, 'rb')
#         # load json iteratively
#         parser = ijson.parse(input_file)
# #     return ij.items(parser)
#         for prefix, event, value in parser:
#             if prefix=='screen':
#                 print(value)
# #             print(prefix)
# #             print('prefix={}, event={}, value={}'.format(prefix, event, value))

# # if __name__ == '__main__':
# parse_json(path)
# b.head()
b=db.read_text(path).map(json.loads)
# b.to_dataframe()

# b=b.filter(lambda record: record['screen'])

# # for i in b:
# #     print(i)
# #
def flatten(record):
        try:
            return{
                'userId': record['userId'],
                'expression':record['expression'],
                'platform':record['platform'],
                'country':record['country'],
                "date":record['date']['$date'],
                "cameraImageType":record['metadataMap']["cameraImageType"],
                "screen":record['screen']
            }
        except KeyError:
            pass
df=b.map(flatten)
df.take(5)

# df.remove(None)
def filter1(record):
    if record is None:
        return record

# df.to_textfiles()
# .to_dataframe()
# p=df.map(filter1)
# df1=df-p

# # df.compute()
# # df.notnull().take(10)

# # df.dropna(how='all')
# # df.head(50)
# # p=filter(None,df)
# # list(b.filter('screen'))
# # b.count().compute()
# p=df.to_csv()
# d=df.dropna()

# d.head()

# # b.filter(lambda record: record['screen']=='CAMERA').take(10)
</code>```

(None,
 None,
 {'userId': 'foo',
  'expression': 'bar',
  'platform': 'IOS',
  'country': 'GT',
  'date': '2018-03-04T22:58:18.000Z',
  'cameraImageType': 'typed',
  'screen': 'CAMERA'},
 None,
 None)enter image description here

答:
If I understand correctly, your bag contains some elements with real data as dictionaries and some with just the value None, where the keys could not be found - you would like to keep only the real data.

I would use the filter method:

```<code>b2 = b.map(flatten).filter(bool)
</code>```

(or, to be more explicit, replace bool with lambda x: x is not None; this is a function which specifies whether you want to keep a given element or not)

Then you can write this to files, or turn into a dataframe and perform further operations on it.

Body:
Hi I am trying to flatten and parse only 7 out of many keys:value pairs from 30 nested large .json.gz files (4GB each before unzipping). I am trying doing the standard pandas and json combo but reading the rows one row at a time for 30 large json files didn't seem like the best idea so upon some searching I found dask that made this very fast. I am using this function I was able to flatten out and swiftly 7 fields I care about for each json object.

image of jupyter notebook code and along with the result

The goal is to grab all json objects that have key:screen and value:CAMERA. The problem is not all json objects in these files have key=screen. To override that key error for rows where there is no key=screen, I do something I know is not recommended; try and catch block. While this works, it just creates a bunch of None rows and there is no way to swiftly remove them. For more clarity, the None rows are created in places where there was nothing to flatten because that particular json object had no screen key. I want to find
either a) a way to filter out and flatten json files based on key and not just value.
OR
*b)*Find a swift dropna() equivalent for dask bags so I can get rid of all these None rows in one command.

End goal is to do this for all files for march 2018 and compile them into one dataframe for further analysis.

I have tried using other commands and methods that don't involve using dask like the module ijson and the whole prefix, value thing(check commented out part of following code screenshot). None of the alternatives seem as swift and efficient as the dask.bag method given the size of my files. An ideal solution would be finding a way to get rid of the None rows issues.

import dask.bag as db
import json
import gzip
import pandas as pd
import ijson as ij
path="etl/mar2018/mongo-feedback-2018-03-05.json.gz"
# pd.read_json(path)
# b=ij.parse(path)
# print(b)

# def parse_json(json_filename):
#     with gzip.open(path,'rt', encoding='utf-8') as input_file:
# #     with open(json_filename, 'rb')
#         # load json iteratively
#         parser = ijson.parse(input_file)
# #     return ij.items(parser)
#         for prefix, event, value in parser:
#             if prefix=='screen':
#                 print(value)
# #             print(prefix)
# #             print('prefix={}, event={}, value={}'.format(prefix, event, value))

# # if __name__ == '__main__':
# parse_json(path)
# b.head()
b=db.read_text(path).map(json.loads)
# b.to_dataframe()

# b=b.filter(lambda record: record['screen'])

# # for i in b:
# #     print(i)
# #
def flatten(record):
        try:
            return{
                'userId': record['userId'],
                'expression':record['expression'],
                'platform':record['platform'],
                'country':record['country'],
                "date":record['date']['$date'],
                "cameraImageType":record['metadataMap']["cameraImageType"],
                "screen":record['screen']
            }
        except KeyError:
            pass
df=b.map(flatten)
df.take(5)

# df.remove(None)
def filter1(record):
    if record is None:
        return record

# df.to_textfiles()
# .to_dataframe()
# p=df.map(filter1)
# df1=df-p

# # df.compute()
# # df.notnull().take(10)

# # df.dropna(how='all')
# # df.head(50)
# # p=filter(None,df)
# # list(b.filter('screen'))
# # b.count().compute()
# p=df.to_csv()
# d=df.dropna()

# d.head()

# # b.filter(lambda record: record['screen']=='CAMERA').take(10)

(None,
 None,
 {'userId': 'foo',
  'expression': 'bar',
  'platform': 'IOS',
  'country': 'GT',
  'date': '2018-03-04T22:58:18.000Z',
  'cameraImageType': 'typed',
  'screen': 'CAMERA'},
 None,
 None)enter image description here

Body:
If I understand correctly, your bag contains some elements with real data as dictionaries and some with just the value None, where the keys could not be found - you would like to keep only the real data.

I would use the filter method:

b2 = b.map(flatten).filter(bool)

(or, to be more explicit, replace bool with lambda x: x is not None; this is a function which specifies whether you want to keep a given element or not)

Then you can write this to files, or turn into a dataframe and perform further operations on it.


问:
How can I scale font size based on android displayMetrics?
I'm writing an app to show a simple digital clock in Android and I need to scale the font size of the TextView so that it fills the screen as much as possible. I found a quite simple way to scale text size using displayMetrics but it doesn't work correctly on some devices.
What I want to achieve looks like this:

I would work only in landscape mode, and I would like it to run on my old smartphones and tablets lying around as well as on newer devices. So I have a variety of screen types to cater to.

To scale the font I do the following

```<code>    ...
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_clock);

    // Get screen size and calculate text size needed to fit
    // TODO: doesn't work well on some devices
    TextView tvScreenSize = findViewById(R.id.tvScreenSize);
    DisplayMetrics displayMetrics = new DisplayMetrics(); // From: https://stackoverflow.com/questions/4743116/get-screen-width-and-height
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    // The screen height and width are recalculated automatically by Android when the screen is redrawn on a rotation
    height = displayMetrics.heightPixels;
    width = displayMetrics.widthPixels;
    textSP = width / 12; // Empirical value
    String hString = Integer.toString(height);
    String wString = Integer.toString(width);
    tvScreenSize.setText("h: " + hString + "  w:" + wString);

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            // Display time of day
            Date curDate = new Date();
            TextView tvTime = findViewById(R.id.clockView);
            String timeStr = format.format(curDate);

            tvTime.setText(timeStr);
            tvTime.setScaleY(1.5f);
            tvTime.setWidth(width * 8 / 10); // Make it fill 80% of the screen
            tvTime.setHeight(height * 8 / 10);
            tvTime.setTextSize(textSP);
            ...
</code>```

The quid is with the line:

```<code>textSP = width / 12; // Empirical value
</code>```

For some screens a value of 6 works well. For other screens this creates a font so big that only a small part is visible. Changing this value to 12 does the trick.

It seems that I'm missing something related to the density of the screen, but what?

Thanks!

FINAL RESULT: For anyone trying to scale text like me, here's the final code after input from ismail:

The activity_main.xml file:

```<code>?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/tvClockFace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="6dp"
    android:text="12:34"
    android:textColor="@android:color/holo_red_dark"
    android:textSize="30sp"
    android:textStyle="bold"
    android:typeface="monospace"
    app:fontFamily="monospace"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/tvScreenSize"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="H:... W:..."
    android:textSize="14sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

And the MainActivity.java:

```<code>package com.schalkx.testautosizeclockdisplay;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Scale the textsize automatically
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics outMetrics = new DisplayMetrics ();
    display.getMetrics(outMetrics);

    float density  = getResources().getDisplayMetrics().density;
    float dpHeight = outMetrics.heightPixels / density;
    float dpWidth  = outMetrics.widthPixels / density;

    // Convert height and width to integer values
    float fTextSize = dpWidth/4; // Trial and error
    // int iTextSize = Math.round(fTextSize);
    int scrHeight = Math.round(dpHeight);
    int scrWidth = Math.round(dpWidth);

    // Display de height and width on screen (for reference)
    String wString = Integer.toString(scrWidth); // In case you need the width
    String hString = Integer.toString(scrHeight); // Same for height
    TextView tvScreenSize = findViewById(R.id.tvScreenSize);
    tvScreenSize.setText("h: " + hString + "  w:" + wString);

    // Scale the font of the clock face
    TextView tvClockFace = findViewById(R.id.tvClockFace);
    // tvClockFace.setHeight(50);
    // tvClockFace.setWidth(100);
    tvClockFace.setTextSize(fTextSize);
    tvClockFace.setScaleY(1.5f);
    }
}
</code>```

答:
don't use the pixel value in your code at all. convert pixel  to device independent pixel(dp) </p>

```<code>public static float convertPixelsToDp(float px, Context context){
    return px / ((float) context.getResources().getDisplayMetrics().densityDpi/
         DisplayMetrics.DENSITY_DEFAULT);
}
</code>```

Body:
I'm writing an app to show a simple digital clock in Android and I need to scale the font size of the TextView so that it fills the screen as much as possible. I found a quite simple way to scale text size using displayMetrics but it doesn't work correctly on some devices.
What I want to achieve looks like this:

I would work only in landscape mode, and I would like it to run on my old smartphones and tablets lying around as well as on newer devices. So I have a variety of screen types to cater to.

To scale the font I do the following

    ...
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_clock);

    // Get screen size and calculate text size needed to fit
    // TODO: doesn't work well on some devices
    TextView tvScreenSize = findViewById(R.id.tvScreenSize);
    DisplayMetrics displayMetrics = new DisplayMetrics(); // From: https://stackoverflow.com/questions/4743116/get-screen-width-and-height
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    // The screen height and width are recalculated automatically by Android when the screen is redrawn on a rotation
    height = displayMetrics.heightPixels;
    width = displayMetrics.widthPixels;
    textSP = width / 12; // Empirical value
    String hString = Integer.toString(height);
    String wString = Integer.toString(width);
    tvScreenSize.setText("h: " + hString + "  w:" + wString);

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            // Display time of day
            Date curDate = new Date();
            TextView tvTime = findViewById(R.id.clockView);
            String timeStr = format.format(curDate);

            tvTime.setText(timeStr);
            tvTime.setScaleY(1.5f);
            tvTime.setWidth(width * 8 / 10); // Make it fill 80% of the screen
            tvTime.setHeight(height * 8 / 10);
            tvTime.setTextSize(textSP);
            ...

The quid is with the line:

textSP = width / 12; // Empirical value

For some screens a value of 6 works well. For other screens this creates a font so big that only a small part is visible. Changing this value to 12 does the trick.

It seems that I'm missing something related to the density of the screen, but what?

Thanks!

FINAL RESULT: For anyone trying to scale text like me, here's the final code after input from ismail:

The activity_main.xml file:

?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/tvClockFace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="6dp"
    android:text="12:34"
    android:textColor="@android:color/holo_red_dark"
    android:textSize="30sp"
    android:textStyle="bold"
    android:typeface="monospace"
    app:fontFamily="monospace"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/tvScreenSize"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="H:... W:..."
    android:textSize="14sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

And the MainActivity.java:

package com.schalkx.testautosizeclockdisplay;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Scale the textsize automatically
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics outMetrics = new DisplayMetrics ();
    display.getMetrics(outMetrics);

    float density  = getResources().getDisplayMetrics().density;
    float dpHeight = outMetrics.heightPixels / density;
    float dpWidth  = outMetrics.widthPixels / density;

    // Convert height and width to integer values
    float fTextSize = dpWidth/4; // Trial and error
    // int iTextSize = Math.round(fTextSize);
    int scrHeight = Math.round(dpHeight);
    int scrWidth = Math.round(dpWidth);

    // Display de height and width on screen (for reference)
    String wString = Integer.toString(scrWidth); // In case you need the width
    String hString = Integer.toString(scrHeight); // Same for height
    TextView tvScreenSize = findViewById(R.id.tvScreenSize);
    tvScreenSize.setText("h: " + hString + "  w:" + wString);

    // Scale the font of the clock face
    TextView tvClockFace = findViewById(R.id.tvClockFace);
    // tvClockFace.setHeight(50);
    // tvClockFace.setWidth(100);
    tvClockFace.setTextSize(fTextSize);
    tvClockFace.setScaleY(1.5f);
    }
}

Body:
don't use the pixel value in your code at all. convert pixel  to device independent pixel(dp)

public static float convertPixelsToDp(float px, Context context){
    return px / ((float) context.getResources().getDisplayMetrics().densityDpi/
         DisplayMetrics.DENSITY_DEFAULT);
}


问:
Build static library for iOS (Device and Simulator) and use in XCode
I'm new to XCode-/iOS-Development(not programming itself) and want to make some simple Apps to get used to it.

My current project is a simple QR-Code-Generation. For this task I want to use the Open Source Library libqrencode.
( http://fukuchi.org/works/qrencode/index.en.html )
I did not use open source libraries in my older coding projects but I guess I understood most of the "mechanics" ;)

Until now I tried to build the static library and include it in my XCode-Project. But when compiling code using functions from the library I get Error-Messages.

1st Problem:

I try to build for iPhone-Device like this:

```<code>#### Build libqrencode for iPhoneOS

export DEVROOT=/Developer/Platforms/iPhoneOS.platform/Developer
export HOST=arm-apple-darwin10
export TARGET=arm-apple-darwin10
export PREFIX=$HOME/Desktop/MyProjects/cocoa/libqrencode/Release-iphoneos

export AR=$DEVROOT/usr/bin/ar
export CPP=$DEVROOT/usr/bin/cpp
export CXXPP=$DEVROOT/usr/bin/cpp
export CXX=$DEVROOT/usr/bin/arm-apple-darwin10-llvm-g++-4.2
export LD=$DEVROOT/usr/bin/ld
export NM=$DEVROOT/usr/bin/nm
export RANLIB=$DEVROOT/usr/bin/ranlib

./configure --prefix=$PREFIX --host=$HOST --target=$TARGET --disable-shared --enable-static

makedepend
make
make install
</code>```

But when I include it in my XCode-Project and try to use two simple Functions from that library I get the following error:

```<code>Ld build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv6/myQRencode normal armv6
cd /Users/johnny/Desktop/MyProjects/myQRencode
setenv IPHONEOS_DEPLOYMENT_TARGET 4.2
setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 -arch armv6 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk -L/Users/johnny/Desktop/MyProjects/myQRencode/build/Release-iphoneos -L/Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Release-iphoneos/lib -F/Users/johnny/Desktop/MyProjects/myQRencode/build/Release-iphoneos -filelist /Users/johnny/Desktop/MyProjects/myQRencode/build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv6/myQRencode.LinkFileList -dead_strip -miphoneos-version-min=4.2 -framework Foundation -framework UIKit -framework CoreGraphics -lqrencode -o /Users/johnny/Desktop/MyProjects/myQRencode/build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv6/myQRencode

ld: warning: in /Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Release-iphoneos/lib/libqrencode.a, file was built for unsupported file format which is not the architecture being linked (armv6)
Undefined symbols:
  "_QRcode_encodeString", referenced from:
      _main in main.o
  "_QRcode_free", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

Ld build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv7/myQRencode normal armv7
cd /Users/johnny/Desktop/MyProjects/myQRencode
setenv IPHONEOS_DEPLOYMENT_TARGET 4.2
setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 -arch armv7 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk -L/Users/johnny/Desktop/MyProjects/myQRencode/build/Release-iphoneos -L/Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Release-iphoneos/lib -F/Users/johnny/Desktop/MyProjects/myQRencode/build/Release-iphoneos -filelist /Users/johnny/Desktop/MyProjects/myQRencode/build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv7/myQRencode.LinkFileList -dead_strip -miphoneos-version-min=4.2 -framework Foundation -framework UIKit -framework CoreGraphics -lqrencode -o /Users/johnny/Desktop/MyProjects/myQRencode/build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv7/myQRencode

ld: warning: in /Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Release-iphoneos/lib/libqrencode.a, file was built for unsupported file format which is not the architecture being linked (armv7)
Undefined symbols:
  "_QRcode_encodeString", referenced from:
      _main in main.o
  "_QRcode_free", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
</code>```

2nd Problem:

I try to build for iPhone-Device like this:

```<code>#### Build libqrencode for iPhone-Simulator

export DEVROOT=/Developer/Platforms/iPhoneSimulator.platform/Developer
export HOST=i386-apple-darwin10
export TARGET=i386-apple-darwin10
export PREFIX=$HOME/Desktop/MyProjects/cocoa/libqrencode/Debug-iphonesimulator

export AR=$DEVROOT/usr/bin/ar
export CPP=$DEVROOT/usr/bin/cpp
export CXXPP=$DEVROOT/usr/bin/cpp
export CXX=$DEVROOT/usr/bin/i686-apple-darwin10-llvm-g++-4.2
export LD=$DEVROOT/usr/bin/ld
export NM=$DEVROOT/usr/bin/nm
export RANLIB=$DEVROOT/usr/bin/ranlib

./configure --prefix=$PREFIX --host=$HOST --target=$TARGET --disable-shared --enable-static

makedepend
make
make install
</code>```

But when I include it in my XCode-Project and try to use two simple Functions from that library I get the following error (actually same error-message like above):

```<code>Ld build/Debug-iphonesimulator/myQRencode.app/myQRencode normal i386
cd /Users/johnny/Desktop/MyProjects/myQRencode
setenv MACOSX_DEPLOYMENT_TARGET 10.6
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk -L/Users/johnny/Desktop/MyProjects/myQRencode/build/Debug-iphonesimulator -L/Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Debug-iphonesimulator/lib -F/Users/johnny/Desktop/MyProjects/myQRencode/build/Debug-iphonesimulator -filelist /Users/johnny/Desktop/MyProjects/myQRencode/build/myQRencode.build/Debug-iphonesimulator/myQRencode.build/Objects-normal/i386/myQRencode.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework Foundation -framework UIKit -framework CoreGraphics -lqrencode -o /Users/johnny/Desktop/MyProjects/myQRencode/build/Debug-iphonesimulator/myQRencode.app/myQRencode

ld: warning: in /Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Debug-iphonesimulator/lib/libqrencode.a, file was built for unsupported file format which is not the architecture being linked (i386)
Undefined symbols:
  "_QRcode_encodeString", referenced from:
      _main in main.o
  "_QRcode_free", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
</code>```

Question 1:
I also tried HOST and TARGET to be set to i686, but that didn't work either (same error message). Unfortunately I only have "i686-apple-darwin10-llvm-g++-4.2" and similar ones, but no "i386-xxxx....". Is this the problem or what settings did I choose wrong?

Question 2:
How do I check what target the library was built for? Is there a special command in bash?
I remember when first time building libqrencode I needed to get libpng12. Until now I do not use any commands for creating PNGs but I did not rebuild it for the iPhone-Simulator nor the iPhone-Device. Will the libpng12-library still be linked by XCode and could this consequently be the source of error?

Any help appreciated. Sorry for the long post, but I wanted to be as thorough as possible. Thans allready!!

Added Infos:

I managed to build libpng12 for I386 using the following Configuration-Settings:

```<code>#! /bin/bash

#### Build libpng12 for iPhone-Simulator

unset CPATH
unset C_INCLUDE_PATH
unset CPLUS_INCLUDE_PATH
unset OBJC_INCLUDE_PATH
unset LIBS
unset DYLD_FALLBACK_LIBRARY_PATH
unset DYLD_FALLBACK_FRAMEWORK_PATH

unset CPP
unset CXXPP
unset CC
unset CXX
unset LD
unset STRIP
unset CPPFLAGS
unset CFLAGS
unset CXXFLAGS
unset LDFLAGS
unset AS
unset ASCPP

export SDKVER="4.2"
export DEVROOT="/Developer/Platforms/iPhoneSimulator.platform/Developer"
export SDKROOT="$DEVROOT/SDKs/iPhoneSimulator$SDKVER.sdk"

export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig"
export PKG_CONFIG_LIBDIR="$PKG_CONFIG_PATH"
export PREFIX="$HOME/Desktop/MyProjects/cocoa/libpng12/Debug-iphonesimulator"
export AS="$DEVROOT/usr/bin/as"
export ASCPP="$DEVROOT/usr/bin/as"
export AR="$DEVROOT/usr/bin/ar"
export RANLIB="$DEVROOT/usr/bin/ranlib"
export CPPFLAGS="-miphoneos-version-min=$SDKVER -std=c99 -pipe -no-cpp-precomp -I$SDKROOT/usr/include -I$HOME/Desktop/MyProjects/cocoa/libpng12/Debug-iphonesimulator/include -I/usr/local/iphone-simulator-$SDKVER/include"
export CFLAGS="-miphoneos-version-min=$SDKVER -std=c99 -arch i386 -pipe -no-cpp-precomp --sysroot='$SDKROOT' -isystem $SDKROOT/usr/include -isystem $HOME/Desktop/MyProjects/cocoa/libpng12/Debug-iphonesimulator/include -isystem /usr/local/iphone-simulator-$SDKVER/include -m32"
export CXXFLAGS="-miphoneos-version-min=$SDKVER -std=c99 -arch i386 -pipe -no-cpp-precomp --sysroot='$SDKROOT' -isystem $SDKROOT/usr/include -isystem $HOME/Desktop/MyProjects/cocoa/libpng12/Debug-iphonesimulator/include -isystem /usr/local/iphone-simulator-$SDKVER/include"
export LDFLAGS="-miphoneos-version-min=$SDKVER -arch i386 --sysroot='$SDKROOT' -L$SDKROOT/usr/lib -L$HOME/Desktop/MyProjects/cocoa/libpng12/Debug-iphonesimulator/lib -L/usr/local/iphone-simulator-$SDKVER/lib"
export CPP="$DEVROOT/usr/bin/cpp"
export CXXCPP="$DEVROOT/usr/bin/cpp"
export CC="$DEVROOT/usr/bin/gcc-4.2"
export CXX="$DEVROOT/usr/bin/g++-4.2"
export LD="$DEVROOT/usr/bin/ld"
export STRIP="$DEVROOT/usr/bin/strip"

./configure --prefix="$PREFIX" --host="i386-apple-darwin9" --enable-static --disable-shared
</code>```

But when I try using similar/same settings for libqrencode I get following error:

```<code>make  all-recursive
Making all in .
/bin/sh ./libtool --tag=CC   --mode=link gcc  -Wall -miphoneos-version-min=4.2 -std=c99 -arch i386 -pipe -no-cpp-precomp --sysroot='/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk' -isystem /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/usr/include -isystem /Users/johnny/Desktop/MyProjects/cocoa/libqrencode/Debug-iphonesimulator/include -isystem /usr/local/iphone-simulator-4.2/include -m32 -version-number 3:1:1 -miphoneos-version-min=4.2 -arch i386 --sysroot='/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk' -L/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/usr/lib -L/Users/johnny/Desktop/MyProjects/cocoa/libqrencode/Debug-iphonesimulator/lib -L/usr/local/iphone-simulator-4.2/lib -m32 -o libqrencode.la -rpath /Users/johnny/Desktop/MyProjects/cocoa/libqrencode/Debug-iphonesimulator/lib qrencode.lo qrinput.lo bitstream.lo qrspec.lo rscode.lo split.lo mask.lo
libtool: link: rm -fr  .libs/libqrencode.a
libtool: link: /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ar cru .libs/libqrencode.a  qrencode.o qrinput.o bitstream.o qrspec.o rscode.o split.o mask.o
/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(bitstream.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(rscode.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(split.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
libtool: link: /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ranlib .libs/libqrencode.a
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(bitstream.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(rscode.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(split.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
make[2]: *** [libqrencode.la] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
</code>```

答: Sorry for not helping you with your compile problems, but it seems you have a much bigger issue: libqrencode is licensed under LGPL, and many consider it to be incompatible with Apple's terms (another article about GPL/LGPL being incompatible with Apple's terms). So you might put yourself at a legal risk by using libqrencode in your app.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm new to XCode-/iOS-Development(not programming itself) and want to make some simple Apps to get used to it.

My current project is a simple QR-Code-Generation. For this task I want to use the Open Source Library libqrencode.
( http://fukuchi.org/works/qrencode/index.en.html )
I did not use open source libraries in my older coding projects but I guess I understood most of the "mechanics" ;)

Until now I tried to build the static library and include it in my XCode-Project. But when compiling code using functions from the library I get Error-Messages.

1st Problem:

I try to build for iPhone-Device like this:

#### Build libqrencode for iPhoneOS

export DEVROOT=/Developer/Platforms/iPhoneOS.platform/Developer
export HOST=arm-apple-darwin10
export TARGET=arm-apple-darwin10
export PREFIX=$HOME/Desktop/MyProjects/cocoa/libqrencode/Release-iphoneos

export AR=$DEVROOT/usr/bin/ar
export CPP=$DEVROOT/usr/bin/cpp
export CXXPP=$DEVROOT/usr/bin/cpp
export CXX=$DEVROOT/usr/bin/arm-apple-darwin10-llvm-g++-4.2
export LD=$DEVROOT/usr/bin/ld
export NM=$DEVROOT/usr/bin/nm
export RANLIB=$DEVROOT/usr/bin/ranlib

./configure --prefix=$PREFIX --host=$HOST --target=$TARGET --disable-shared --enable-static

makedepend
make
make install

But when I include it in my XCode-Project and try to use two simple Functions from that library I get the following error:

Ld build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv6/myQRencode normal armv6
cd /Users/johnny/Desktop/MyProjects/myQRencode
setenv IPHONEOS_DEPLOYMENT_TARGET 4.2
setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 -arch armv6 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk -L/Users/johnny/Desktop/MyProjects/myQRencode/build/Release-iphoneos -L/Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Release-iphoneos/lib -F/Users/johnny/Desktop/MyProjects/myQRencode/build/Release-iphoneos -filelist /Users/johnny/Desktop/MyProjects/myQRencode/build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv6/myQRencode.LinkFileList -dead_strip -miphoneos-version-min=4.2 -framework Foundation -framework UIKit -framework CoreGraphics -lqrencode -o /Users/johnny/Desktop/MyProjects/myQRencode/build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv6/myQRencode

ld: warning: in /Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Release-iphoneos/lib/libqrencode.a, file was built for unsupported file format which is not the architecture being linked (armv6)
Undefined symbols:
  "_QRcode_encodeString", referenced from:
      _main in main.o
  "_QRcode_free", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

Ld build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv7/myQRencode normal armv7
cd /Users/johnny/Desktop/MyProjects/myQRencode
setenv IPHONEOS_DEPLOYMENT_TARGET 4.2
setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 -arch armv7 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk -L/Users/johnny/Desktop/MyProjects/myQRencode/build/Release-iphoneos -L/Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Release-iphoneos/lib -F/Users/johnny/Desktop/MyProjects/myQRencode/build/Release-iphoneos -filelist /Users/johnny/Desktop/MyProjects/myQRencode/build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv7/myQRencode.LinkFileList -dead_strip -miphoneos-version-min=4.2 -framework Foundation -framework UIKit -framework CoreGraphics -lqrencode -o /Users/johnny/Desktop/MyProjects/myQRencode/build/myQRencode.build/Release-iphoneos/myQRencode.build/Objects-normal/armv7/myQRencode

ld: warning: in /Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Release-iphoneos/lib/libqrencode.a, file was built for unsupported file format which is not the architecture being linked (armv7)
Undefined symbols:
  "_QRcode_encodeString", referenced from:
      _main in main.o
  "_QRcode_free", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

2nd Problem:

I try to build for iPhone-Device like this:

#### Build libqrencode for iPhone-Simulator

export DEVROOT=/Developer/Platforms/iPhoneSimulator.platform/Developer
export HOST=i386-apple-darwin10
export TARGET=i386-apple-darwin10
export PREFIX=$HOME/Desktop/MyProjects/cocoa/libqrencode/Debug-iphonesimulator

export AR=$DEVROOT/usr/bin/ar
export CPP=$DEVROOT/usr/bin/cpp
export CXXPP=$DEVROOT/usr/bin/cpp
export CXX=$DEVROOT/usr/bin/i686-apple-darwin10-llvm-g++-4.2
export LD=$DEVROOT/usr/bin/ld
export NM=$DEVROOT/usr/bin/nm
export RANLIB=$DEVROOT/usr/bin/ranlib

./configure --prefix=$PREFIX --host=$HOST --target=$TARGET --disable-shared --enable-static

makedepend
make
make install

But when I include it in my XCode-Project and try to use two simple Functions from that library I get the following error (actually same error-message like above):

Ld build/Debug-iphonesimulator/myQRencode.app/myQRencode normal i386
cd /Users/johnny/Desktop/MyProjects/myQRencode
setenv MACOSX_DEPLOYMENT_TARGET 10.6
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk -L/Users/johnny/Desktop/MyProjects/myQRencode/build/Debug-iphonesimulator -L/Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Debug-iphonesimulator/lib -F/Users/johnny/Desktop/MyProjects/myQRencode/build/Debug-iphonesimulator -filelist /Users/johnny/Desktop/MyProjects/myQRencode/build/myQRencode.build/Debug-iphonesimulator/myQRencode.build/Objects-normal/i386/myQRencode.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework Foundation -framework UIKit -framework CoreGraphics -lqrencode -o /Users/johnny/Desktop/MyProjects/myQRencode/build/Debug-iphonesimulator/myQRencode.app/myQRencode

ld: warning: in /Users/johnny/Desktop/MyProjects/myQRencode/libqrencode/Debug-iphonesimulator/lib/libqrencode.a, file was built for unsupported file format which is not the architecture being linked (i386)
Undefined symbols:
  "_QRcode_encodeString", referenced from:
      _main in main.o
  "_QRcode_free", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

Question 1:
I also tried HOST and TARGET to be set to i686, but that didn't work either (same error message). Unfortunately I only have "i686-apple-darwin10-llvm-g++-4.2" and similar ones, but no "i386-xxxx....". Is this the problem or what settings did I choose wrong?

Question 2:
How do I check what target the library was built for? Is there a special command in bash?
I remember when first time building libqrencode I needed to get libpng12. Until now I do not use any commands for creating PNGs but I did not rebuild it for the iPhone-Simulator nor the iPhone-Device. Will the libpng12-library still be linked by XCode and could this consequently be the source of error?

Any help appreciated. Sorry for the long post, but I wanted to be as thorough as possible. Thans allready!!

Added Infos:

I managed to build libpng12 for I386 using the following Configuration-Settings:

#! /bin/bash

#### Build libpng12 for iPhone-Simulator

unset CPATH
unset C_INCLUDE_PATH
unset CPLUS_INCLUDE_PATH
unset OBJC_INCLUDE_PATH
unset LIBS
unset DYLD_FALLBACK_LIBRARY_PATH
unset DYLD_FALLBACK_FRAMEWORK_PATH

unset CPP
unset CXXPP
unset CC
unset CXX
unset LD
unset STRIP
unset CPPFLAGS
unset CFLAGS
unset CXXFLAGS
unset LDFLAGS
unset AS
unset ASCPP

export SDKVER="4.2"
export DEVROOT="/Developer/Platforms/iPhoneSimulator.platform/Developer"
export SDKROOT="$DEVROOT/SDKs/iPhoneSimulator$SDKVER.sdk"

export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig"
export PKG_CONFIG_LIBDIR="$PKG_CONFIG_PATH"
export PREFIX="$HOME/Desktop/MyProjects/cocoa/libpng12/Debug-iphonesimulator"
export AS="$DEVROOT/usr/bin/as"
export ASCPP="$DEVROOT/usr/bin/as"
export AR="$DEVROOT/usr/bin/ar"
export RANLIB="$DEVROOT/usr/bin/ranlib"
export CPPFLAGS="-miphoneos-version-min=$SDKVER -std=c99 -pipe -no-cpp-precomp -I$SDKROOT/usr/include -I$HOME/Desktop/MyProjects/cocoa/libpng12/Debug-iphonesimulator/include -I/usr/local/iphone-simulator-$SDKVER/include"
export CFLAGS="-miphoneos-version-min=$SDKVER -std=c99 -arch i386 -pipe -no-cpp-precomp --sysroot='$SDKROOT' -isystem $SDKROOT/usr/include -isystem $HOME/Desktop/MyProjects/cocoa/libpng12/Debug-iphonesimulator/include -isystem /usr/local/iphone-simulator-$SDKVER/include -m32"
export CXXFLAGS="-miphoneos-version-min=$SDKVER -std=c99 -arch i386 -pipe -no-cpp-precomp --sysroot='$SDKROOT' -isystem $SDKROOT/usr/include -isystem $HOME/Desktop/MyProjects/cocoa/libpng12/Debug-iphonesimulator/include -isystem /usr/local/iphone-simulator-$SDKVER/include"
export LDFLAGS="-miphoneos-version-min=$SDKVER -arch i386 --sysroot='$SDKROOT' -L$SDKROOT/usr/lib -L$HOME/Desktop/MyProjects/cocoa/libpng12/Debug-iphonesimulator/lib -L/usr/local/iphone-simulator-$SDKVER/lib"
export CPP="$DEVROOT/usr/bin/cpp"
export CXXCPP="$DEVROOT/usr/bin/cpp"
export CC="$DEVROOT/usr/bin/gcc-4.2"
export CXX="$DEVROOT/usr/bin/g++-4.2"
export LD="$DEVROOT/usr/bin/ld"
export STRIP="$DEVROOT/usr/bin/strip"

./configure --prefix="$PREFIX" --host="i386-apple-darwin9" --enable-static --disable-shared

But when I try using similar/same settings for libqrencode I get following error:

make  all-recursive
Making all in .
/bin/sh ./libtool --tag=CC   --mode=link gcc  -Wall -miphoneos-version-min=4.2 -std=c99 -arch i386 -pipe -no-cpp-precomp --sysroot='/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk' -isystem /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/usr/include -isystem /Users/johnny/Desktop/MyProjects/cocoa/libqrencode/Debug-iphonesimulator/include -isystem /usr/local/iphone-simulator-4.2/include -m32 -version-number 3:1:1 -miphoneos-version-min=4.2 -arch i386 --sysroot='/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk' -L/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/usr/lib -L/Users/johnny/Desktop/MyProjects/cocoa/libqrencode/Debug-iphonesimulator/lib -L/usr/local/iphone-simulator-4.2/lib -m32 -o libqrencode.la -rpath /Users/johnny/Desktop/MyProjects/cocoa/libqrencode/Debug-iphonesimulator/lib qrencode.lo qrinput.lo bitstream.lo qrspec.lo rscode.lo split.lo mask.lo
libtool: link: rm -fr  .libs/libqrencode.a
libtool: link: /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ar cru .libs/libqrencode.a  qrencode.o qrinput.o bitstream.o qrspec.o rscode.o split.o mask.o
/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(bitstream.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(rscode.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(split.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
libtool: link: /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ranlib .libs/libqrencode.a
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(bitstream.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(rscode.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/ranlib: archive member: .libs/libqrencode.a(split.o) cputype (16777223) does not match previous archive members cputype (7) (all members must match)
make[2]: *** [libqrencode.la] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2


问:
Copy data from one table to another - Ignore duplicates Postgresql
I am using Postgresql db. I have data in two tables. Table A has 10 records and Table B 5 records.

I would like to copy Table A data to Table B but only copy the new entries (5 records) and ignore the duplicates/already existing data

I would like to copy data from Table A to Table B where Table B will have 10 records (5 old records + 5 new records from Table A)

Can you please help me as to how can this be done?

答:
If you are looking to copy rows unique to A that are not in B then you can use INSERT...SELECT. The SELECT statement should use the union operator EXCEPT:

```<code>INSERT INTO B (column)
SELECT column FROM A
EXCEPT
SELECT column FROM B;
</code>```

EXCEPT (https://www.postgresql.org/docs/current/queries-union.html) compares the two result sets and will return the distinct rows present in result A but not in B, then supply these values to INSERT. For this to work both the columns and respective datatypes must match in both SELECT queries and your INSERT.

Body:
If you are looking to copy rows unique to A that are not in B then you can use INSERT...SELECT. The SELECT statement should use the union operator EXCEPT:

INSERT INTO B (column)
SELECT column FROM A
EXCEPT
SELECT column FROM B;

EXCEPT (https://www.postgresql.org/docs/current/queries-union.html) compares the two result sets and will return the distinct rows present in result A but not in B, then supply these values to INSERT. For this to work both the columns and respective datatypes must match in both SELECT queries and your INSERT.


问:
Using two semaphores in one method
I'm stuck on this assignment and I just can't get my head around it.

Let's say there's a queue of visitors waiting to get into one of the cars which are also queued. Only one car at a time is supposed to drive up to the platform to pick up 2 waiting people. As soon as 2 visitors enter the car it has to leave the platform.

I need to change the following methods "carArrives()" and "visitorArrives()" from Busy - Waiting to using either only Mutex or Semaphores.

Sorry for any mistakes.

```<code>int availableCars = 0;
int availableSeats = 0;

void carArrives(){
     while(availableCars > 0){noop;}   //exchange this with Mutex/Semaphore
     availableCars = 1;
     driveToPlatform();
     openDoors();
     availableSeats = 2;
     while(availableSeats > 0){noop;} //exchange this with Mutex/Semaphore
     closeDoors();
     leavePlatform();
     availableCars = 0;
}

void visitorArrives(){
     while(availableSeats < 1){noop;} //exchange this with Mutex/Semaphore
     enterCar();
     availableSeats = availableSeats - 1;

}
</code>```

答:
if you generate a mutex:

```<code>pthread_mutex MyMutex = PTHREAD_MUTEX_INIT;
</code>```

Then to stop any other part of the program from modifying some resource while the current thread is modifying/accessing the resource:

```<code>pthread_mutex_lock( &MyMutex );
// modify or access resource here
pthread_mutex_unlock( &MyMutex );
</code>```

Note:  to be effective, all places in the code that access that resource must use the same 'MyMutex'

regarding:

```<code>availableSeats = 2;
while(availableSeats > 0){noop;}
</code>```

Suggest between locking a mutex for that same resource, to pause a bit, while not locked, to allow some other thread some time to modify the 'availableSeats' value.  For instance:

```<code>pthread_mutex SeatsFilled = PTHREAD_MUTEX_INIT;
...
pthread_mutex_lock( &SeatsFilled );
availableSeats = 2;
pthread_mutex_unlock( &SeatsFilled );
...
do
{
    int numSeats;
    pthread_mutex_lock( &SeatsFilled );
    numSeats = availableSeats;
    pthread_mutex_unlock( &SeatsFilled );

    if( !numSeats )
    {
        nanosleep( 1000 );
    }
} while( numSeats );
...
</code>```

Title: Using two semaphores in one method

Body:
I'm stuck on this assignment and I just can't get my head around it.

Let's say there's a queue of visitors waiting to get into one of the cars which are also queued. Only one car at a time is supposed to drive up to the platform to pick up 2 waiting people. As soon as 2 visitors enter the car it has to leave the platform.

I need to change the following methods "carArrives()" and "visitorArrives()" from Busy - Waiting to using either only Mutex or Semaphores.

Sorry for any mistakes.

int availableCars = 0;
int availableSeats = 0;

void carArrives(){
     while(availableCars > 0){noop;}   //exchange this with Mutex/Semaphore
     availableCars = 1;
     driveToPlatform();
     openDoors();
     availableSeats = 2;
     while(availableSeats > 0){noop;} //exchange this with Mutex/Semaphore
     closeDoors();
     leavePlatform();
     availableCars = 0;
}

void visitorArrives(){
     while(availableSeats < 1){noop;} //exchange this with Mutex/Semaphore
     enterCar();
     availableSeats = availableSeats - 1;

}

Body:
if you generate a mutex:

pthread_mutex MyMutex = PTHREAD_MUTEX_INIT;

Then to stop any other part of the program from modifying some resource while the current thread is modifying/accessing the resource:

pthread_mutex_lock( &MyMutex );
// modify or access resource here
pthread_mutex_unlock( &MyMutex );

Note:  to be effective, all places in the code that access that resource must use the same 'MyMutex'

regarding:

availableSeats = 2;
while(availableSeats > 0){noop;}

Suggest between locking a mutex for that same resource, to pause a bit, while not locked, to allow some other thread some time to modify the 'availableSeats' value.  For instance:

pthread_mutex SeatsFilled = PTHREAD_MUTEX_INIT;
...
pthread_mutex_lock( &SeatsFilled );
availableSeats = 2;
pthread_mutex_unlock( &SeatsFilled );
...
do
{
    int numSeats;
    pthread_mutex_lock( &SeatsFilled );
    numSeats = availableSeats;
    pthread_mutex_unlock( &SeatsFilled );

    if( !numSeats )
    {
        nanosleep( 1000 );
    }
} while( numSeats );
...


问:
What does this Python code do? Explanation of brackets
Can you explain these lines?
I can't understand what's happening in brackets (j,pbase).

```<code>mults = {}
if c in mults:
    (j,pbase) = mults.pop(c)
</code>```

答: the python .pop() function will remove the item at that index and then return whatever was deleted. this means that the element of mults at index c will be stored within j and pbase. the way this is written would suggest that each element of the list is a tuple or such. this would mean that the first item goes in j and the second in pbase.

Body:
Can you explain these lines?
I can't understand what's happening in brackets (j,pbase).

mults = {}
if c in mults:
    (j,pbase) = mults.pop(c)


问:
Delete folder in Amazon S3 using PHP
I just started trying out Amazon S3 for hosting my website's images. I'm using the official Amazon AWS PHP SDK library.

Problem: How can I delete all files located in a S3 'folder'?

 For example if I have a file named images/2012/photo.jpg, I want to delete all files whose filenames start with images/2012/.

答:
I've tested this and it works 2019-05-28

```<code>function Amazon_s3_delete_dir($delPath, $s3, $bucket) {
//the $dir is the path to the directory including the directory
// the directories need to have a / at the end.
// Clear it just in case it may or may not be there and then add it back in.
$dir = rtrim($dir, "/");
$dir = ltrim($dir, "/");
$dir = $dir . "/";

$response = $s3->getIterator(
        'ListObjects',
        [
            'Bucket' => $bucket,
            'Prefix' => $delPath
        ]
);
//delete each
foreach ($response as $object) {
    $fileName = $object['Key'];
    $s3->deleteObject([
        'Bucket' => $bucket,
        'Key' => $fileName
    ]);
}//foreach

    return true;
 }//function
</code>```

Usage:

```<code>$delPath = $myDir . $theFolderName . "/";
Amazon_s3_delete_dir($delPath, $s3, $bucket);
</code>```

Title: Delete folder in Amazon S3 using PHP

Body:
I've tested this and it works 2019-05-28

function Amazon_s3_delete_dir($delPath, $s3, $bucket) {
//the $dir is the path to the directory including the directory
// the directories need to have a / at the end.
// Clear it just in case it may or may not be there and then add it back in.
$dir = rtrim($dir, "/");
$dir = ltrim($dir, "/");
$dir = $dir . "/";

$response = $s3->getIterator(
        'ListObjects',
        [
            'Bucket' => $bucket,
            'Prefix' => $delPath
        ]
);
//delete each
foreach ($response as $object) {
    $fileName = $object['Key'];
    $s3->deleteObject([
        'Bucket' => $bucket,
        'Key' => $fileName
    ]);
}//foreach

    return true;
 }//function

Usage:

$delPath = $myDir . $theFolderName . "/";
Amazon_s3_delete_dir($delPath, $s3, $bucket);


问:
Big O: Is this FOR loop O(n log(n)) or O(log(n)^2)?
I have a generic function

```<code>for i from 1 to n; i = 2i; {
    for j from 1 to i; {
        (constant time stuff)
    }
}
</code>```

For this function, the first line for i from 1 to n; i = 2i; I know is O(log(n)). The line (constant time stuff) is irrelevant so who cares since it's O(1).

But the middle line for j from 1 to i; is where I'm having trouble.

I'm assuming that the Big O of this line is the same as the first, since it's following the same pattern as the first where the i is doubled after each iteration, which would make it O(log(n)), but could it also be O(n)?

Also, if it is in fact O(log(n)) * O(log(n)), that's just O(log(n)^2) correct?

Sorry, I just started this Big O stuff and unfortunately I've had to rely on the internet so far since my teacher isn't very good :(

答:
Abusing notation a bit, you have

```<code>  sum_{i=1..log n} ( sum_{j=1..2^i} O(1) )
= sum_{i=1..log n} (2^i * O(1))
= O(2^(log n + 1))
= O(n)
</code>```

The second but last equivalence can be proven by an easy induction:

```<code>  2^(n+1)
= 2 * 2^n
= 2 * (sum_{i=0..n-1} (2^i) + 1)
= sum_{i=1..n} (2^i) + 2
= sum_{i=0..n} (2^i) + 1
</code>```

with base case n=1: 2^1 = 1+1 = 2^0+1.

Body:
I have a generic function

for i from 1 to n; i = 2i; {
    for j from 1 to i; {
        (constant time stuff)
    }
}

For this function, the first line for i from 1 to n; i = 2i; I know is O(log(n)). The line (constant time stuff) is irrelevant so who cares since it's O(1).

But the middle line for j from 1 to i; is where I'm having trouble.

I'm assuming that the Big O of this line is the same as the first, since it's following the same pattern as the first where the i is doubled after each iteration, which would make it O(log(n)), but could it also be O(n)?

Also, if it is in fact O(log(n)) * O(log(n)), that's just O(log(n)^2) correct?

Sorry, I just started this Big O stuff and unfortunately I've had to rely on the internet so far since my teacher isn't very good :(

Body:
Abusing notation a bit, you have

  sum_{i=1..log n} ( sum_{j=1..2^i} O(1) )
= sum_{i=1..log n} (2^i * O(1))
= O(2^(log n + 1))
= O(n)

The second but last equivalence can be proven by an easy induction:

  2^(n+1)
= 2 * 2^n
= 2 * (sum_{i=0..n-1} (2^i) + 1)
= sum_{i=1..n} (2^i) + 2
= sum_{i=0..n} (2^i) + 1

with base case n=1: 2^1 = 1+1 = 2^0+1.