问:
Why isn't column data for a table visible when viewing data?
I added some custom columns to a table and then imported data to the Dataverse database table from an Excel file.  When I choose Data>Edit Data In Excel, all of the imported data is visible in Excel.  When just clicking on the Data option, however, only the "ID" and "Created On" columns are displayed.  Also, when clicking on a row and clicking on the Edit Record button, those same "ID" and "Created On" columns are the only ones that are visible.

How do you view data in a Dataverse table (other than viewing in Excel)?

Screenshot of the empty Dataverse table in the web UI

答:
There are a couple of ways to make sure that you can see the data you want.

#1 Make a new "Entity Form"

the Form will allow you to insert and update data in the table

go to Tables > your_table > Forms

choose main form

once you create, save, and publish your form it will the same layout shown to you when you go to edit individual entries in the table
-- this is one form I made

-- same view when I edit a single table row

go to Tables > your_table > Data > choose the record and then hit edit record at top

and then you will be taken to a screen that will allow you to edit that row

#2 Make a new table "View"

the View will be used to display they data that you designate when building it

go to Tables > your_table > Views > make a new view or update default one

I would recommend updating the "Active your_tableName" view that is provided by default.

I've already updated mine so it's called Approved ERG Groups.

Once you've made your View, go to Data tab and that view along with any other will now be choices to display table data from the drop down in top right corner.

Hope that helps you out.

Happy Building.


来源: stackexchange

问:
numpy inplace mixed operand type operations possible?
In C/C++, I can do:

```<code>uint8 i = 10;
i = uint8(i * 1.1f);
</code>```

In numpy:

```<code>i = array([10,], dtype=np.uint8);
i.mutiply(i, 1.1, out=i);
</code>```

... fails because the result of the operands (int*float) is not the same dtype as out.

Nevertheless, this is what I'd like to do - in-place mixed type operations in order to avoid unnecessarily created very many, and very large matrices.

Is there any support for this in numpy?

答:
You can use np.multiply with casting='unsafe':

```<code>In [8]: i = array([10,], dtype=np.uint8)

In [9]: i
Out[9]: array([10], dtype=uint8)

In [10]: np.multiply(i, 1.1, out=i, casting='unsafe')
Out[10]: array([11], dtype=uint8)

In [11]: i
Out[11]: array([11], dtype=uint8)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In C/C++, I can do:

uint8 i = 10;
i = uint8(i * 1.1f);

In numpy:

i = array([10,], dtype=np.uint8);
i.mutiply(i, 1.1, out=i);

... fails because the result of the operands (int*float) is not the same dtype as out.

Nevertheless, this is what I'd like to do - in-place mixed type operations in order to avoid unnecessarily created very many, and very large matrices.

Is there any support for this in numpy?

Body:
You can use np.multiply with casting='unsafe':

In [8]: i = array([10,], dtype=np.uint8)

In [9]: i
Out[9]: array([10], dtype=uint8)

In [10]: np.multiply(i, 1.1, out=i, casting='unsafe')
Out[10]: array([11], dtype=uint8)

In [11]: i
Out[11]: array([11], dtype=uint8)


问:
JavaScript syntax check with JavaScript?
How could a Commando like me check if inputed code is a valid JavaScript source using some JavaScript built-in methods (if any!) or in any other possible way!? (Something like a preparser found in various IDE's like NetBeans, Eclipse, etc)?

I have to check if code is OKAY and then window.eval()-it to the current document instance.

答:
Assuming that your need is to check whether the code will not throw any syntax errors, following is my solution:

```<code>var code = "asdfsd = 1";

try {
    (function(){
        new Function(code);
    })()
}
catch(e) {
    alert('error');
}
</code>```

Working Example: http://jsfiddle.net/5NpGa/

Body:
Assuming that your need is to check whether the code will not throw any syntax errors, following is my solution:

var code = "asdfsd = 1";

try {
    (function(){
        new Function(code);
    })()
}
catch(e) {
    alert('error');
}

Working Example: http://jsfiddle.net/5NpGa/

ContentLicense: CC BY-SA 3.0


问:
Next.js v12 middleware does not work with node-fetch and axios
I am currently trying to create a middleware that will user's data by fetching an external endpoint with Axios. Axios too, does not work with the middleware. Here is my error when using node-fetch:

```<code>Module build failed: UnhandledSchemeError: Reading from "node:buffer" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.
</code>```

Any idea why this happens?

Here is my code:

```<code>import fetch from "node-fetch"
import { getSession } from "next-auth/react";
import { NextMiddleware, NextResponse } from "next/server";

export const middleware: NextMiddleware = async (req, ev) => {
  const session = await getSession() as any;
  const user = await fetch("some-url", {
    headers: {
      Authorization: `Bearer ${session?.user?.someproperty}`,
    },
  });

  if (user.statusCode !== 200) return NextResponse.redirect(req.url);
  else return NextResponse.next();
};
</code>```

答:
In my case I was using axios inside middleware, and got the following error

```<code>error - node_modules\axios\lib\core\dispatchRequest.js (53:0) @ dispatchRequest
TypeError: adapter is not a function
</code>```

I had to install axios-fetch-adapter according to this question

My code would like

import type { NextFetchEvent, NextRequest } from 'next/server'
import fetchAdapter from '@vespaiach/axios-fetch-adapter'
import axios from 'axios'

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
    const axiosInstance = axios.create({
        adapter: fetchAdapter
    })

    const data = await axiosInstance.get('/whatever-url')

    // the rest of the code

}
```
<p>Or if you already had a preconfigured instance with custom options</p>
<pre class="lang-js prettyprint-override"><code>import type { NextFetchEvent, NextRequest } from 'next/server'
import fetchAdapter from '@vespaiach/axios-fetch-adapter'
import axiosInstance from './the-path-of-your-instance'

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
    axiosInstance.defaults.adapter = fetchAdapter

    const data = await axiosInstance.get('/whatever-url')

    // the rest of the code

}
</code>```

Body:
I am currently trying to create a middleware that will user's data by fetching an external endpoint with Axios. Axios too, does not work with the middleware. Here is my error when using node-fetch:

Module build failed: UnhandledSchemeError: Reading from "node:buffer" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.

Any idea why this happens?

Here is my code:

import fetch from "node-fetch"
import { getSession } from "next-auth/react";
import { NextMiddleware, NextResponse } from "next/server";

export const middleware: NextMiddleware = async (req, ev) => {
  const session = await getSession() as any;
  const user = await fetch("some-url", {
    headers: {
      Authorization: `Bearer ${session?.user?.someproperty}`,
    },
  });

  if (user.statusCode !== 200) return NextResponse.redirect(req.url);
  else return NextResponse.next();
};

Body:
In my case I was using axios inside middleware, and got the following error

error - node_modules\axios\lib\core\dispatchRequest.js (53:0) @ dispatchRequest
TypeError: adapter is not a function

I had to install axios-fetch-adapter according to this question

My code would like

import type { NextFetchEvent, NextRequest } from 'next/server'
import fetchAdapter from '@vespaiach/axios-fetch-adapter'
import axios from 'axios'

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
    const axiosInstance = axios.create({
        adapter: fetchAdapter
    })

    const data = await axiosInstance.get('/whatever-url')

    // the rest of the code

}

Or if you already had a preconfigured instance with custom options

import type { NextFetchEvent, NextRequest } from 'next/server'
import fetchAdapter from '@vespaiach/axios-fetch-adapter'
import axiosInstance from './the-path-of-your-instance'

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
    axiosInstance.defaults.adapter = fetchAdapter

    const data = await axiosInstance.get('/whatever-url')

    // the rest of the code

}


问:
Php IntlDateFormatter class does not show unix timestamp
I'm trying to get the unix timestamp with IntlDateFormatter.

I've tried this

$formatter = new IntlDateFormatter(
        'fr_FR',
        IntlDateFormatter::FULL,
        IntlDateFormatter::FULL,
        'Europe/Paris',
        IntlDateFormatter::TRADITIONAL,
        'unix'
    );
echo $formatter->format(strtotime('now'));
```

Gave me 2022, while I'm trying to get it in this format 1644601950.

I've also tried to change unix with U AND u etc. but I can't find the right keyword for the unix timestamp in IntlDateFormatter class.

If I change the 'unix' to 'YY-MM-d' it would give me 22-02-11, but it's not in unix timestamp format.

答:
Quick answer

To get unix timestamp with IntlDateFormatter class. Use this code.

```<code>$formatter = new IntlDateFormatter(
    'fr_FR',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'Europe/Paris',
    IntlDateFormatter::TRADITIONAL
);
echo $formatter->parse($formatter->format(strtotime('now')));
</code>```

It seems that the only way to get timestamp from this class is only use IntlDateFormatter::parse() method.

Timestamp

Timestamp is always measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) whatever functions or classes you use to get it. Example time(), mktime(), DateTime::getTimestamp().

Get timestamp from specific date/time.

In this example, assume that my server php.ini timezone is Asia/Bangkok and you get this date/time in Asia/Macau.

```<code>// server php.ini timezone is Asia/Bangkok
// set the date/time input.
// assume that it is Asia/Macau timezone.
$datetime = '2025-03-12 15:34:26';

$timestamp = strtotime($datetime);
echo $timestamp.'<br>';// 1741768466

// if you use function `date()`, the result will be wrong! because the timestamp is incorrectly parse using server timezone.
echo 'use date(): ' . date('Y-m-d H:i:s P', $timestamp) . '<br>';// 2025-03-12 15:34:26 +07:00 WRONG! incorrect timezone.

// even if you use `\IntlDateFormatter()` class, with or without set timezome the result still be wrong!
$formatter = new \IntlDateFormatter(
    'en',
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::FULL,
    new \DateTimeZone('Asia/Macau'),
    \IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd kk:mm:ss ZZZZZ'
);
echo $formatter->format($timestamp).'<br>';// 2025-03-12 16:34:26 +08:00 WRONG! time does not matched.
$formatter->setTimeZone(new \DateTimeZone('Asia/Macau'));
echo $formatter->format($timestamp).'<br>';// 2025-03-12 16:34:26 +08:00 WRONG! time does not matched.
</code>```

All the example above is wrong because the timestamp is parsed base on server timezone (php.ini).

Get time stamp in correct timezone.

As @Álvaro González commented, you can use strtotime('date/time timzone'); to get timstamp in certain timzone but you can also use \Datetime() or \IntlDateFormatter classes.

Example:

```<code>// server php.ini timezone is Asia/Bangkok
// set the date/time input.
// assume that it is Asia/Macau timezone.
$datetime = '2025-03-12 15:34:26';

$timestamp = strtotime($datetime . ' Asia/Macau');
echo $timestamp .'<br>';// 1741764866
echo 'use date(): ' . date('Y-m-d H:i:s P', $timestamp) . '<br>';// 2025-03-12 14:34:26 +07:00 CORRECT! but time zone is Bangkok as specified in php.ini (-1 hour for Macau to Bangkok).

$formatter = new \IntlDateFormatter(
    'en',
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::FULL,
    new \DateTimeZone('Asia/Macau'),
    \IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd kk:mm:ss ZZZZZ'
);
echo $formatter->format($timestamp).'<br>';// 2025-03-12 15:34:26 +08:00 CORRECT!

// use `DateTime()` class to get timestamp in certain timezone.
$date = new DateTime($datetime, new \DateTimeZone('Asia/Macau'));
$timestamp2 = (int) $date->getTimestamp();
echo $timestamp2.'<br>';// 1741764866

$formatter = new \IntlDateFormatter(
    'en',
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::FULL,
    new \DateTimeZone('Asia/Macau'),
    \IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd kk:mm:ss ZZZZZ'
);
echo $formatter->format($timestamp2) . '<br>';// 2025-03-12 15:34:26 +08:00 CORRECT!

// use `\IntlDateFormatter()` class to get timestamp in certain timezone.
$formatter = new IntlDateFormatter(
    'en-US',
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    new \DateTimeZone('Asia/Macau'),
    IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd kk:mm:ss'
);
$timestamp3 = (int) $formatter->parse($datetime);
echo $timestamp3 . '<br>';// 1741764866 CORRECT!
</code>```

To get timestamp from \IntlDateFormatter() class, you have to set the pattern in constructor matched the date/time source format.

Convert date/time across timezone

In this example I'll convert date/time result across timezone based on date/time that have got from Asia/Macau timezone.

I will use IntlDateFormatter() class to convert.

```<code>// server php.ini timezone is Asia/Bangkok
// set the date/time input.
// assume that it is date/time from Asia/Macau timezone.
$datetime = '2025-03-12 15:34:26';

$tsmacau = strtotime($datetime . ' Asia/Macau');// 1741764866

$formatter = new \IntlDateFormatter(
    'en',
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::FULL,
    new \DateTimeZone('Asia/Macau'),// timezone for input timestamp.
    \IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd kk:mm:ss ZZZZZ'
);
// convert to Asia/Bangkok timezone.
$formatter->setTimezone(new \DateTimeZone('Asia/Bangkok'));
echo $formatter->format($tsmacau).'<br>';// 2025-03-12 14:34:26 +07:00

// convert to Europe/Paris timezone
$formatter->setTimezone(new \DateTimeZone('Europe/Paris'));
echo $formatter->format($tsmacau).'<br>';// 2025-03-12 08:34:26 +01:00
</code>```

In this case you must know the timezone of timestamp because you have to set the input timezone into class constructor and change the timezone you want to convert into before call to format().

Body:
I'm trying to get the unix timestamp with IntlDateFormatter.

I've tried this

$formatter = new IntlDateFormatter(
        'fr_FR',
        IntlDateFormatter::FULL,
        IntlDateFormatter::FULL,
        'Europe/Paris',
        IntlDateFormatter::TRADITIONAL,
        'unix'
    );
echo $formatter->format(strtotime('now'));

Gave me 2022, while I'm trying to get it in this format 1644601950.

I've also tried to change unix with U AND u etc. but I can't find the right keyword for the unix timestamp in IntlDateFormatter class.

If I change the 'unix' to 'YY-MM-d' it would give me 22-02-11, but it's not in unix timestamp format.

Body:
Quick answer

To get unix timestamp with IntlDateFormatter class. Use this code.

$formatter = new IntlDateFormatter(
    'fr_FR',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'Europe/Paris',
    IntlDateFormatter::TRADITIONAL
);
echo $formatter->parse($formatter->format(strtotime('now')));

It seems that the only way to get timestamp from this class is only use IntlDateFormatter::parse() method.

Timestamp

Timestamp is always measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) whatever functions or classes you use to get it. Example time(), mktime(), DateTime::getTimestamp().

Get timestamp from specific date/time.

In this example, assume that my server php.ini timezone is Asia/Bangkok and you get this date/time in Asia/Macau.

// server php.ini timezone is Asia/Bangkok
// set the date/time input.
// assume that it is Asia/Macau timezone.
$datetime = '2025-03-12 15:34:26';

$timestamp = strtotime($datetime);
echo $timestamp.'<br>';// 1741768466

// if you use function `date()`, the result will be wrong! because the timestamp is incorrectly parse using server timezone.
echo 'use date(): ' . date('Y-m-d H:i:s P', $timestamp) . '<br>';// 2025-03-12 15:34:26 +07:00 WRONG! incorrect timezone.

// even if you use `\IntlDateFormatter()` class, with or without set timezome the result still be wrong!
$formatter = new \IntlDateFormatter(
    'en',
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::FULL,
    new \DateTimeZone('Asia/Macau'),
    \IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd kk:mm:ss ZZZZZ'
);
echo $formatter->format($timestamp).'<br>';// 2025-03-12 16:34:26 +08:00 WRONG! time does not matched.
$formatter->setTimeZone(new \DateTimeZone('Asia/Macau'));
echo $formatter->format($timestamp).'<br>';// 2025-03-12 16:34:26 +08:00 WRONG! time does not matched.

All the example above is wrong because the timestamp is parsed base on server timezone (php.ini).

Get time stamp in correct timezone.

As @Álvaro González commented, you can use strtotime('date/time timzone'); to get timstamp in certain timzone but you can also use \Datetime() or \IntlDateFormatter classes.

Example:

// server php.ini timezone is Asia/Bangkok
// set the date/time input.
// assume that it is Asia/Macau timezone.
$datetime = '2025-03-12 15:34:26';

$timestamp = strtotime($datetime . ' Asia/Macau');
echo $timestamp .'<br>';// 1741764866
echo 'use date(): ' . date('Y-m-d H:i:s P', $timestamp) . '<br>';// 2025-03-12 14:34:26 +07:00 CORRECT! but time zone is Bangkok as specified in php.ini (-1 hour for Macau to Bangkok).

$formatter = new \IntlDateFormatter(
    'en',
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::FULL,
    new \DateTimeZone('Asia/Macau'),
    \IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd kk:mm:ss ZZZZZ'
);
echo $formatter->format($timestamp).'<br>';// 2025-03-12 15:34:26 +08:00 CORRECT!

// use `DateTime()` class to get timestamp in certain timezone.
$date = new DateTime($datetime, new \DateTimeZone('Asia/Macau'));
$timestamp2 = (int) $date->getTimestamp();
echo $timestamp2.'<br>';// 1741764866

$formatter = new \IntlDateFormatter(
    'en',
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::FULL,
    new \DateTimeZone('Asia/Macau'),
    \IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd kk:mm:ss ZZZZZ'
);
echo $formatter->format($timestamp2) . '<br>';// 2025-03-12 15:34:26 +08:00 CORRECT!

// use `\IntlDateFormatter()` class to get timestamp in certain timezone.
$formatter = new IntlDateFormatter(
    'en-US',
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    new \DateTimeZone('Asia/Macau'),
    IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd kk:mm:ss'
);
$timestamp3 = (int) $formatter->parse($datetime);
echo $timestamp3 . '<br>';// 1741764866 CORRECT!

To get timestamp from \IntlDateFormatter() class, you have to set the pattern in constructor matched the date/time source format.

Convert date/time across timezone

In this example I'll convert date/time result across timezone based on date/time that have got from Asia/Macau timezone.

I will use IntlDateFormatter() class to convert.

// server php.ini timezone is Asia/Bangkok
// set the date/time input.
// assume that it is date/time from Asia/Macau timezone.
$datetime = '2025-03-12 15:34:26';

$tsmacau = strtotime($datetime . ' Asia/Macau');// 1741764866

$formatter = new \IntlDateFormatter(
    'en',
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::FULL,
    new \DateTimeZone('Asia/Macau'),// timezone for input timestamp.
    \IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd kk:mm:ss ZZZZZ'
);
// convert to Asia/Bangkok timezone.
$formatter->setTimezone(new \DateTimeZone('Asia/Bangkok'));
echo $formatter->format($tsmacau).'<br>';// 2025-03-12 14:34:26 +07:00

// convert to Europe/Paris timezone
$formatter->setTimezone(new \DateTimeZone('Europe/Paris'));
echo $formatter->format($tsmacau).'<br>';// 2025-03-12 08:34:26 +01:00

In this case you must know the timezone of timestamp because you have to set the input timezone into class constructor and change the timezone you want to convert into before call to format().


问:
how to divide huge blade file into small parts
I have a blade file that has over 4k sentences, it works well for sure but it is so difficult for me to edit the file and find what I am looking for, hence I am looking for a way to divide this huge file into small parts to make it easy to edit later or any solution for that.</p>

答:
resources/views/one.blade.php

one

```
<hr />
<p>resources/views/two.blade.php</p>
<pre class="lang-php prettyprint-override"><code><div>two</div>
</code>```

resources/views/all.blade.php

@include('one')
@include('two')
```

Body:
resources/views/one.blade.php

<div>one</div>

resources/views/two.blade.php

<div>two</div>

resources/views/all.blade.php

@include('one')
@include('two')


问:
Android API 24 < Crashes with java.lang.NoClassDefFoundError: com.google.common.base.CharMatcher
My app is crashing everytime it starts up with: java.lang.NoClassDefFoundError: com.google.common.base.CharMatcher. This only happens on devices running below android API 24. I have tried amending the Gradle versions and plugins as well as including the com.google.guava dependency but it did not work. Here is the full stack trace:

```<code>java.lang.NoClassDefFoundError: com.google.common.base.CharMatcher
    at com.google.common.base.Splitter.on(Splitter.java:127)
    at io.grpc.internal.GrpcUtil.<clinit>(GrpcUtil.java:197)
    at io.grpc.internal.AbstractManagedChannelImplBuilder.<clinit>(AbstractManagedChannelImplBuilder.java:90)
    at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget(OkHttpChannelProvider.java:46)
    at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget(OkHttpChannelProvider.java:26)
    at io.grpc.ManagedChannelBuilder.forTarget(ManagedChannelBuilder.java:76)
    at com.google.firebase.firestore.remote.GrpcCallProvider.initChannel(GrpcCallProvider.java:113)
    at com.google.firebase.firestore.remote.GrpcCallProvider.lambda$initChannelTask$6(GrpcCallProvider.java:256)
    at com.google.firebase.firestore.remote.GrpcCallProvider$$Lambda$5.call(GrpcCallProvider.java)
    at com.google.android.gms.tasks.zzy.run(com.google.android.gms:play-services-tasks@@17.1.0:2)
    at com.google.firebase.firestore.util.ThrottledForwardingExecutor.lambda$execute$0(ThrottledForwardingExecutor.java:54)
    at com.google.firebase.firestore.util.ThrottledForwardingExecutor$$Lambda$1.run(ThrottledForwardingExecutor.java)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)
</code>```

I also get this exception constantly along with the above one:

```<code>W/System.err: io.reactivex.exceptions.UndeliverableException: java.lang.NoClassDefFoundError: io.grpc.okhttp.OkHttpChannelBuilder
        at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:367)
        at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:69)
        at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
    Caused by: java.lang.NoClassDefFoundError: io.grpc.okhttp.OkHttpChannelBuilder
</code>```

My project level gradle file looks like this:

```<code>buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.google.gms:google-services:4.3.3'
    classpath 'com.android.tools.build:gradle:4.0.2'
    classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0"
    classpath 'com.google.firebase:firebase-crashlytics-gradle:2.1.1'
    classpath 'com.google.firebase:perf-plugin:1.3.1'  // Performance Monitoring plugin
}
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}
</code>```

This is my app level gradle file:

```<code>plugins {
    id("com.github.triplet.play") version "2.8.0"
}

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "..."
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 48
        versionName "4.0.4"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    signingConfigs {
        release {
            ...
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled false
            shrinkResources false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                    'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    flavorDimensions "version"
    productFlavors{
        spanish{
            dimension "version"
            applicationId "..."
            buildConfigField 'String', 'PRIMARY_COLOR', '"#ffc400"'
            buildConfigField 'String', 'ACCENT_COLOR', '"#C60B1E"'
            buildConfigField 'String', 'LANG_CODE', '"es"'
        }
        italian{
            dimension "version"
            applicationId "..."
            buildConfigField 'String', 'PRIMARY_COLOR', '"#008C45"'
            buildConfigField 'String', 'ACCENT_COLOR', '"#CD212A"'
            buildConfigField 'String', 'LANG_CODE', '"it"'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
    }
}

play {
    ...
}

dependencies {
    //debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-beta-5'
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.firebase:firebase-core:17.4.4'
    implementation 'com.google.firebase:firebase-firestore:21.7.1'
    implementation 'com.google.firebase:firebase-crashlytics:17.1.1'
    implementation 'br.com.simplepass:loading-button-android:2.2.0'
    implementation 'com.google.firebase:firebase-perf:19.0.8'
    implementation 'com.google.firebase:firebase-analytics:17.4.4'
    implementation 'com.google.firebase:firebase-functions:19.0.2'
    implementation 'com.google.android.play:core:1.8.0'
    implementation 'com.google.firebase:firebase-config:19.2.0'
    implementation 'com.github.triplet.gradle:play-publisher:2.8.0'
    implementation 'com.google.guava:guava:29.0-android'
}
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'com.google.firebase.firebase-perf'
</code>```

答:
If you replace

```<code>implementation 'com.google.guava:guava:29.0-android'
</code>```

for this

```<code>implementation ('com.google.guava:guava') {
    version {
        strictly '29.0-android'
    }
}
</code>```

it should work.

Body:
My app is crashing everytime it starts up with: java.lang.NoClassDefFoundError: com.google.common.base.CharMatcher. This only happens on devices running below android API 24. I have tried amending the Gradle versions and plugins as well as including the com.google.guava dependency but it did not work. Here is the full stack trace:

java.lang.NoClassDefFoundError: com.google.common.base.CharMatcher
    at com.google.common.base.Splitter.on(Splitter.java:127)
    at io.grpc.internal.GrpcUtil.<clinit>(GrpcUtil.java:197)
    at io.grpc.internal.AbstractManagedChannelImplBuilder.<clinit>(AbstractManagedChannelImplBuilder.java:90)
    at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget(OkHttpChannelProvider.java:46)
    at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget(OkHttpChannelProvider.java:26)
    at io.grpc.ManagedChannelBuilder.forTarget(ManagedChannelBuilder.java:76)
    at com.google.firebase.firestore.remote.GrpcCallProvider.initChannel(GrpcCallProvider.java:113)
    at com.google.firebase.firestore.remote.GrpcCallProvider.lambda$initChannelTask$6(GrpcCallProvider.java:256)
    at com.google.firebase.firestore.remote.GrpcCallProvider$$Lambda$5.call(GrpcCallProvider.java)
    at com.google.android.gms.tasks.zzy.run(com.google.android.gms:play-services-tasks@@17.1.0:2)
    at com.google.firebase.firestore.util.ThrottledForwardingExecutor.lambda$execute$0(ThrottledForwardingExecutor.java:54)
    at com.google.firebase.firestore.util.ThrottledForwardingExecutor$$Lambda$1.run(ThrottledForwardingExecutor.java)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)

I also get this exception constantly along with the above one:

W/System.err: io.reactivex.exceptions.UndeliverableException: java.lang.NoClassDefFoundError: io.grpc.okhttp.OkHttpChannelBuilder
        at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:367)
        at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:69)
        at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
    Caused by: java.lang.NoClassDefFoundError: io.grpc.okhttp.OkHttpChannelBuilder

My project level gradle file looks like this:

buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.google.gms:google-services:4.3.3'
    classpath 'com.android.tools.build:gradle:4.0.2'
    classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0"
    classpath 'com.google.firebase:firebase-crashlytics-gradle:2.1.1'
    classpath 'com.google.firebase:perf-plugin:1.3.1'  // Performance Monitoring plugin
}
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

This is my app level gradle file:

plugins {
    id("com.github.triplet.play") version "2.8.0"
}

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "..."
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 48
        versionName "4.0.4"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    signingConfigs {
        release {
            ...
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled false
            shrinkResources false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                    'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    flavorDimensions "version"
    productFlavors{
        spanish{
            dimension "version"
            applicationId "..."
            buildConfigField 'String', 'PRIMARY_COLOR', '"#ffc400"'
            buildConfigField 'String', 'ACCENT_COLOR', '"#C60B1E"'
            buildConfigField 'String', 'LANG_CODE', '"es"'
        }
        italian{
            dimension "version"
            applicationId "..."
            buildConfigField 'String', 'PRIMARY_COLOR', '"#008C45"'
            buildConfigField 'String', 'ACCENT_COLOR', '"#CD212A"'
            buildConfigField 'String', 'LANG_CODE', '"it"'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
    }
}

play {
    ...
}

dependencies {
    //debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-beta-5'
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.firebase:firebase-core:17.4.4'
    implementation 'com.google.firebase:firebase-firestore:21.7.1'
    implementation 'com.google.firebase:firebase-crashlytics:17.1.1'
    implementation 'br.com.simplepass:loading-button-android:2.2.0'
    implementation 'com.google.firebase:firebase-perf:19.0.8'
    implementation 'com.google.firebase:firebase-analytics:17.4.4'
    implementation 'com.google.firebase:firebase-functions:19.0.2'
    implementation 'com.google.android.play:core:1.8.0'
    implementation 'com.google.firebase:firebase-config:19.2.0'
    implementation 'com.github.triplet.gradle:play-publisher:2.8.0'
    implementation 'com.google.guava:guava:29.0-android'
}
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'com.google.firebase.firebase-perf'

Body:
If you replace

implementation 'com.google.guava:guava:29.0-android'

for this

implementation ('com.google.guava:guava') {
    version {
        strictly '29.0-android'
    }
}

it should work.


问:
Cordova plugin development - adding aar
I am new to the cordova plugin development stuff.
I want to write a plugin which is able to open a new android activty and showing some advertisement.

So I followed a simple tutorial here. That works very well and as expected.

Next step is to include this Android Studio Gradle project to my plugin.

My first try: Adding the gradle project to a subfolder of my cordova plugin and adding the following line to the plugin.xml file:

```<code><framework src="libs/Broper/build.gradle" custom="true" type="gradleReference" />
</code>```

also I tried:

```<code><framework src="libs/Broper/app/build.gradle" custom="true" type="gradleReference" />
</code>```

doesn't work. So I can't import the classes of that android studio project to my plugin java files.

Then a better solution (I thought so) is to add an AAR instead. But there I don't even have a clue what to do to add that AAR in my cordova plugin.

So, the question is: How do I add an android studio project (or library) to my cordova plugin the right way?

答:
Okay, because there are multiple answers here and none of them fully capture everything that needs to be done, I'm going to create an all inclusive answer. Hopefully it will save people some time and frustration.

It's pretty straight forward, you just have to update plugin.xml to state where the .aar file should go inside the android project. Then you have to tell gradle where to look for it.

So I have this directory structure (you can use a different one):

```<code>-- my-plugin/
   |-- deps/
       |-- some-dependency.aar
   |-- src/
       |-- MyPlugin.java
   |-- www/
       |-- plugin.js
   |-- package.json
   |-- plugin-settings.gradle
   |-- plugin.xml
</code>```

Step 1

The first step is to tell cordova where to put the .aar file. You do that by including a line in plugin.xml:

```<code><resource-file src="deps/some-dependency.aar" target="libs/some-dependency.aar" />
</code>```

That will grab the file from the deps folder in your source and stick it into the the platforms/android/app/src/main/libs/ folder in the resulting android project. Apparently the target path is relative to the platforms/android/app/src/main folder. Not sure if that can be changed.

Before moving on to step 2, it might be a good idea to run cordova build android to verify that the .aar file is being copied to the right place.

Step 2

So once that's working the next step is to tell gradle where the file is so it can resolve it correctly during the build. You do that by creating your own .gradle file that will be merged with the main gradle file that cordova creates for you.

Create a file called plugin-settings.gradle and put the following line in it:

```<code>repositories{
  flatDir {
      dirs 'src/main/libs'
   }
}

dependencies {
   compile(name:'some-dependency', ext:'aar')
}
</code>```

Note that the line dirs 'src/main/libs' tells gradle where to look for the .aar file. It does not dictate where cordova puts that file, just where gradle looks for it. Also note that the path is relative to the platforms/android/app/ folder and that the resulting path must match where cordova is putting the .aar file.

So in my plugin.xml file I have target="libs/some-dependency.aar" therefore in my plugin-settings.gradle file I have dirs 'src/main/libs'. If these don't line up you're going to get build errors.

Step 3

Now tell your plugin to use the .gradle file:

```<code><framework src="plugin-settings.gradle" custom="true" type="gradleReference" />
</code>```

Note that you can put the pllugin-settings.gradle file where ever you want and you can call it whatever you want. Just make sure the <framework> entry matches.

Yay

That's pretty much it. You should be able to build and run your app at this point. You're welcome.

Title: Cordova plugin development - adding aar

Body:
I am new to the cordova plugin development stuff.
I want to write a plugin which is able to open a new android activty and showing some advertisement.

So I followed a simple tutorial here. That works very well and as expected.

Next step is to include this Android Studio Gradle project to my plugin.

My first try: Adding the gradle project to a subfolder of my cordova plugin and adding the following line to the plugin.xml file:

<framework src="libs/Broper/build.gradle" custom="true" type="gradleReference" />

also I tried:

<framework src="libs/Broper/app/build.gradle" custom="true" type="gradleReference" />

doesn't work. So I can't import the classes of that android studio project to my plugin java files.

Then a better solution (I thought so) is to add an AAR instead. But there I don't even have a clue what to do to add that AAR in my cordova plugin.

So, the question is: How do I add an android studio project (or library) to my cordova plugin the right way?

Body:
Okay, because there are multiple answers here and none of them fully capture everything that needs to be done, I'm going to create an all inclusive answer. Hopefully it will save people some time and frustration.

It's pretty straight forward, you just have to update plugin.xml to state where the .aar file should go inside the android project. Then you have to tell gradle where to look for it.

So I have this directory structure (you can use a different one):

-- my-plugin/
   |-- deps/
       |-- some-dependency.aar
   |-- src/
       |-- MyPlugin.java
   |-- www/
       |-- plugin.js
   |-- package.json
   |-- plugin-settings.gradle
   |-- plugin.xml

Step 1

The first step is to tell cordova where to put the .aar file. You do that by including a line in plugin.xml:

<resource-file src="deps/some-dependency.aar" target="libs/some-dependency.aar" />

That will grab the file from the deps folder in your source and stick it into the the platforms/android/app/src/main/libs/ folder in the resulting android project. Apparently the target path is relative to the platforms/android/app/src/main folder. Not sure if that can be changed.

Before moving on to step 2, it might be a good idea to run cordova build android to verify that the .aar file is being copied to the right place.

Step 2

So once that's working the next step is to tell gradle where the file is so it can resolve it correctly during the build. You do that by creating your own .gradle file that will be merged with the main gradle file that cordova creates for you.

Create a file called plugin-settings.gradle and put the following line in it:

repositories{
  flatDir {
      dirs 'src/main/libs'
   }
}

dependencies {
   compile(name:'some-dependency', ext:'aar')
}

Note that the line dirs 'src/main/libs' tells gradle where to look for the .aar file. It does not dictate where cordova puts that file, just where gradle looks for it. Also note that the path is relative to the platforms/android/app/ folder and that the resulting path must match where cordova is putting the .aar file.

So in my plugin.xml file I have target="libs/some-dependency.aar" therefore in my plugin-settings.gradle file I have dirs 'src/main/libs'. If these don't line up you're going to get build errors.

Step 3

Now tell your plugin to use the .gradle file:

<framework src="plugin-settings.gradle" custom="true" type="gradleReference" />

Note that you can put the pllugin-settings.gradle file where ever you want and you can call it whatever you want. Just make sure the <framework> entry matches.

Yay

That's pretty much it. You should be able to build and run your app at this point. You're welcome.


问:
android editText
I'm looking for the easiest way (ie without rewritting a keyboard, if possible - maybe using an existing one out there?) to create an editText to input a digit password.

It's not that uncommon, yet I found no flag combination to do that.

Since it's digit only characters, I either want a digit only keyboard (ideally like on the iphone, 4*3=12 keys, 0-10+del+ok), or at least a phone-like keyboard, with ()+* and characters like that, but so that they can't be written in the textEdit.

I don't mind using deprecated flags.

In particular, number|textPassword for inputType doesn't work (characters not hidden), android:password="true" android:inputType="phone" and android:numeric="integer" android:password="true" produce the same result, but the hint text disappears and special characters are still allowed.

Thanks.

答:
I'm afraid that there might be no easy way to achieve that. android:password="true" only hides the input text and inputType="phone" still allow some special character for dialing although you can make those character do nothing by handling KeyEvent.

I was required to do the same thing once, and eventually implemented a custom layout that only rises when the EditText gets focused. If you can't find better solution and you don't have too many EditText of this type, maybe it is the way to go

Title: android editText


问:
How to place and center text in an SVG rectangle
I have the following rectangle:

```<code><rect x="0px" y="0px" width="60px" height="20px"/>
</code>```

I would like to center the word "Fiction" inside of it. For other rectangles, does SVG word wrap to stay within them? I can't seem to find anything specifically about inserting text within shapes that are centered both horizontally and vertically and word wrap. Also, the text can not leave the rectangle.

Looking at the https://www.w3.org/TR/SVG/text.html#TextElement example doesn't help since the text element's x and y are different from the rectangle's x and y. There doesn't seem to be width and height for text elements. I am not sure of the math here.

(My HTML table is just not going to work.)

答:
11 years too late for the party... use pathLength

x="50%" y ="50%" won't work in complex SVGs

No one mentioning pathLength

make it pathLength="2" here in a path id="#P"

then use the path as guide in the textPath href="#P":

so startoffset="1" is the middle of the blue path

and text-anchor="middle" aligns the text

(hide the blue line with stroke="transparent")

(or not use pathLength and set startoffset="50%")

<svg viewbox="0 0 200 50" style="background:pink">
  <rect x="10" y="10" width="180" height="30" stroke="green" fill="none"/>
  <path id="P" pathLength="2" d="M10 25h180" stroke="blue"/>
  <text>
    <textPath href="#P"
              startoffset="1" text-anchor="middle" dominant-baseline="middle"
              fill="black" font-size="14px">aligned in middle</textPath>
  </text>
</svg>```

Body:
I have the following rectangle:

<rect x="0px" y="0px" width="60px" height="20px"/>

I would like to center the word "Fiction" inside of it. For other rectangles, does SVG word wrap to stay within them? I can't seem to find anything specifically about inserting text within shapes that are centered both horizontally and vertically and word wrap. Also, the text can not leave the rectangle.

Looking at the https://www.w3.org/TR/SVG/text.html#TextElement example doesn't help since the text element's x and y are different from the rectangle's x and y. There doesn't seem to be width and height for text elements. I am not sure of the math here.

(My HTML table is just not going to work.)


问:
Need help in pandas date time
So I need help in converting the date in a pandas Dataframe which is in the format 20200125 and change it to 2020-01-25.

when executing with the code -

```<code>df['document_create_date']=pd.to_datetime(df['document_create_date'],format='%Y-%m-%d')
</code>```

The output I get is in the format -> 1970-01-01 00:00:00.020200125

答:
Update
Maybe you have to convert your column from int to string before:

```<code># Setup
df = pd.DataFrame({'document_create_date': [20200125]})

df['document_create_date']=pd.to_datetime(df['document_create_date'].astype(str))
</code>```

You have not the right format. You have to specify the source format not the target format:

```<code>df['document_create_date']=pd.to_datetime(df['document_create_date'],format='%Y%m%d')
</code>```

Output:

```<code>>>> df
  document_create_date
0           2020-01-25
</code>```

Or let pandas determine the right format:

```<code>df['document_create_date']=pd.to_datetime(df['document_create_date'])
</code>```

Title: Need help in pandas date time

Body:
So I need help in converting the date in a pandas Dataframe which is in the format 20200125 and change it to 2020-01-25.

when executing with the code -

df['document_create_date']=pd.to_datetime(df['document_create_date'],format='%Y-%m-%d')

The output I get is in the format -> 1970-01-01 00:00:00.020200125

Body:
Update
Maybe you have to convert your column from int to string before:

# Setup
df = pd.DataFrame({'document_create_date': [20200125]})

df['document_create_date']=pd.to_datetime(df['document_create_date'].astype(str))

You have not the right format. You have to specify the source format not the target format:

df['document_create_date']=pd.to_datetime(df['document_create_date'],format='%Y%m%d')

Output:

>>> df
  document_create_date
0           2020-01-25

Or let pandas determine the right format:

df['document_create_date']=pd.to_datetime(df['document_create_date'])


问:
A final answer on how to get Exif data from URI
This topic has been discussed in lots of questions here, with mostly different results and, due to API changes and different types of URIs, no definitive answer.

I don’t have an answer myself, but let’s talk about it.
The ExifInterface has a single constructor that accepts a filePath. That itself is annoying, as it is discouraged now to rely on paths - you should rather use Uris and ContentResolver. OK.

Our Uri named uri can be retrieved from the intent in onActivityResult (if you pick the picture from gallery with ACTION_GET_CONTENT) or can be an Uri that we previously had (if you pick the picture from camera and call intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)).

API<19

Our uri can have two different schemas:

Uris coming from cameras will mostly have a file:// schema. Those are pretty easy to treat, because they hold the path. You can call new ExifInterface(uri.getPath()) and you are done.

Uris coming from gallery or other content providers usually have a content:// interface. I personally don’t know what that is about, but is driving me mad.

This second case, as far as I understand, should be treated with a ContentResolver that you can get with Context.getContentResolver(). The following works with all apps I have tested, in any case:

```<code>public static ExifInterface getPictureData(Context context, Uri uri) {
    String[] uriParts = uri.toString().split(":");
    String path = null;

    if (uriParts[0].equals("content")) {
        // we can use ContentResolver.
        // let’s query the DATA column which holds the path
        String col = MediaStore.Images.ImageColumns.DATA;
        Cursor c = context.getContentResolver().query(uri,
                new String[]{col},
                null, null, null);

        if (c != null && c.moveToFirst()) {
            path = c.getString(c.getColumnIndex(col));
            c.close();
            return new ExifInterface(path);
        }

    } else if (uriParts[0].equals("file")) {
        // it's easy to get the path
        path = uri.getEncodedPath();
        return new ExifInterface(path);
    }
    return null;
}
</code>```

API19+

My issues arise from Kitkat onward with content:// URIs. Kitkat introduces the Storage Access Framework (see here) along with a new intent, ACTION_OPEN_DOCUMENT, and a platform picker. However, it is said that

On Android 4.4 and higher, you have the additional option of using the
  ACTION_OPEN_DOCUMENT intent, which displays a picker UI controlled by
  the system that allows the user to browse all files that other apps
  have made available. From this single UI, the user can pick a file
  from any of the supported apps.

ACTION_OPEN_DOCUMENT is not intended to be a replacement for
  ACTION_GET_CONTENT. The one you should use depends on the needs of
  your app.

So to keeps this very simple, let’s say that we are ok with the old ACTION_GET_CONTENT: it will fire a chooser dialog where you can choose a gallery app.

However, the content approach doesn’t work anymore. Sometimes it works on Kitkat, but never works on Lollipop, for example. I don’t know what exactly has changed.

I have searched and tried a lot; another approach taken for Kitkat specifically is:

```<code>String wholeId = DocumentsContract.getDocumentId(uri);
String[] parts = wholeId.split(“:”);
String numberId = parts[1];

Cursor c = context.getContentResolver().query(
    // why external and not internal ?
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
    new String[]{ col },
    MediaStore.Images.Media._ID + “=?”,
    new String[]{ numberId },
    null);
</code>```

This works sometimes, but others not. Specifically, it works when wholeId is something like image:2839, but obviously breaks when wholeId is simply a number.

You can try this using the system picker (i.e. firing the gallery with ACTION_OPEN_DOCUMENT): if you choose an image from “Recents”, it works; if you choose an image from “Downloads”, it breaks.

So how to?!

The immediate answer is You don’t, you don’t find file paths from content uris in newer version of the OS. It could be said that not all content uris point to pictures or even files.

That’s totally OK for me, and at first I worked to avoid this. But then, How are we supposed to use the ExifInterface class if we should not use paths?

I don’t understand how modern apps do this - finding orientation and metadata is an issue you immediately face, and ContentResolver does not offer any API in that sense. You have ContentResolver.openFileDescriptor() and similar stuff, but no APIs to read metadata (which truly is in that file). There might be external libraries that read Exif stuff from a stream, but I’m wondering about the common/platform way to solve this.

I have searched for similar code in google’s open source apps, but found nothing.

答:
In my case I have issues with getting orientation with InputStream. So instead of getting ExifInterface from InputStream I used FileDescriptor.

This solution was not working:

```<code>val inputStream = contentResolver.openInputStream(uri)
val bitmap: Bitmap? = BitmapFactory.decodeStream(inputStream)
val exifInterface = inputStream?.let { ExifInterface(inputStream) }
inputStream?.close()
</code>```

I had better results when I opened separate InputStream for ExifInterface (but I did not like it that way):

```<code>val inputStream = contentResolver.openInputStream(uri)
val bitmap: Bitmap? = BitmapFactory.decodeStream(inputStream)
inputStream?.close()

val inputStream2 = contentResolver.openInputStream(uri)
val fileDescriptor = contentResolver.openFileDescriptor(uri, "r")?.fileDescriptor
val exifInterface = inputStream2?.let { ExifInterface(inputStream2) }
inputStream2?.close()
</code>```

But I ended up with this method using FileDescriptor for construction of ExifInterface:

```<code>fun Context.getImageFromGallery(uri: Uri): Bitmap? {
    return try {
        val inputStream = contentResolver.openInputStream(uri)
        val bitmap: Bitmap? = BitmapFactory.decodeStream(inputStream)
        inputStream?.close()

        val fileDescriptor = contentResolver.openFileDescriptor(uri, "r")?.fileDescriptor
        val exifInterface = fileDescriptor?.let { ExifInterface(fileDescriptor) }

        return when (exifInterface?.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)) {
            ExifInterface.ORIENTATION_ROTATE_90 -> TransformationUtils.rotateImage(bitmap!!, 90)
            ExifInterface.ORIENTATION_ROTATE_180 -> TransformationUtils.rotateImage(bitmap!!, 180)
            ExifInterface.ORIENTATION_ROTATE_270 -> TransformationUtils.rotateImage(bitmap!!, 270)
            ExifInterface.ORIENTATION_NORMAL -> bitmap
            else -> bitmap
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        null
    }
}
</code>```

Body:
This topic has been discussed in lots of questions here, with mostly different results and, due to API changes and different types of URIs, no definitive answer.

I don’t have an answer myself, but let’s talk about it.
The ExifInterface has a single constructor that accepts a filePath. That itself is annoying, as it is discouraged now to rely on paths - you should rather use Uris and ContentResolver. OK.

Our Uri named uri can be retrieved from the intent in onActivityResult (if you pick the picture from gallery with ACTION_GET_CONTENT) or can be an Uri that we previously had (if you pick the picture from camera and call intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)).

API<19

Our uri can have two different schemas:

Uris coming from cameras will mostly have a file:// schema. Those are pretty easy to treat, because they hold the path. You can call new ExifInterface(uri.getPath()) and you are done.

Uris coming from gallery or other content providers usually have a content:// interface. I personally don’t know what that is about, but is driving me mad.

This second case, as far as I understand, should be treated with a ContentResolver that you can get with Context.getContentResolver(). The following works with all apps I have tested, in any case:

public static ExifInterface getPictureData(Context context, Uri uri) {
    String[] uriParts = uri.toString().split(":");
    String path = null;

    if (uriParts[0].equals("content")) {
        // we can use ContentResolver.
        // let’s query the DATA column which holds the path
        String col = MediaStore.Images.ImageColumns.DATA;
        Cursor c = context.getContentResolver().query(uri,
                new String[]{col},
                null, null, null);

        if (c != null && c.moveToFirst()) {
            path = c.getString(c.getColumnIndex(col));
            c.close();
            return new ExifInterface(path);
        }

    } else if (uriParts[0].equals("file")) {
        // it's easy to get the path
        path = uri.getEncodedPath();
        return new ExifInterface(path);
    }
    return null;
}

API19+

My issues arise from Kitkat onward with content:// URIs. Kitkat introduces the Storage Access Framework (see here) along with a new intent, ACTION_OPEN_DOCUMENT, and a platform picker. However, it is said that

On Android 4.4 and higher, you have the additional option of using the
  ACTION_OPEN_DOCUMENT intent, which displays a picker UI controlled by
  the system that allows the user to browse all files that other apps
  have made available. From this single UI, the user can pick a file
  from any of the supported apps.

ACTION_OPEN_DOCUMENT is not intended to be a replacement for
  ACTION_GET_CONTENT. The one you should use depends on the needs of
  your app.

So to keeps this very simple, let’s say that we are ok with the old ACTION_GET_CONTENT: it will fire a chooser dialog where you can choose a gallery app.

However, the content approach doesn’t work anymore. Sometimes it works on Kitkat, but never works on Lollipop, for example. I don’t know what exactly has changed.

I have searched and tried a lot; another approach taken for Kitkat specifically is:

String wholeId = DocumentsContract.getDocumentId(uri);
String[] parts = wholeId.split(“:”);
String numberId = parts[1];

Cursor c = context.getContentResolver().query(
    // why external and not internal ?
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
    new String[]{ col },
    MediaStore.Images.Media._ID + “=?”,
    new String[]{ numberId },
    null);

This works sometimes, but others not. Specifically, it works when wholeId is something like image:2839, but obviously breaks when wholeId is simply a number.

You can try this using the system picker (i.e. firing the gallery with ACTION_OPEN_DOCUMENT): if you choose an image from “Recents”, it works; if you choose an image from “Downloads”, it breaks.

So how to?!

The immediate answer is You don’t, you don’t find file paths from content uris in newer version of the OS. It could be said that not all content uris point to pictures or even files.

That’s totally OK for me, and at first I worked to avoid this. But then, How are we supposed to use the ExifInterface class if we should not use paths?

I don’t understand how modern apps do this - finding orientation and metadata is an issue you immediately face, and ContentResolver does not offer any API in that sense. You have ContentResolver.openFileDescriptor() and similar stuff, but no APIs to read metadata (which truly is in that file). There might be external libraries that read Exif stuff from a stream, but I’m wondering about the common/platform way to solve this.

I have searched for similar code in google’s open source apps, but found nothing.

Body:
In my case I have issues with getting orientation with InputStream. So instead of getting ExifInterface from InputStream I used FileDescriptor.

This solution was not working:

val inputStream = contentResolver.openInputStream(uri)
val bitmap: Bitmap? = BitmapFactory.decodeStream(inputStream)
val exifInterface = inputStream?.let { ExifInterface(inputStream) }
inputStream?.close()

I had better results when I opened separate InputStream for ExifInterface (but I did not like it that way):

val inputStream = contentResolver.openInputStream(uri)
val bitmap: Bitmap? = BitmapFactory.decodeStream(inputStream)
inputStream?.close()

val inputStream2 = contentResolver.openInputStream(uri)
val fileDescriptor = contentResolver.openFileDescriptor(uri, "r")?.fileDescriptor
val exifInterface = inputStream2?.let { ExifInterface(inputStream2) }
inputStream2?.close()

But I ended up with this method using FileDescriptor for construction of ExifInterface:

fun Context.getImageFromGallery(uri: Uri): Bitmap? {
    return try {
        val inputStream = contentResolver.openInputStream(uri)
        val bitmap: Bitmap? = BitmapFactory.decodeStream(inputStream)
        inputStream?.close()

        val fileDescriptor = contentResolver.openFileDescriptor(uri, "r")?.fileDescriptor
        val exifInterface = fileDescriptor?.let { ExifInterface(fileDescriptor) }

        return when (exifInterface?.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)) {
            ExifInterface.ORIENTATION_ROTATE_90 -> TransformationUtils.rotateImage(bitmap!!, 90)
            ExifInterface.ORIENTATION_ROTATE_180 -> TransformationUtils.rotateImage(bitmap!!, 180)
            ExifInterface.ORIENTATION_ROTATE_270 -> TransformationUtils.rotateImage(bitmap!!, 270)
            ExifInterface.ORIENTATION_NORMAL -> bitmap
            else -> bitmap
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        null
    }
}


问:
what is the use of room in the in the render section?
***python Django framework
I can't understand what is the use of {'rooms':rooms}) in the render section please help i am just learning django

```<code>import imp
from django.shortcuts import render
from django.http import HttpResponse

rooms =[
    {'id':1, 'name':'learn python'},
    {'id':2, 'name':'learn html and javascript'},
    {'id':3, 'name':'at last learn django'},
]

# Create your views here.
def home(request):
    return render(request,'home.html',
                  **{'rooms':rooms})**

def room(request):
    return render(request,
                    'room.html')
</code>```

答:
{'rooms':rooms} is a dictionary with key/value pair.

You send this key/value pair to home.html with this statement

```<code>return render(request,'home.html',
                  {'rooms':rooms})
</code>```

Now inside home.html, you can access this dictionary with just the key rooms. For example,

home.html

```<code><html>
  <head>
  </head>
  <body>
    {{ rooms }}
  </body>
</html>
</code>```

It is not required that the key and value should be the same name. Instead of {'rooms':rooms}, you can also use {'number_of_rooms':rooms}. But then you have to access the value inside home.html using the key number_of_rooms

home.html

```<code><html>
  <head>
  </head>
  <body>
    {{ number_of_rooms }}
  </body>
</html>
</code>```

Body:
***python Django framework
I can't understand what is the use of {'rooms':rooms}) in the render section please help i am just learning django

import imp
from django.shortcuts import render
from django.http import HttpResponse

rooms =[
    {'id':1, 'name':'learn python'},
    {'id':2, 'name':'learn html and javascript'},
    {'id':3, 'name':'at last learn django'},
]

# Create your views here.
def home(request):
    return render(request,'home.html',
                  **{'rooms':rooms})**

def room(request):
    return render(request,
                    'room.html')

Body:
{'rooms':rooms} is a dictionary with key/value pair.

You send this key/value pair to home.html with this statement

return render(request,'home.html',
                  {'rooms':rooms})

Now inside home.html, you can access this dictionary with just the key rooms. For example,

home.html

<html>
  <head>
  </head>
  <body>
    {{ rooms }}
  </body>
</html>

It is not required that the key and value should be the same name. Instead of {'rooms':rooms}, you can also use {'number_of_rooms':rooms}. But then you have to access the value inside home.html using the key number_of_rooms

home.html

<html>
  <head>
  </head>
  <body>
    {{ number_of_rooms }}
  </body>
</html>


问:
How to merge/zip generic lists of differing types (and cast the result to a dictionary)?
i need to read data from some excel sheets. The data in the excel sheets is already formatted in such a way that i am able to get the desired data by using this method.

This is what i am doing:

```<code>using (var conn = new OleDbConnection(strBld.ToString()))
{
    conn.Open();

    IEnumerable<IDictionary<string, object>> excelDataRaw =
        conn.Query("select * from [Curves$A:IT]").
        Cast<IDictionary<string, object>>();

    int i = 0;
    string previousKey = null;
    var curve = new List<IEnumerable<object>>();
    var excelData = new Dictionary<string, IDictionary<object, object>>();
    //var excelData = new Dictionary<string, IDictionary<string, decimal>>();

    foreach (var key in excelDataRaw.Select(dictionary => dictionary.Keys).
        ElementAt(i))
    {
        string key1 = key;
        // gets the data from one column within the excel file
        curve.Add(excelDataRaw.Select(col => col[key1]).
            Where(row => row != null).ToList());

        if (i % 2 == 0)
        {
            // store the column header
            previousKey = key;
        }

        if (i % 2 == 1)
        {
            // merge the data from the first column (keys)
            // with the data from the second column (values)
            IEnumerable<object> keys = curve[i - 1];
            IEnumerable<object> values = curve[i];
            // cast works but than you can't zip the lists together
            //IEnumerable<string> keys = curve[i - 1].Cast<string>();
            //IEnumerable<decimal> values = curve[i].Cast<decimal>();

            // zip them together on their index
            var dic = keys.Zip(values, (k, v) => new { k, v }).
                ToDictionary(x => x.k, x => x.v);

            if (previousKey != null)
            {
                if (!excelData.ContainsKey(previousKey))
                {
                    excelData.Add(previousKey, dic);
                }
            }
        }

        ++i;
    }
}
</code>```

I extract all data from the excel file (excelDataRaw). i then select all data that belongs together into a list (curve) and combine two lists that belong to each other into a dictionary (dic). The final result is a dictionary (excelData) that contains the column head from the excel file as a key (previousKey) and the data relevant to this column head as a dictionary (dic).

I would like to cast the dictionary (excelData) from

```<code>Dictionary<string, IDictionary<object, object>>
</code>```

into

```<code>Dictionary<string, IDictionary<string, decimal>>
</code>```

but i can't cast object into string or decimal and i can't zip the lists together to get the dictionary (dic) after casting each list to the desired type. Has anyone an idea how to achieve the desired result(type)?

答:
ExcelDataRaw is of type Dictionary<string, IDictionary<object, object>> so it needs IDictionary<object, object> as the value. You can't cast Dictionary<string,decimal> into IDictionary<object,object> because IDictionary is not a covariant interface - see http://msdn.microsoft.com/en-us/library/dd469487.aspx.

The solution is either to change the type of ExcelDataRaw to Dictionary<string, IDictionary<string, decimal>> or to keep it as is and when trying to use the values from that dictionary cast those to correct types:

```<code>foreach(var kv in ExcelDataRaw)
{
   Dictionary<string,decimal> convertedValue=kv.Value.ToDictionary(x=>(string)x.Key,x=>(decimal)x.Value);
   // or convert it even further down the road
   string lookup = "abc";
   decimal v = (decimal)kv.Value[lookup];
}
</code>```

Body:
i need to read data from some excel sheets. The data in the excel sheets is already formatted in such a way that i am able to get the desired data by using this method.

This is what i am doing:

using (var conn = new OleDbConnection(strBld.ToString()))
{
    conn.Open();

    IEnumerable<IDictionary<string, object>> excelDataRaw =
        conn.Query("select * from [Curves$A:IT]").
        Cast<IDictionary<string, object>>();

    int i = 0;
    string previousKey = null;
    var curve = new List<IEnumerable<object>>();
    var excelData = new Dictionary<string, IDictionary<object, object>>();
    //var excelData = new Dictionary<string, IDictionary<string, decimal>>();

    foreach (var key in excelDataRaw.Select(dictionary => dictionary.Keys).
        ElementAt(i))
    {
        string key1 = key;
        // gets the data from one column within the excel file
        curve.Add(excelDataRaw.Select(col => col[key1]).
            Where(row => row != null).ToList());

        if (i % 2 == 0)
        {
            // store the column header
            previousKey = key;
        }

        if (i % 2 == 1)
        {
            // merge the data from the first column (keys)
            // with the data from the second column (values)
            IEnumerable<object> keys = curve[i - 1];
            IEnumerable<object> values = curve[i];
            // cast works but than you can't zip the lists together
            //IEnumerable<string> keys = curve[i - 1].Cast<string>();
            //IEnumerable<decimal> values = curve[i].Cast<decimal>();

            // zip them together on their index
            var dic = keys.Zip(values, (k, v) => new { k, v }).
                ToDictionary(x => x.k, x => x.v);

            if (previousKey != null)
            {
                if (!excelData.ContainsKey(previousKey))
                {
                    excelData.Add(previousKey, dic);
                }
            }
        }

        ++i;
    }
}

I extract all data from the excel file (excelDataRaw). i then select all data that belongs together into a list (curve) and combine two lists that belong to each other into a dictionary (dic). The final result is a dictionary (excelData) that contains the column head from the excel file as a key (previousKey) and the data relevant to this column head as a dictionary (dic).

I would like to cast the dictionary (excelData) from

Dictionary<string, IDictionary<object, object>>

into

Dictionary<string, IDictionary<string, decimal>>

but i can't cast object into string or decimal and i can't zip the lists together to get the dictionary (dic) after casting each list to the desired type. Has anyone an idea how to achieve the desired result(type)?

Body:
ExcelDataRaw is of type Dictionary<string, IDictionary<object, object>> so it needs IDictionary<object, object> as the value. You can't cast Dictionary<string,decimal> into IDictionary<object,object> because IDictionary is not a covariant interface - see http://msdn.microsoft.com/en-us/library/dd469487.aspx.

The solution is either to change the type of ExcelDataRaw to Dictionary<string, IDictionary<string, decimal>> or to keep it as is and when trying to use the values from that dictionary cast those to correct types:

foreach(var kv in ExcelDataRaw)
{
   Dictionary<string,decimal> convertedValue=kv.Value.ToDictionary(x=>(string)x.Key,x=>(decimal)x.Value);
   // or convert it even further down the road
   string lookup = "abc";
   decimal v = (decimal)kv.Value[lookup];
}


问:
Least number of stamps needed to pay certain postage
I wrote a C program to solve the stamp and postage problem using brute force. However, it looks really stupid... Is there any better algorithms there to find the fewest number of stamps needed to pay certain postage?</p>
```<code>const int denominations[] = {1, 5, 17, 23, 37, 50};
int stamps[] = {0, 0, 0, 0, 0, 0};

void ALG2(int p) { //p means postage
    int least = p;
    int i[] = {0, 0, 0, 0, 0, 0};

    for (i[0] = 0; i[0] <= p / denominations[0]; i[0]++) {
        for (i[1] = 0; i[1] <= p / denominations[1]; i[1]++) {
            for (i[2] = 0; i[2] <= p / denominations[2]; i[2]++) {
                for (i[3] = 0; i[3] <= p / denominations[3]; i[3]++) {
                    for (i[4] = 0; i[4] <= p / denominations[4]; i[4]++) {
                        for (i[5] = 0; i[5] <= p / denominations[5]; i[5]++) {
                            if (getSum(i) == p) {
                                if (getCount(i) < least) {
                                    least = getCount(i);
                                    for (int j = 0; j < 6; j++)
                                        stamps[j] = i[j];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

答:
5 is evenly divisible by 1; so it never makes sense to have 5 or more 1 cent stamps. In other words, you can significantly reduce the worst case by doing for (i[0] = 0; (i[0] <= p / denominations[0]) && (i[0] < 5); i[0]++) {

What is the maximum number of 5 cent stamps that could make sense? You can determine this by using "lowest least common multiple":

```<code>LCM(5, 17) = 85 = less than (85/5) or 17 of the 5 cent stamps
LCM(5, 23) = 115 = less than (115/5) or 23 of the 5 cent stamps
LCM(5, 37) = 185 = less than (185/5) or 37 of the 5 cent stamps
LCM(5, 50) = 50 = less than (50/5) or 10 of the 5 cent stamps
Result: Less than 10 of the 5 cent stamps
</code>```

What is the maximum number of 17, 23, or 37 cent stamps that could make sense? Same approach:

```<code>LCM(17, 23) = 391 = less than 23
LCM(17, 37) = 629 = less than 37
LCM(17, 50) = 850 = less than 50
Result: Less than 23 of the 17 cent stamps

LCM(23, 37) = 851 = less than 37
LCM(23, 50) = 1150 = less than 50
Result: Less than 37 of the 23 cent stamps

LCM(37, 50) = 1850 = less than 50
Result: Less than 50 of the 37 cent stamps
</code>```

Also; LCM(5, 17, 23, 37, 50) = 723350. This means that if you want a higher amount of postage you can assume there must be at least (p/723350)*(723350/50) of the 50 cent stamps, or there must be at least (p/723350)* 14467 of the 50 cent stamps. E.g. if someone wants 9999999 postage, then (9999999/723350) * 14467 = 13 * 14467 = 188071, so there must be at least 188071 of the 50 cent stamps.

For getSum(), you can keep track in each loop so that it only requires additions. E.g.:

```<code>    for (i[0] = 0, sum0 = 0; i[0] <= p / denominations[0]; i[0]++, sum0 += i[0]) {
        for (i[1] = 0, sum1 = sum0; i[1] <= p / denominations[1]; i[1]++, sum1 += i[1]) {
            for (i[1] = 0, sum2 = sum1; i[1] <= p / denominations[1]; i[1]++, sum2 += i[2]) {
</code>```

This allows you to improve efficiency (compared to doing getSum()); but more importantly it allows you to replace the inner loop with a modulo operation, like:

```<code>if(sum4 < p) {
    if( (p - sum4) % denominations[5] == 0) {
        i[5] = (p - sum4) / denominations[5];
        if (getCount(i) < least) {
</code>```

By reversing the order of loops (so that 50 cent stamps are the outer-most loop and the 1 cent stamps are the inner-most loop) this gets even better because you know everything is divisible by 1:

```<code>if(sum1 < p) {
    i[0] = p - sum1;
    if (getCount(i) < least) {
</code>```

It also allows you to be smarter about the loops (as mentioned by Reinstate Monica's answer). E.g.:

```<code>        for (i[2] = 0, sum2 = sum3; (i[2] <= (p - sum3) / denominations[2]) && (i[2] < 37); i[2]++, sum2 += denominations[2]) {
</code>```

Now...

What if you had a small table containing the best answer for all postage values from 0 to 9, so if the amount of postage you're still looking for is less than 10 you can use the table to skip all the work in all the remaining inner loops, like:

```<code>    for (i[5] = 0, sum5 = 0; (i[5] <= p / denominations[5]) && (i[5] < 37); i[5]++, sum5 += denominations[5]) {
        if(p - sum5 < 10) {
            /* Use table to skip everything else */
        } else {
            for (i[4] = 0, sum4 = sum5; (i[4] <= (p - sum5) / denominations[4]) && (i[4] < 50); i[4]++, sum4 += denominations[4]) {
            if(p - sum4 < 10) {
                /* Use table to skip everything else */
            } else {
</code>```

What if the table was a bigger and contained the best answer for all postage values from 0 to 999? Obviously, the larger the table is the more work you can skip and the faster it's going to be.

Taking into account the "LCM(5, 17, 23, 37, 50) = 723350" stuff from earlier; the maximum size table you'd need would have 723350 entries. At this point all the loops become unnecessary. It's probably too big to include a pre-calculated table in the program itself; but what if an entry in the table could be set to "currently unknown"?

In that case you could start with a small pre-calculated table (e.g. the best answer for all postage values from 0 to 99) to initialize the huge table; then do something like:

```<code>    for (i[5] = 0, sum5 = 0; (i[5] <= p / denominations[5]) && (i[5] < 37); i[5]++, sum5 += denominations[5]) {
        if(huge_table_entry[p - sum5].state != UNKNOWN) {
            /* Use table to skip everything else */
        } else {
            /* Determine answer for p - sum5 without using table, and then store
               the answer in the table in case it's needed again at some point */
</code>```

Body:
I wrote a C program to solve the stamp and postage problem using brute force. However, it looks really stupid... Is there any better algorithms there to find the fewest number of stamps needed to pay certain postage?

const int denominations[] = {1, 5, 17, 23, 37, 50};
int stamps[] = {0, 0, 0, 0, 0, 0};

void ALG2(int p) { //p means postage
    int least = p;
    int i[] = {0, 0, 0, 0, 0, 0};

    for (i[0] = 0; i[0] <= p / denominations[0]; i[0]++) {
        for (i[1] = 0; i[1] <= p / denominations[1]; i[1]++) {
            for (i[2] = 0; i[2] <= p / denominations[2]; i[2]++) {
                for (i[3] = 0; i[3] <= p / denominations[3]; i[3]++) {
                    for (i[4] = 0; i[4] <= p / denominations[4]; i[4]++) {
                        for (i[5] = 0; i[5] <= p / denominations[5]; i[5]++) {
                            if (getSum(i) == p) {
                                if (getCount(i) < least) {
                                    least = getCount(i);
                                    for (int j = 0; j < 6; j++)
                                        stamps[j] = i[j];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

Body:
5 is evenly divisible by 1; so it never makes sense to have 5 or more 1 cent stamps. In other words, you can significantly reduce the worst case by doing for (i[0] = 0; (i[0] <= p / denominations[0]) && (i[0] < 5); i[0]++) {

What is the maximum number of 5 cent stamps that could make sense? You can determine this by using "lowest least common multiple":

LCM(5, 17) = 85 = less than (85/5) or 17 of the 5 cent stamps
LCM(5, 23) = 115 = less than (115/5) or 23 of the 5 cent stamps
LCM(5, 37) = 185 = less than (185/5) or 37 of the 5 cent stamps
LCM(5, 50) = 50 = less than (50/5) or 10 of the 5 cent stamps
Result: Less than 10 of the 5 cent stamps

What is the maximum number of 17, 23, or 37 cent stamps that could make sense? Same approach:

LCM(17, 23) = 391 = less than 23
LCM(17, 37) = 629 = less than 37
LCM(17, 50) = 850 = less than 50
Result: Less than 23 of the 17 cent stamps

LCM(23, 37) = 851 = less than 37
LCM(23, 50) = 1150 = less than 50
Result: Less than 37 of the 23 cent stamps

LCM(37, 50) = 1850 = less than 50
Result: Less than 50 of the 37 cent stamps

Also; LCM(5, 17, 23, 37, 50) = 723350. This means that if you want a higher amount of postage you can assume there must be at least (p/723350)*(723350/50) of the 50 cent stamps, or there must be at least (p/723350)* 14467 of the 50 cent stamps. E.g. if someone wants 9999999 postage, then (9999999/723350) * 14467 = 13 * 14467 = 188071, so there must be at least 188071 of the 50 cent stamps.

For getSum(), you can keep track in each loop so that it only requires additions. E.g.:

    for (i[0] = 0, sum0 = 0; i[0] <= p / denominations[0]; i[0]++, sum0 += i[0]) {
        for (i[1] = 0, sum1 = sum0; i[1] <= p / denominations[1]; i[1]++, sum1 += i[1]) {
            for (i[1] = 0, sum2 = sum1; i[1] <= p / denominations[1]; i[1]++, sum2 += i[2]) {

This allows you to improve efficiency (compared to doing getSum()); but more importantly it allows you to replace the inner loop with a modulo operation, like:

if(sum4 < p) {
    if( (p - sum4) % denominations[5] == 0) {
        i[5] = (p - sum4) / denominations[5];
        if (getCount(i) < least) {

By reversing the order of loops (so that 50 cent stamps are the outer-most loop and the 1 cent stamps are the inner-most loop) this gets even better because you know everything is divisible by 1:

if(sum1 < p) {
    i[0] = p - sum1;
    if (getCount(i) < least) {

It also allows you to be smarter about the loops (as mentioned by Reinstate Monica's answer). E.g.:

        for (i[2] = 0, sum2 = sum3; (i[2] <= (p - sum3) / denominations[2]) && (i[2] < 37); i[2]++, sum2 += denominations[2]) {

Now...

What if you had a small table containing the best answer for all postage values from 0 to 9, so if the amount of postage you're still looking for is less than 10 you can use the table to skip all the work in all the remaining inner loops, like:

    for (i[5] = 0, sum5 = 0; (i[5] <= p / denominations[5]) && (i[5] < 37); i[5]++, sum5 += denominations[5]) {
        if(p - sum5 < 10) {
            /* Use table to skip everything else */
        } else {
            for (i[4] = 0, sum4 = sum5; (i[4] <= (p - sum5) / denominations[4]) && (i[4] < 50); i[4]++, sum4 += denominations[4]) {
            if(p - sum4 < 10) {
                /* Use table to skip everything else */
            } else {

What if the table was a bigger and contained the best answer for all postage values from 0 to 999? Obviously, the larger the table is the more work you can skip and the faster it's going to be.

Taking into account the "LCM(5, 17, 23, 37, 50) = 723350" stuff from earlier; the maximum size table you'd need would have 723350 entries. At this point all the loops become unnecessary. It's probably too big to include a pre-calculated table in the program itself; but what if an entry in the table could be set to "currently unknown"?

In that case you could start with a small pre-calculated table (e.g. the best answer for all postage values from 0 to 99) to initialize the huge table; then do something like:

    for (i[5] = 0, sum5 = 0; (i[5] <= p / denominations[5]) && (i[5] < 37); i[5]++, sum5 += denominations[5]) {
        if(huge_table_entry[p - sum5].state != UNKNOWN) {
            /* Use table to skip everything else */
        } else {
            /* Determine answer for p - sum5 without using table, and then store
               the answer in the table in case it's needed again at some point */


问:
Program to input correct password and limiting to tries
I am attempting to solve this coding question where the password has been set, and compare the user's input with the password. If the password matches, program outputs correct, if it doesnt, user has three maximum tries to fill in the correct password.

The program works fine but i noticed one small issue, if the tries < 3, the loop is never exited and it will be incomplete. This is the program i coded.

```<code>void matching(int matches)
    {
         if(matches == 0)
         {
             printf("You have entered the correct password!\n");
         }
    }

int main()
{
    char password[]= "tacobell";
    char input[15];
    int match;
    int count = 0;

    printf("Enter your password here: ");
    scanf("%s", input);

    match = strcmp(password, input);
    matching(match);

        while(match != 0)
    {
        while (count<3)
        {
            if (match != 0){
            printf("You have entered the wrong password, try again: ");
            scanf("%s", input);`enter code here`
            count++;
            match = strcmp(password, input);
            match = matching(match);
              //exits the while loop once the password has matched where match takes 0 value
        }
        }

        printf("You have attempted to log in %d times. ", count); //total number of scans will be returned
        printf("You have run out of tries, please try again later. \n");
        break;

    }

}
</code>```

答:
Recomended links:

You can find more about bit operators here.
With them you can chain multiple conditions in one
if statement or while statement etc.

I have used a short if statement in printf for example to determine if it was only one try or multiple tries and depending on this the singular form of try is printed or the plural form of try.
You can find more about short if statements here

```<code>
#include <stdio.h>
#include <string.h>

#pragma warning (disable:4996)
void matching(int matches)
{
    if (matches == 0)
    {
        printf("You have entered the correct password!\n");
    }
}

int main()
{
    char password[] = "tacobell";
    char input[15];
    int match;
    int count = 0;

    printf("Enter your password here: ");
    scanf("%s", input);
    count = 1;  //first attempt

    match = strcmp(password, input);
    matching(match);

    //I have combined your two conditions with the bit operator &&(and) it is only
    //executet as long as both are true -> if the right password is entered the second
    //condition after && 'match != 0' is no longer true and while is no longer executed
    //-> if count = 3 the left condition is false and while is no longer executed more
    //Info about bit operator && and more are in the first link
    while (count < 3 && match != 0)
    {
        printf("You have entered the wrong password, try again: ");
        scanf("%s", input);
        count++;
        match = strcmp(password, input);
    }

    //(count == 1) ? "time" : "times" is a short if statement it reads like this
    //if (count == 1){ "time" } else { "times" }
    //but you can't write if (count == 1){ "time" } else { "times" } in printf
    //more to short if statements can you find in the second link
    printf("You have attempted to log in %d %s.\n", count, (count == 1) ? "time" : "times"); //total number of scans will be returned

    //You have run out of tries should only be printed if the match wasn't found
    //an alternative to the short version would be
    //if (match != 0){ printf("You have run out of tries, please try again later. \n"); }
    //more to short if statements can you find in the second link
    printf("%s", (match != 0) ? "You have run out of tries, please try again later. \n" : "");
    return 0;
}

</code>```

Body:
I am attempting to solve this coding question where the password has been set, and compare the user's input with the password. If the password matches, program outputs correct, if it doesnt, user has three maximum tries to fill in the correct password.

The program works fine but i noticed one small issue, if the tries < 3, the loop is never exited and it will be incomplete. This is the program i coded.

void matching(int matches)
    {
         if(matches == 0)
         {
             printf("You have entered the correct password!\n");
         }
    }

int main()
{
    char password[]= "tacobell";
    char input[15];
    int match;
    int count = 0;

    printf("Enter your password here: ");
    scanf("%s", input);

    match = strcmp(password, input);
    matching(match);

        while(match != 0)
    {
        while (count<3)
        {
            if (match != 0){
            printf("You have entered the wrong password, try again: ");
            scanf("%s", input);`enter code here`
            count++;
            match = strcmp(password, input);
            match = matching(match);
              //exits the while loop once the password has matched where match takes 0 value
        }
        }

        printf("You have attempted to log in %d times. ", count); //total number of scans will be returned
        printf("You have run out of tries, please try again later. \n");
        break;

    }

}

Body:
Recomended links:

You can find more about bit operators here.
With them you can chain multiple conditions in one
if statement or while statement etc.

I have used a short if statement in printf for example to determine if it was only one try or multiple tries and depending on this the singular form of try is printed or the plural form of try.
You can find more about short if statements here

#include <stdio.h>
#include <string.h>

#pragma warning (disable:4996)
void matching(int matches)
{
    if (matches == 0)
    {
        printf("You have entered the correct password!\n");
    }
}

int main()
{
    char password[] = "tacobell";
    char input[15];
    int match;
    int count = 0;

    printf("Enter your password here: ");
    scanf("%s", input);
    count = 1;  //first attempt

    match = strcmp(password, input);
    matching(match);

    //I have combined your two conditions with the bit operator &&(and) it is only
    //executet as long as both are true -> if the right password is entered the second
    //condition after && 'match != 0' is no longer true and while is no longer executed
    //-> if count = 3 the left condition is false and while is no longer executed more
    //Info about bit operator && and more are in the first link
    while (count < 3 && match != 0)
    {
        printf("You have entered the wrong password, try again: ");
        scanf("%s", input);
        count++;
        match = strcmp(password, input);
    }

    //(count == 1) ? "time" : "times" is a short if statement it reads like this
    //if (count == 1){ "time" } else { "times" }
    //but you can't write if (count == 1){ "time" } else { "times" } in printf
    //more to short if statements can you find in the second link
    printf("You have attempted to log in %d %s.\n", count, (count == 1) ? "time" : "times"); //total number of scans will be returned

    //You have run out of tries should only be printed if the match wasn't found
    //an alternative to the short version would be
    //if (match != 0){ printf("You have run out of tries, please try again later. \n"); }
    //more to short if statements can you find in the second link
    printf("%s", (match != 0) ? "You have run out of tries, please try again later. \n" : "");
    return 0;
}


问:
Unable to create a new Cloud Function - cloud-client-api-gae
I'm unable to create a Cloud Function in my GCP project using GUI, but have admin roles for GCF, SA and IAM.

Here is the error message:

Missing necessary permission iam.serviceAccounts.actAs for
cloud-client-api-gae on the service account
serviceaccountname@DOMAIN.iam.gserviceaccount.com. Grant the role
'roles/iam.serviceAccountUser' to cloud-client-api-gae on the service
account serviceaccountname@DOMAIN.iam.gserviceaccount.com.

cloud-client-api-gae is not an SA nor User on my IAM list. It must be a creature living underneath Graphical User Interfrace.

I have Enabled API for GCF, AppEngine and I have Service Account Admin role.

I had literally 0 search results when googling for cloud-client-api-gae.

答: The user account attempting to create cloud function, need to be given "Service account user" role on the Service account they are using for this cloud function to run on.</p>


问:
How do I split a list on certain conditions in Haskell?
As a programming exercise I'm trying to build a function in Haskell where given a list it splits the list whenever an element is repeated. [1,2,3,3,4,5] would split into [[1,2,3],[3,4,5]] for example. My first idea was to split the list into a list of lists with single elements, where [1,2,3,3,4,5] would become [[1],[2],[3],[3],[4],[5]] and then merge lists only when the elements being compared are not equal, but implementing this has been a headache for me as I'm very new to Haskell and recursion has always given me trouble. I think something is wrong with the function I'm using to combine the lists, it will only ever return a list where all the elements that were broken apart are combined, where [1,2,3,3,4,5] becomes [[1],[2],[3],[3],[4],[5]] but my split_help function will transform this into [[1,2,3,3,4,5]] instead of [[1,2,3],[3,4,5]]

I've pasted my incomplete code below, it doesn't work right now but it should give the general idea of what I'm trying to accomplish. Any feedback on general Haskell code etiquette would also be welcome.

split_breaker breaks the list into a list of list and split_help is what I'm trying to use to combine unequal elements.

```<code>split_help x y
     | x /= y = x ++ y
     | otherwise = []

split_breaker :: Eq a => [a] -> [[a]]
split_breaker [] = []
split_breaker [x] = [[x]]
split_breaker (x:xs) = [x]:split_breaker xs

split_at_duplicate :: Eq a => [a] -> [[a]]
split_at_duplicate [x] = [[x]]
split_at_duplicate (x:xs) = foldl1 (split_help) (split_breaker [xs])
</code>```

答:
Do you want to work it something like this?

```<code>splitAtDup [1,2,3,3,3,4,4,5,5,5,5,6]
[[1,2,3],[3],[3,4],[4,5],[5],[5],[5,6]]
</code>```

Am I right?

Then do it simple:

```<code>splitAtDup :: Eq a => [a] -> [[a]]
splitAtDup (x : y : xs) | x == y = [x] : splitAtDup (y : xs)
splitAtDup (x : xs) =
  case splitAtDup xs of
    x' : xs' -> (x : x') : xs'
    _ -> [[x]]
splitAtDup [] = []
</code>```

Body:
As a programming exercise I'm trying to build a function in Haskell where given a list it splits the list whenever an element is repeated. [1,2,3,3,4,5] would split into [[1,2,3],[3,4,5]] for example. My first idea was to split the list into a list of lists with single elements, where [1,2,3,3,4,5] would become [[1],[2],[3],[3],[4],[5]] and then merge lists only when the elements being compared are not equal, but implementing this has been a headache for me as I'm very new to Haskell and recursion has always given me trouble. I think something is wrong with the function I'm using to combine the lists, it will only ever return a list where all the elements that were broken apart are combined, where [1,2,3,3,4,5] becomes [[1],[2],[3],[3],[4],[5]] but my split_help function will transform this into [[1,2,3,3,4,5]] instead of [[1,2,3],[3,4,5]]

I've pasted my incomplete code below, it doesn't work right now but it should give the general idea of what I'm trying to accomplish. Any feedback on general Haskell code etiquette would also be welcome.

split_breaker breaks the list into a list of list and split_help is what I'm trying to use to combine unequal elements.

split_help x y
     | x /= y = x ++ y
     | otherwise = []

split_breaker :: Eq a => [a] -> [[a]]
split_breaker [] = []
split_breaker [x] = [[x]]
split_breaker (x:xs) = [x]:split_breaker xs

split_at_duplicate :: Eq a => [a] -> [[a]]
split_at_duplicate [x] = [[x]]
split_at_duplicate (x:xs) = foldl1 (split_help) (split_breaker [xs])

Body:
Do you want to work it something like this?

splitAtDup [1,2,3,3,3,4,4,5,5,5,5,6]
[[1,2,3],[3],[3,4],[4,5],[5],[5],[5,6]]

Am I right?

Then do it simple:

splitAtDup :: Eq a => [a] -> [[a]]
splitAtDup (x : y : xs) | x == y = [x] : splitAtDup (y : xs)
splitAtDup (x : xs) =
  case splitAtDup xs of
    x' : xs' -> (x : x') : xs'
    _ -> [[x]]
splitAtDup [] = []


问:
How to improve the count of unique values to illustrate cleaner format
Column order_cd has two unique values = SGL, DBL.
I am trying to get the count of these for each store number in a location. I am able to get the count with my code below but would like to learn how to get it into the desired format in sql.</p>
```<code>SELECT
Location, store_nm,
,SUM(CASE WHEN order_cd = 'SGL' THEN 1 ELSE 0 end) AS Single
,SUM(CASE WHEN order_cd = 'DBL' THEN 1 ELSE 0 end) AS Double
From Table
</code>```
```<code>**Current state
+----------+----------+--------+---------+
| Location | Store_nm | Single | Double  |
+----------+----------+--------+---------+
|     E    |   10     |   123  |   0     |
|     E    |   10     |    0   |   2     |
|     E    |   30     |    55  |   0     |
|     E    |   30     |    0   |   65    |
|     E    |   45     |   1456 |   0     |
|     E    |   45     |   0    |   800   |
+----------+----------+--------+---------+

**DESIRED**
+----------+----------+--------+---------+
| Location | Store_nm | Single | Double  |
+----------+----------+--------+---------+
|     E    |   10     |   123  |    2    |
|     E    |   30     |   55   |    65   |
|     E    |   45     |  1456  |   800   |
+----------+----------+--------+---------+
</code>```

答:
Answer provided by user FlexYourData.

Add GROUP BY Location, store_nm to the end of your query.

Thank you!

Body:
Column order_cd has two unique values = SGL, DBL.
I am trying to get the count of these for each store number in a location. I am able to get the count with my code below but would like to learn how to get it into the desired format in sql.

SELECT
Location, store_nm,
,SUM(CASE WHEN order_cd = 'SGL' THEN 1 ELSE 0 end) AS Single
,SUM(CASE WHEN order_cd = 'DBL' THEN 1 ELSE 0 end) AS Double
From Table

**Current state
+----------+----------+--------+---------+
| Location | Store_nm | Single | Double  |
+----------+----------+--------+---------+
|     E    |   10     |   123  |   0     |
|     E    |   10     |    0   |   2     |
|     E    |   30     |    55  |   0     |
|     E    |   30     |    0   |   65    |
|     E    |   45     |   1456 |   0     |
|     E    |   45     |   0    |   800   |
+----------+----------+--------+---------+

**DESIRED**
+----------+----------+--------+---------+
| Location | Store_nm | Single | Double  |
+----------+----------+--------+---------+
|     E    |   10     |   123  |    2    |
|     E    |   30     |   55   |    65   |
|     E    |   45     |  1456  |   800   |
+----------+----------+--------+---------+


问:
Python and arbitrary command line options
I am writing a command-line plugin-based program where the plugins will provide additional functionality on top of whatever I provide.

So for example suppose I wrote a simple script that parsed images and stored them, and that's all I do. Then someone else can write a set of scripts to manipulate the image, putting his scripts in a plugin.

The plugin would be loaded and users can access the plugin by specifying its name in the command line.

It is not uncommon for scripts to want to provide additional options for the user.
So suppose in some years, 20 different plugins have been written.

Now, all of the authors want to allow users to provide options, so the main engine should take the user's options and pass them to the plugin so that it can handle them however it wants.

To keep it uniform, they might agree that certain options should perform a similar operation. Like "-o name" should set the output name to "name". They would then go about implementing their own options and stuff, which the main engine does not know about (of course, it shouldn't know what the plugins do)

I am using the deprecated getopt module, and it will throw exceptions whenever I specify an undefined option. I have heard of optparse and argparse, but I am not sure if these will allow the user to specify any options he wants without the code throwing an exception.

How can I make it so I can specify any command-line option?

答: argparse lets you partially parse an argument list with the parse_known_args method, returning what was parsed correctly, together with a list of the remaining arguments.