问:
Rollup.js - Use rollup.config.js in JS API?
I have a working rollup.config.js file but need to run a separate packaging script after Rollup is done. My plan was to use Rollup's watchers via their JS API. However, I cannot get the JS API to work at all.

I am referencing this code from the Rollup site...

```<code>const loadConfigFile = require('rollup/dist/loadConfigFile');
const path = require('path');
const rollup = require('rollup');

loadConfigFile(path.resolve(__dirname, 'rollup.config.js'))
  .then(async ({options, warnings}) => {
    warnings.flush();
    const bundle = await rollup.rollup(options);
    await Promise.all(options.output.map(bundle.write));
    rollup.watch(options);
  })
</code>```

but I keep getting an error Unknown input options: 0.......Error: You must supply options.input to rollup

My rollup.config.js is as follow...

```<code>import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from "rollup-plugin-terser";
import replace from '@rollup/plugin-replace';
import json from '@rollup/plugin-json';

const production = !process.env.ROLLUP_WATCH;

export default {
    input: 'src/main.js',
    output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/bundle.js'
    },
    plugins: [
        json(),
        production && replace({
            'eruda': ``,
            exclude: 'node_modules/**',
            delimiters: ['import * as eruda from \'', '\'']
        }),
        production && replace({
            'eruda': ``,
            exclude: 'node_modules/**',
            delimiters: ['', '.init()']
        }),
        svelte({
            dev: !production,
            css: css => {
                css.write('public/bundle.css');
            }
        }),
        resolve({ browser: true }),
        commonjs(),

        !production && livereload('public'),
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};
</code>```

Any thoughts are appreciated!

答: Figured it out, apparently the options returned from loadConfigFile is an array so I had to do options[0] inside the async function

Body:
I have a working rollup.config.js file but need to run a separate packaging script after Rollup is done. My plan was to use Rollup's watchers via their JS API. However, I cannot get the JS API to work at all.

I am referencing this code from the Rollup site...

const loadConfigFile = require('rollup/dist/loadConfigFile');
const path = require('path');
const rollup = require('rollup');

loadConfigFile(path.resolve(__dirname, 'rollup.config.js'))
  .then(async ({options, warnings}) => {
    warnings.flush();
    const bundle = await rollup.rollup(options);
    await Promise.all(options.output.map(bundle.write));
    rollup.watch(options);
  })

but I keep getting an error Unknown input options: 0.......Error: You must supply options.input to rollup

My rollup.config.js is as follow...

import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from "rollup-plugin-terser";
import replace from '@rollup/plugin-replace';
import json from '@rollup/plugin-json';

const production = !process.env.ROLLUP_WATCH;

export default {
    input: 'src/main.js',
    output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/bundle.js'
    },
    plugins: [
        json(),
        production && replace({
            'eruda': ``,
            exclude: 'node_modules/**',
            delimiters: ['import * as eruda from \'', '\'']
        }),
        production && replace({
            'eruda': ``,
            exclude: 'node_modules/**',
            delimiters: ['', '.init()']
        }),
        svelte({
            dev: !production,
            css: css => {
                css.write('public/bundle.css');
            }
        }),
        resolve({ browser: true }),
        commonjs(),

        !production && livereload('public'),
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

Any thoughts are appreciated!


来源: stackexchange

问:
Type bounds constraints restrictions in Higher Kinds when extending a trait
Let's set up issue conditions

trait Bound
trait Bound2 extends Bound

trait T1[B <: Bound]
trait T2[B <: Bound2] extends T1[B]

trait WrapperT1[Tz[B2 <: Bound] <: T1[B2]]
```

<p>This code compile without problem, issue comes when trying to extend <code>WrapperT1</code></p>

<pre class="lang-scala prettyprint-override"><code>trait WrapperT2[Tz[B2 <: Bound2] <: T2[B2]] extends WrapperT1[T2]

// Compilator error
kinds of the type arguments (T2) do not conform to the expected kinds of the type parameters (type Tz) in trait WrapperT1.

[error] ex.T2's type parameters do not match type Tz's expected parameters:

[error] type B's bounds <: Bound2 are stricter than type B2's declared bounds <: ex.Bound

[error]     trait WrapperT2[Tz[B2 <: Bound2] <: T2[B2]] extends WrapperT1[T2]

</code>```

Yes B2 <: Bound2 is stricter than B2 <: Bound but i'm not understanding why the compilator complains for this reason and i would be grateful to know more about it.

Potential solution but does it has some drawbacks ?

trait Bound
trait Bound2 extends Bound

trait T1[B] {
    implicit val ev: B <:< Bound
}

trait T2[B] extends T1[B] {
    // this is possible thank's to covariance of class `<:<[-From, +To]` if i'm not wrong
    implicit val ev: B <:< Bound2
}

trait WrapperT1[Tz[B2] <: T1[B2]]
// Compiles
trait WrapperT2[Tz[B2] <: T2[B2]] extends WrapperT1[Tz]

```

This looks nice and we keep the compilation checks about B2 generic type but is there any inconveniant using it ?

答:
To understand why the compiler complains, let's look at this piece of code (which is the same as your code, but with different names)

```<code>trait Show[A <: AnyRef] {
  def show(a: A): Unit
}
trait ShowString[S <: CharSequence] extends Show[S] {
  def show(s: S): Unit = println(s)
}

trait Wrapper1[S[A <: AnyRef] <: Show[A]] {
  def show[A <: AnyRef](a: A)(implicit show: S[A]): Unit = show.show(a)
}

trait Wrapper2[S[C <: CharSequence] <: ShowString[C]] extends Wrapper1[S]
</code>```

Here, too, the compiler emits the error type C's bounds <: CharSequence are stricter than type A's declared bounds <: AnyRef, but let's pretend you somehow get it to compile here. That would mean if someone wanted to use your wrapper class to print, say, a list, they wouldn't be able to do that, meaning that your wrapper class would be basically useless.

```<code>val w2: Wrapper[ShowString] = ???
w2.show(List(1, 2))
//Error: could not find implicit value for parameter show: ShowString[List[Int]]
</code>```

In this case, it's just that the implicit isn't found. However, if you have a method in wrapper that accepts a S[_] (or Tz[_], from your example) and you try to shoehorn an object of the wrong type into your show method, you could get a runtime exception.

It fails for the same reason you can't do this

```<code>trait T1[A] {
  def process(a: A): Unit
}
trait T2 extends T1[Int] {
  def process(i: Int): Unit = ???
}
val t2: T2 = ???

t2.process("not an int")
</code>```

T2 is just not equipped to handle anything that is not an Int, and the same applies here.

ContentLicense: CC BY-SA 4.0

Body:
Let's set up issue conditions

trait Bound
trait Bound2 extends Bound

trait T1[B <: Bound]
trait T2[B <: Bound2] extends T1[B]

trait WrapperT1[Tz[B2 <: Bound] <: T1[B2]]

This code compile without problem, issue comes when trying to extend WrapperT1

trait WrapperT2[Tz[B2 <: Bound2] <: T2[B2]] extends WrapperT1[T2]

// Compilator error
kinds of the type arguments (T2) do not conform to the expected kinds of the type parameters (type Tz) in trait WrapperT1.

[error] ex.T2's type parameters do not match type Tz's expected parameters:

[error] type B's bounds <: Bound2 are stricter than type B2's declared bounds <: ex.Bound

[error]     trait WrapperT2[Tz[B2 <: Bound2] <: T2[B2]] extends WrapperT1[T2]

Yes B2 <: Bound2 is stricter than B2 <: Bound but i'm not understanding why the compilator complains for this reason and i would be grateful to know more about it.

Potential solution but does it has some drawbacks ?

trait Bound
trait Bound2 extends Bound

trait T1[B] {
    implicit val ev: B <:< Bound
}

trait T2[B] extends T1[B] {
    // this is possible thank's to covariance of class `<:<[-From, +To]` if i'm not wrong
    implicit val ev: B <:< Bound2
}

trait WrapperT1[Tz[B2] <: T1[B2]]
// Compiles
trait WrapperT2[Tz[B2] <: T2[B2]] extends WrapperT1[Tz]

This looks nice and we keep the compilation checks about B2 generic type but is there any inconveniant using it ?

Body:
To understand why the compiler complains, let's look at this piece of code (which is the same as your code, but with different names)

trait Show[A <: AnyRef] {
  def show(a: A): Unit
}
trait ShowString[S <: CharSequence] extends Show[S] {
  def show(s: S): Unit = println(s)
}

trait Wrapper1[S[A <: AnyRef] <: Show[A]] {
  def show[A <: AnyRef](a: A)(implicit show: S[A]): Unit = show.show(a)
}

trait Wrapper2[S[C <: CharSequence] <: ShowString[C]] extends Wrapper1[S]

Here, too, the compiler emits the error type C's bounds <: CharSequence are stricter than type A's declared bounds <: AnyRef, but let's pretend you somehow get it to compile here. That would mean if someone wanted to use your wrapper class to print, say, a list, they wouldn't be able to do that, meaning that your wrapper class would be basically useless.

val w2: Wrapper[ShowString] = ???
w2.show(List(1, 2))
//Error: could not find implicit value for parameter show: ShowString[List[Int]]

In this case, it's just that the implicit isn't found. However, if you have a method in wrapper that accepts a S[_] (or Tz[_], from your example) and you try to shoehorn an object of the wrong type into your show method, you could get a runtime exception.

It fails for the same reason you can't do this

trait T1[A] {
  def process(a: A): Unit
}
trait T2 extends T1[Int] {
  def process(i: Int): Unit = ???
}
val t2: T2 = ???

t2.process("not an int")

T2 is just not equipped to handle anything that is not an Int, and the same applies here.


Title: Python Dataframes: Merging two dataframes according to a condition (Pandas)

Body:
Let say that I have this two DataFrames:

DATAFRAME 1
    onset  offset
0       1     200
1     201     400
2     401     600
3     601     800
4     801    1000
5    1001    1200
6    1201    1400
7    1401    1600
8    1601    1800
9    1801    2000
10   2001    2200
11   2201    2400
12   2401    2600
13   2601    2800
14   2801    3000
15   3001    3200
16   3201    3400
17   3401    3600
18   3601    3800
19   3801    4000
20   4001    4200
21   4201    4400
22   4401    4600
23   4601    4800
24   4801    5000
25   5001    5200
26   5201    5400
27   5401    5600
28   5601    5800
29   5801    6000
DATAFRAME 2
   onset rhythm_name  rhythm_code  offset
0      1         NSR          100    2760
1   2761  JUNCTIONAL         4000    3938
2   3939         NSR          100    6000

My goal is to merge both dataframes with the onset-offset intervals and add their respective rhythm_name and rhythm_code to get something like this:

    onset  offset  rhythm_name  rhythm_code
0       1     200        NSR          100
1     201     400        NSR          100
2     401     600        NSR          100
3     601     800        NSR          100
4     801    1000        NSR          100
5    1001    1200        NSR          100
6    1201    1400        NSR          100
7    1401    1600        NSR          100
8    1601    1800        NSR          100
9    1801    2000        NSR          100
10   2001    2200        NSR          100
11   2201    2400        NSR          100
12   2401    2600        NSR          100
13   2601    2800        Null         Null
14   2801    3000  JUNCTIONAL         4000
15   3001    3200  JUNCTIONAL         4000
16   3201    3400  JUNCTIONAL         4000
17   3401    3600  JUNCTIONAL         4000
18   3601    3800  JUNCTIONAL         4000
19   3801    4000        Null         Null
20   4001    4200        NSR          100
21   4201    4400        NSR          100
22   4401    4600        NSR          100
23   4601    4800        NSR          100
24   4801    5000        NSR          100
25   5001    5200        NSR          100
26   5201    5400        NSR          100
27   5401    5600        NSR          100
28   5601    5800        NSR          100
29   5801    6000        NSR          100

What can I use to do this? I can`t find a way to solve this problem. I have tried something like:

df1["rhythm_name"] = df2[(df1['onset'] >= df2['onset']) & (df1['offset'] <= df2['offset'])])

And I get this:

ValueError: Can only compare identically-labeled Series objects

I made a script to reproduce the problem:

df1 = pd.DataFrame()
onsets = []
for i in range(0,30):
  onset = i * 200 + 1
  onsets.append(onset)
df1['onset'] = onsets
df1['offset'] = df1["onset"]+200-1

df2 = {'onset': [1, 2761, 3939],
       'offset': [2760, 3938, 6000],
       'rhythm_name': ["NSR", "JUNCTIONAL", "NSR"],
       'rhythm_code': [100, 4000, 100]}

Body:
If your data is not too big, you can use a broadcasting approach:

cond1 = df1.onset.values[:,None] >= df2.onset.values
cond2 = df1.offset.values[:,None] <= df2.offset.values

mask = (cond1&cond2)
idx = np.where(mask.any(1), mask.argmax(1), np.nan)

for col in ['rhythm_name', 'rhythm_code']:
    df1[col] = df2[col].reindex(idx).values

Output:

0       1     200         NSR        100.0
1     201     400         NSR        100.0
2     401     600         NSR        100.0
3     601     800         NSR        100.0
4     801    1000         NSR        100.0
5    1001    1200         NSR        100.0
6    1201    1400         NSR        100.0
7    1401    1600         NSR        100.0
8    1601    1800         NSR        100.0
9    1801    2000         NSR        100.0
10   2001    2200         NSR        100.0
11   2201    2400         NSR        100.0
12   2401    2600         NSR        100.0
13   2601    2800         NaN          NaN
14   2801    3000  JUNCTIONAL       4000.0
15   3001    3200  JUNCTIONAL       4000.0
16   3201    3400  JUNCTIONAL       4000.0
17   3401    3600  JUNCTIONAL       4000.0
18   3601    3800  JUNCTIONAL       4000.0
19   3801    4000         NaN          NaN
20   4001    4200         NSR        100.0
21   4201    4400         NSR        100.0
22   4401    4600         NSR        100.0
23   4601    4800         NSR        100.0
24   4801    5000         NSR        100.0
25   5001    5200         NSR        100.0
26   5201    5400         NSR        100.0
27   5401    5600         NSR        100.0
28   5601    5800         NSR        100.0
29   5801    6000         NSR        100.0

Option 2: Another (better) approach with merge_asof:

(pd.merge_asof(df1,df2,on='onset',direction='backward',suffixes=['','_y'])
   .query('offset<=offset_y')
   .reindex(df1.index)
   .drop('offset_y', axis=1)
   .fillna(df1)
)

And you get the same output.


问:
imperative to functional: n-body collision
I'm a beginner in functional programming but I'm famaliar with imperative programming. I'm having trouble translating a piece of cpp code involving updatating two objects at the same time (context is n-body simulation).

It's roughly like this in c++:

for (Particle &i: particles) {
  for (Particle &j: particles) {
     collide(i, j) // function that mutates particles i and j
  }
}
```

<p>I'm translating this to Ocaml, with immutable objects and immutable Lists. The difficult part is that I need to replace two objects at the same time. So far I have this:</p>

<pre class="lang-ml prettyprint-override"><code>List.map (fun i ->
  List.map (fun j ->
    let (new_i, new_j) = collide(i, j) in // function that returns new particles i, j
    // how do i update particles with new i, j?
  ) particles
) particles
</code>```

How do I replace both objects in the List at the same time?

答:
The functional equivalent of the imperative code is just as simple as,

```<code>let nbody f xs =
  List.map (fun x -> List.fold_left f x xs) xs
</code>```

It is a bit more generic, as a I abstracted the collide function and made it a parameter. The function f takes two bodies and returns the state of the first body as affected by the second body. For example, we can implement the following symbolic collide function,

```<code>let symbolic x y = "f(" ^ x ^ "," ^ y ^ ")"
</code>```

so that we can see the result and associativity of the the collide function application,

```<code># nbody symbolic [
    "x"; "y"; "z"
];;
- : string list =
["f(f(f(x,x),y),z)"; "f(f(f(y,x),y),z)"; "f(f(f(z,x),y),z)"]
</code>```

So, the first element of the output list is the result of collision of x with x itself, then with y, then with z. The second element is the result of collision of y with x, and y, and z. And so on.

Obviously the body shall not collide with itself, but this could be easily fixed by either modifying the collide function or by filtering the input list to List.fold and removing the currently being computed element. This is left as an exercise.

Body:
I'm a beginner in functional programming but I'm famaliar with imperative programming. I'm having trouble translating a piece of cpp code involving updatating two objects at the same time (context is n-body simulation).

It's roughly like this in c++:

for (Particle &i: particles) {
  for (Particle &j: particles) {
     collide(i, j) // function that mutates particles i and j
  }
}

I'm translating this to Ocaml, with immutable objects and immutable Lists. The difficult part is that I need to replace two objects at the same time. So far I have this:

List.map (fun i ->
  List.map (fun j ->
    let (new_i, new_j) = collide(i, j) in // function that returns new particles i, j
    // how do i update particles with new i, j?
  ) particles
) particles

How do I replace both objects in the List at the same time?

Body:
The functional equivalent of the imperative code is just as simple as,

let nbody f xs =
  List.map (fun x -> List.fold_left f x xs) xs

It is a bit more generic, as a I abstracted the collide function and made it a parameter. The function f takes two bodies and returns the state of the first body as affected by the second body. For example, we can implement the following symbolic collide function,

let symbolic x y = "f(" ^ x ^ "," ^ y ^ ")"

so that we can see the result and associativity of the the collide function application,

# nbody symbolic [
    "x"; "y"; "z"
];;
- : string list =
["f(f(f(x,x),y),z)"; "f(f(f(y,x),y),z)"; "f(f(f(z,x),y),z)"]

So, the first element of the output list is the result of collision of x with x itself, then with y, then with z. The second element is the result of collision of y with x, and y, and z. And so on.

Obviously the body shall not collide with itself, but this could be easily fixed by either modifying the collide function or by filtering the input list to List.fold and removing the currently being computed element. This is left as an exercise.


问:
assign a given dat to DateTime in Flutter
I have a variable pickedDate that contains a user picked date of the DateTime type. I want to assign that date to the initial FirstDate of another instance that is now set to initialFirstDate: new DateTime.now(),

How can I achieve this?

答:
If your pickedDate is of type DateTime, then you can just set the initialDate of the second instance to that variable. </p>

```<code>await showDatePicker(
    context: context,
    initialDate: DateTime.now(),
    firstDate: pickedDate, //if pickedDate is type DateTime then this should work
    lastDate: DateTime(2222));
</code>```

Body:
If your pickedDate is of type DateTime, then you can just set the initialDate of the second instance to that variable.

await showDatePicker(
    context: context,
    initialDate: DateTime.now(),
    firstDate: pickedDate, //if pickedDate is type DateTime then this should work
    lastDate: DateTime(2222));


问:
Updating variables in web.config outside appSettings
I need to update values in web.config in Azure TFS. I am able to get the value for connectionString replaced which is part of the appSettings (for this to work, I needed to enable the setting named XML variable substitution (under IIS Web Deploy).

However, there are other areas within web.config which do not get replaced.

I have tried several different approaches, using different tasks for token replacement, using the "Release" or "Environment" setting for variables, using variable groups. However, none of these worked.

Currently I am using the Replace tokens task (available at https://github.com/qetza/vsts-replacetokens-task#readme )

I have set the Token Prefix and Suffix to __ (to match with what is web.config)

Here is an extract of the web.config file

```<code><?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="ConnectionString" value="__ConnectionString__"/>
    </appSettings>
    <system.web>
        <pages theme="__Theme__" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
            <controls>
                <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            </controls>
        </pages>
    </system.web>
    <system.serviceModel>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
        <bindings>
            <customBinding>
                <binding name="TestBinding1">
                    <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Soap12" writeEncoding="utf-8">
                        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    </textMessageEncoding>
                    <httpsTransport manualAddressing="false" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous" bypassProxyOnLocal="false" decompressionEnabled="true" hostNameComparisonMode="StrongWildcard" keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous" realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true" requireClientCertificate="false" />
                </binding>
            </customBinding>
            __basicHttpBindingOptionalBinding__
        </bindings>
        <client>
            <endpoint address="__TestEndPoint__" binding="customBinding" bindingConfiguration="TestBinding1" contract="BSEInspectionsWebServiceForFDA.StateDataTransfer" name="StateDataTransferPort" />
            __endpointOptionalEndpoint__
        </client>
    </system.serviceModel>
</configuration>
</code>```

I expect only blank lines for basicHttpBindingOptionalBinding and endpointOptionalEndpoint. The Theme needs to be replaced with TestTheme and TestEndPoint needs to be set with the value defined in variables.

答:
Add a parameters.xml to your project, as described here:
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/deployment/web-deployment-in-the-enterprise/configuring-parameters-for-web-package-deployment

specify parameter there, for example, "myEndpointAddress".

Then in IIS Web Deploy Task use additional arguments to pass the value
-setParam:name='myEndPointAddress',value='new_value'

Body:
I need to update values in web.config in Azure TFS. I am able to get the value for connectionString replaced which is part of the appSettings (for this to work, I needed to enable the setting named XML variable substitution (under IIS Web Deploy).

However, there are other areas within web.config which do not get replaced.

I have tried several different approaches, using different tasks for token replacement, using the "Release" or "Environment" setting for variables, using variable groups. However, none of these worked.

Currently I am using the Replace tokens task (available at https://github.com/qetza/vsts-replacetokens-task#readme )

I have set the Token Prefix and Suffix to __ (to match with what is web.config)

Here is an extract of the web.config file

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="ConnectionString" value="__ConnectionString__"/>
    </appSettings>
    <system.web>
        <pages theme="__Theme__" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
            <controls>
                <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            </controls>
        </pages>
    </system.web>
    <system.serviceModel>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
        <bindings>
            <customBinding>
                <binding name="TestBinding1">
                    <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Soap12" writeEncoding="utf-8">
                        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    </textMessageEncoding>
                    <httpsTransport manualAddressing="false" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous" bypassProxyOnLocal="false" decompressionEnabled="true" hostNameComparisonMode="StrongWildcard" keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous" realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true" requireClientCertificate="false" />
                </binding>
            </customBinding>
            __basicHttpBindingOptionalBinding__
        </bindings>
        <client>
            <endpoint address="__TestEndPoint__" binding="customBinding" bindingConfiguration="TestBinding1" contract="BSEInspectionsWebServiceForFDA.StateDataTransfer" name="StateDataTransferPort" />
            __endpointOptionalEndpoint__
        </client>
    </system.serviceModel>
</configuration>

I expect only blank lines for basicHttpBindingOptionalBinding and endpointOptionalEndpoint. The Theme needs to be replaced with TestTheme and TestEndPoint needs to be set with the value defined in variables.


问:
Get Percentages of Tables with Group by
I am working on a prediction game for a local league.

A Match is defined by its SPIELTAG (playday) and its MATCH_NR.
A prediction has a Match and a result (ERGA, ERGB)

I have a Table like in this fiddle https://www.db-fiddle.com/f/o4NXPFfzod39LpMaTzqz3r/0

I got the output to count each result per gameday and per match.

```<code>| SPIELTAG | MATCH_NR | ERGA | ERGB | AMOUNT |
| -------- | -------- | ---- | ---- | ------ |
| 4        | 1        | 7    | 1    | 1      |
| 4        | 1        | 7    | 2    | 2      |
| 4        | 1        | 7    | 3    | 5      |
| 4        | 1        | 7    | 4    | 1      |
| 4        | 2        | 1    | 7    | 1      |
| 4        | 2        | 2    | 7    | 6      |
| 4        | 2        | 3    | 7    | 3      |
</code>```

What i am trying to achieve is, next to the amount column something like

```<code>| SPIELTAG | MATCH_NR | ERGA | ERGB | AMOUNT | PERC |
| -------- | -------- | ---- | ---- | ------ | ---- |
| 4        | 1        | 7    | 1    | 1      | 11.1%| => 1 / 9
| 4        | 1        | 7    | 2    | 2      | 22.2%| => 2 / 9
| 4        | 1        | 7    | 3    | 5      | 55.5%| => 5 / 9
| 4        | 1        | 7    | 4    | 1      | 11.1%| => 1 / 9
| 4        | 2        | 1    | 7    | 1      | 11.1%| => 1 / 9
| 4        | 2        | 2    | 7    | 5      | 55.5%| => 5 / 9
| 4        | 2        | 3    | 7    | 3      | 33.3%| => 3 / 9
</code>```

Where PERC is the percentage of picks per playday SPIELTAG. Basically how often is the Result, the tuple of (ERGA, ERGB) predicted for each match SPIELTAG, MATCH_NR.

I found a post where i can get the percentage over all picks but not restricted  on the gameday,match tuple.

An Example:
Match 1 (Spieltag 4, Match 1) has 9 Predictions.

1x:  7-1

2x: 7-2

5x: 7-3

1x: 7-4

__

9x -> ALL_COUNTS_PER_MATCH

So PERC should be something like 'AMOUNT' / ALL_COUNTS_PER_MATCH.

答:
Check this, but will work in Mysql 8, not lower versions

https://www.db-fiddle.com/f/o4NXPFfzod39LpMaTzqz3r/4

```<code>SELECT DISTINCT  `t`.`SPIELTAG` AS `SPIELTAG`,
       `t`.`MATCH_NR` AS `MATCH_NR`,
       `t`.`TEAM_A` AS `ERGA`,
       `t`.`TEAM_B` AS `ERGB`,
       COUNT(0) OVER (PARTITION BY `t`.`SPIELTAG`,
                                   `t`.`MATCH_NR`,
                                   `t`.`TEAM_A`,
                                   `t`.`TEAM_B`) AS AMOUNT,
                     COUNT(0) OVER (PARTITION BY `t`.`SPIELTAG`,
                                                 `t`.`MATCH_NR`,
                                                 `t`.`TEAM_A`,
                                                 `t`.`TEAM_B`) / COUNT(CONCAT(SPIELTAG, MATCH_NR)) OVER (PARTITION BY `t`.`SPIELTAG`,
                                                                                `t`.`MATCH_NR`) AS match_count
FROM `TIPPSPIEL_TIPP` `t`
</code>```

Title: Get Percentages of Tables with Group by

Body:
I am working on a prediction game for a local league.

A Match is defined by its SPIELTAG (playday) and its MATCH_NR.
A prediction has a Match and a result (ERGA, ERGB)

I have a Table like in this fiddle https://www.db-fiddle.com/f/o4NXPFfzod39LpMaTzqz3r/0

I got the output to count each result per gameday and per match.

| SPIELTAG | MATCH_NR | ERGA | ERGB | AMOUNT |
| -------- | -------- | ---- | ---- | ------ |
| 4        | 1        | 7    | 1    | 1      |
| 4        | 1        | 7    | 2    | 2      |
| 4        | 1        | 7    | 3    | 5      |
| 4        | 1        | 7    | 4    | 1      |
| 4        | 2        | 1    | 7    | 1      |
| 4        | 2        | 2    | 7    | 6      |
| 4        | 2        | 3    | 7    | 3      |

What i am trying to achieve is, next to the amount column something like

| SPIELTAG | MATCH_NR | ERGA | ERGB | AMOUNT | PERC |
| -------- | -------- | ---- | ---- | ------ | ---- |
| 4        | 1        | 7    | 1    | 1      | 11.1%| => 1 / 9
| 4        | 1        | 7    | 2    | 2      | 22.2%| => 2 / 9
| 4        | 1        | 7    | 3    | 5      | 55.5%| => 5 / 9
| 4        | 1        | 7    | 4    | 1      | 11.1%| => 1 / 9
| 4        | 2        | 1    | 7    | 1      | 11.1%| => 1 / 9
| 4        | 2        | 2    | 7    | 5      | 55.5%| => 5 / 9
| 4        | 2        | 3    | 7    | 3      | 33.3%| => 3 / 9

Where PERC is the percentage of picks per playday SPIELTAG. Basically how often is the Result, the tuple of (ERGA, ERGB) predicted for each match SPIELTAG, MATCH_NR.

I found a post where i can get the percentage over all picks but not restricted  on the gameday,match tuple.

An Example:
Match 1 (Spieltag 4, Match 1) has 9 Predictions.

1x:  7-1

2x: 7-2

5x: 7-3

1x: 7-4

__

9x -> ALL_COUNTS_PER_MATCH

So PERC should be something like 'AMOUNT' / ALL_COUNTS_PER_MATCH.

Body:
Check this, but will work in Mysql 8, not lower versions

https://www.db-fiddle.com/f/o4NXPFfzod39LpMaTzqz3r/4

SELECT DISTINCT  `t`.`SPIELTAG` AS `SPIELTAG`,
       `t`.`MATCH_NR` AS `MATCH_NR`,
       `t`.`TEAM_A` AS `ERGA`,
       `t`.`TEAM_B` AS `ERGB`,
       COUNT(0) OVER (PARTITION BY `t`.`SPIELTAG`,
                                   `t`.`MATCH_NR`,
                                   `t`.`TEAM_A`,
                                   `t`.`TEAM_B`) AS AMOUNT,
                     COUNT(0) OVER (PARTITION BY `t`.`SPIELTAG`,
                                                 `t`.`MATCH_NR`,
                                                 `t`.`TEAM_A`,
                                                 `t`.`TEAM_B`) / COUNT(CONCAT(SPIELTAG, MATCH_NR)) OVER (PARTITION BY `t`.`SPIELTAG`,
                                                                                `t`.`MATCH_NR`) AS match_count
FROM `TIPPSPIEL_TIPP` `t`


问:
How can I get class files from Maven dependency into the target\classes folder
Is there any sort of Maven plugin that allows me to copy the class files for a dependency into the target\classes folder for my project? Currently I have to manually open the jar file that has the dependencies extract the package that I need to copy over and then copy it into the target\class folder for my project.

I need a way to do those ideally within the pom.xml file but I haven't been able to find a solution that works. Any help would be appreciated, Thanks.

答: This sounds like a terrible idea. If you want to include unpacked dependencies into your project, use the maven assembly plugin or the maven shade plugin.</p>


问:
missing Location in call to Time.In
When I ues beego/orm to operate postgresql database,there is an error like this "missing Location in call to Time.In".

code example

```<code>type dataTest struct {
    Id      int         `pk:"auto"`
    Data    time.Time   `orm:"auto_now;type(timestamp);null"`
}

local, _ := time.LoadLocation("UTC")
test_time, err := time.ParseInLocation("2006-01-02 15:04:05", "1111-01-25 14:27:07", local)
orm.DefaultTimeLoc = time.UTC

o,err := orm.NewOrmWithDB("postgres","default",db)
temp := new(dataTest)
temp.Id = 1
temp.Data = test_time
o.Update(temp)
</code>```

答:
For docker (build multi stage)

Install tzdata after build

```<code>RUN apk --no-cache add tzdata
</code>```

List of time zones available, see: https://golang.org/src/time/zoneinfo_abbrs_windows.go

```<code>loc, _ := time.LoadLocation("America/Bogota")
now := time.Now().In(loc)
</code>```

ContentLicense: CC BY-SA 3.0

Title: missing Location in call to Time.In

Body:
When I ues beego/orm to operate postgresql database,there is an error like this "missing Location in call to Time.In".

code example

type dataTest struct {
    Id      int         `pk:"auto"`
    Data    time.Time   `orm:"auto_now;type(timestamp);null"`
}

local, _ := time.LoadLocation("UTC")
test_time, err := time.ParseInLocation("2006-01-02 15:04:05", "1111-01-25 14:27:07", local)
orm.DefaultTimeLoc = time.UTC

o,err := orm.NewOrmWithDB("postgres","default",db)
temp := new(dataTest)
temp.Id = 1
temp.Data = test_time
o.Update(temp)

Body:
For docker (build multi stage)

Install tzdata after build

RUN apk --no-cache add tzdata

List of time zones available, see: https://golang.org/src/time/zoneinfo_abbrs_windows.go

loc, _ := time.LoadLocation("America/Bogota")
now := time.Now().In(loc)


问:
Which STL Container?
I need a container (not necessarily a STL container) which let me do the following easily:

Insertion and removal of elements at any position

Accessing elements by their index

Iterate over the elements in any order

I used std::list, but it won't let me insert at any position (it does, but for that I'll have to iterate over all elements and then insert at the position I want, which is slow, as the list may be huge). So can you recommend any efficient solution?

答:
(source: adrinael.net)

But it sounds like you're looking for a single container with the following properties:

All the best benefits of various containers

None of their ensuing downsides

And that's impossible. One benefit causes a detriment. Choosing a container is about compromise.

ContentLicense: CC BY-SA 2.5

Title: Which STL Container?


问:
How to maintain many Azure resources and deployments in one git repo?
I have a project that consists of an Azure webapp, a PostgreSQL on Azure, and multiple Azure functions for background ETL workflows. I also have a local Python package that I need to access from both the webapp and the Azure functions.

How can I structure configuration and script deployment for those resources from a single git repo?

Any suggestions or pointers to good examples or tutorials would be very appreciated.
All the Azure tutorials that I've seen are only for small and simple projects.

For now, I've hand-written an admin.py script that does e.g. the webapp and function deployments by creating a Python package, creating ZIP files for each resource and doing ZIP deployments. This is getting messy, and now I want to have QA and PROD versions, and I need to pass secrets so that the DB is reachable, and it's getting more complex. Is there either a nice way to structure this packaging / deployment, or a tool to help with it? For me, putting everything in Kubernetes is not the solution, at least the DB already exists. Also, Azure DevOps is not an option, we are using Gitlab CI, so eventually I want to have a solution that can run on CI/CD there.

答:
Not sure if this will help complete but here we go.

Instead of using a hand-written admin.py script, try using a yaml pipeline flow. For Gitlab, they have https://docs.gitlab.com/ee/ci/yaml/ that you can use to get started. From what you've indicated, I would recommend having several job steps in your yaml pipeline that will build and package your web and function apps. For deployment, you can make use of environments.  Have a look at https://docs.gitlab.com/ee/ci/multi_project_pipelines.html as well which illustrates how you can create downstream pipelines.

From a deployment standpoint, the current integration I've found between Azure and GitLab leaves me with two recommendations:

Leverage the script command of yaml to continue zipping your artifacts use Azure CLI (I would assume you can install the tools during the pipeline) to zip deploy.

Keep your code inside the GitLab repo and utilize Azure Pipelines to handle the CI/CD for you.

I hope you find this helpful.


问:
react limits the number of renders
in react I am displaying products I.E.

{renderPosts.map((item, index) => (
                ...

now, in each product, there is a button to delete that product, inside a button I have onclick that calls sweetAlert to delete particular product:

```<code><Button
  color="danger"
  simple
  justIcon
  onClick={warningWithConfirmMessage}
 >
</code>```

Everything works fine like that... but if I want to pass ID of the product that has to be deleted...

```<code><Button
  color="danger"
  simple
  justIcon
  onClick={warningWithConfirmMessage(item.postId)}
 >
</code>```

Now I am having error:

Too many re-renders. React limits the number of renders to prevent an infinite loop.

How I can pass anything to function... anybody

Thanks in advance!

答:
The new onClick handler you're passing is calling the warningWithConfirmMessage every time it renders. To pass the function as a handler function instead of calling it, use:

```<code>onClick={() => warningWithConfirmMessage(item.postId)}
</code>```

Title: react limits the number of renders

Body:
in react I am displaying products I.E.

{renderPosts.map((item, index) => (
                ...

now, in each product, there is a button to delete that product, inside a button I have onclick that calls sweetAlert to delete particular product:

<Button
  color="danger"
  simple
  justIcon
  onClick={warningWithConfirmMessage}
 >

Everything works fine like that... but if I want to pass ID of the product that has to be deleted...

<Button
  color="danger"
  simple
  justIcon
  onClick={warningWithConfirmMessage(item.postId)}
 >

Now I am having error:

Too many re-renders. React limits the number of renders to prevent an infinite loop.

How I can pass anything to function... anybody

Thanks in advance!

Body:
The new onClick handler you're passing is calling the warningWithConfirmMessage every time it renders. To pass the function as a handler function instead of calling it, use:

onClick={() => warningWithConfirmMessage(item.postId)}


问:
Why is an overloaded function with two arguments of type double called when passing a long long?
I wrote those two overloads:

```<code>int func(int, int) {
    return 1;
}

int func(double, double) {
    return 2;
}
</code>```

When I call them with the obvious two calling schemes, i.e. func(1, 1) and func(1.0, 1.0), the first and the second overloaded functions are called, respectively, and when I try to call func(1, 1.0) it gives me an error, but when I cast the 1 to a long long, I don't get an error, and the second overload is the one called.

```<code>#include <iostream>
int main()
{
    std::cout << func(1, 1); // outputs 1.
    std::cout << func(1.0, 1.0); // outputs 2.
    // std::cout << func(1, 1.0); // erroneous.
    std::cout << func((long long)1, 1.0); // outputs 2.
}
</code>```

Why is this the case? At first, I thought it was because of some promotion, but I tried a third overload with two floats and I could not get it to be called by calling it like func((int)1, 1.0f). I don't know why wouldn't it be the same, and I don't know why the second overload was called when a long long was passed.

答:
Which function from an overload set is chosen to be called (i.e. overload resolution) depends (in part) on how many arguments of the function call must go through an implicit conversion, and what kind of conversion is needed.

The rules that are relevant to your example are:

For each pair of viable function F1 and F2, the implicit conversion sequences from the i-th argument to i-th parameter are ranked to determine which one is better.

F1 is determined to be a better function than F2 if implicit conversions for all arguments of F1 are not worse than the implicit conversions for all arguments of F2, and ... there is at least one argument of F1 whose implicit conversion is better than the corresponding implicit conversion for that argument of F2.

So given the overload set:

```<code>int func(int, int);        // #1
int func(double, double);  // #2
</code>```

Let's consider the following calls:

```<code>func(1, 1);    // perfect match for #1, so #1 is chosen

func(1., 1.);  // perfect match for #2, so #2 is chosen

func(1., 1);   // could call #1 by converting 1st argument to int
               // (floating-integral conversion)

               // could call #2 by converting 2nd argument to double
               // (floating-integral conversion)

               // error: ambiguous (equal number of conversions needed for both #1 and #2)

func(1ll, 1.); // could call #1 by converting both arguments to ints
               // (integral conversion for 1st argument, floating-integral conversion for 2nd argument)

               // could call #2 by converting just 1st argument to double
               // (floating-integral conversion for 1st argument)

               // for the 2nd parameter, #2 is ranked as a better choice,
               // since it has a better implicit conversion sequence for #2
               // and so #2 is chosen (even though both #1 and #2 are tied for the 1st argument)
</code>```

Now let's add a third overload into the mix:

```<code>int func(float, float);  // #3
</code>```

Now when you make the call:

```<code>func(1, 1.f);  // could call #1 by converting 2nd argument to int
               // (floating-integral conversion for 2nd argument)

               // could call #2 by converting 1st argument to double, and converting 2nd argument to double
               // (floating-integral conversion for 1st argument, and floating-point promotion for 2nd argument)

               // could call #3 by converting 1st argument to float
               // (floating-integral conversion for 1st argument)

               // error: ambiguous (equal number of conversions needed for #1, #2 and #3)
</code>```

Body:
I wrote those two overloads:

int func(int, int) {
    return 1;
}

int func(double, double) {
    return 2;
}

When I call them with the obvious two calling schemes, i.e. func(1, 1) and func(1.0, 1.0), the first and the second overloaded functions are called, respectively, and when I try to call func(1, 1.0) it gives me an error, but when I cast the 1 to a long long, I don't get an error, and the second overload is the one called.

#include <iostream>
int main()
{
    std::cout << func(1, 1); // outputs 1.
    std::cout << func(1.0, 1.0); // outputs 2.
    // std::cout << func(1, 1.0); // erroneous.
    std::cout << func((long long)1, 1.0); // outputs 2.
}

Why is this the case? At first, I thought it was because of some promotion, but I tried a third overload with two floats and I could not get it to be called by calling it like func((int)1, 1.0f). I don't know why wouldn't it be the same, and I don't know why the second overload was called when a long long was passed.

Body:
Which function from an overload set is chosen to be called (i.e. overload resolution) depends (in part) on how many arguments of the function call must go through an implicit conversion, and what kind of conversion is needed.

The rules that are relevant to your example are:

For each pair of viable function F1 and F2, the implicit conversion sequences from the i-th argument to i-th parameter are ranked to determine which one is better.

F1 is determined to be a better function than F2 if implicit conversions for all arguments of F1 are not worse than the implicit conversions for all arguments of F2, and ... there is at least one argument of F1 whose implicit conversion is better than the corresponding implicit conversion for that argument of F2.

So given the overload set:

int func(int, int);        // #1
int func(double, double);  // #2

Let's consider the following calls:

func(1, 1);    // perfect match for #1, so #1 is chosen

func(1., 1.);  // perfect match for #2, so #2 is chosen

func(1., 1);   // could call #1 by converting 1st argument to int
               // (floating-integral conversion)

               // could call #2 by converting 2nd argument to double
               // (floating-integral conversion)

               // error: ambiguous (equal number of conversions needed for both #1 and #2)

func(1ll, 1.); // could call #1 by converting both arguments to ints
               // (integral conversion for 1st argument, floating-integral conversion for 2nd argument)

               // could call #2 by converting just 1st argument to double
               // (floating-integral conversion for 1st argument)

               // for the 2nd parameter, #2 is ranked as a better choice,
               // since it has a better implicit conversion sequence for #2
               // and so #2 is chosen (even though both #1 and #2 are tied for the 1st argument)

Now let's add a third overload into the mix:

int func(float, float);  // #3

Now when you make the call:

func(1, 1.f);  // could call #1 by converting 2nd argument to int
               // (floating-integral conversion for 2nd argument)

               // could call #2 by converting 1st argument to double, and converting 2nd argument to double
               // (floating-integral conversion for 1st argument, and floating-point promotion for 2nd argument)

               // could call #3 by converting 1st argument to float
               // (floating-integral conversion for 1st argument)

               // error: ambiguous (equal number of conversions needed for #1, #2 and #3)


问:
DateTime.Now vs. DateTime.UtcNow
I've been wondering what exactly are the principles of how the two properties work. I know the second one is universal and basically doesn't deal with time zones, but can someone explain in detail how they work and which one should be used in what scenario?</p>

答:
DateTime.UtcNow tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer. DateTime.Now gives the date and time as it would appear to someone in your current locale.

I'd recommend using DateTime.Now whenever you're displaying a date to a human being - that way they're comfortable with the value they see - it's something that they can easily compare to what they see on their watch or clock. Use DateTime.UtcNow when you want to store dates or use them for later calculations that way (in a client-server model) your calculations don't become confused by clients in different time zones from your server or from each other.

OwnerDisplayName: Slavo

Title: DateTime.Now vs. DateTime.UtcNow

LastEditorDisplayName: Jedi Master Spooky

OwnerDisplayName: Blair Conrad


问:
XCode 4 Tutorials for Cocoa OS X Applications
There's obviously a lot of buzz around writing Cocoa Touch applications, but there doesn't seem to be much around creating applications for OS X apps using XCode 4.

Does anyone know of any resources that cover OS X Application Development using XCode 4? Are tutorials for XCode 3 usable for XCode 4 Development?

Thanks.

答: Have you looked at developer.apple.com There is more than enough there to get you started.</p>


问:
Laravel Forge Custom VPS on Ubuntu 18.04
I want to provision a new custom vps in Laravel Forge. The client I'm working for only has a cloud server with Ubuntu 18.04 running. The Laravel Forge docs forcing me to use Ubuntu 20.04 - but unfortunately that's not possible at the moment.

Is there any solution to use Laravel Forge with a Ubuntu 18.04 or do we have to move on to a hosting provider who provides Ubuntu 20.04?

Thanks for your help and sorry for my bad english.
Cheers
Mario

答:
I just reached out the the Laravel Forge support with the exact same question. The answer is no, you have to upgrade to 20.04.

https://twitter.com/jbrooksuk/status/1263539840878022656


问:
SOAP:1.027 SRT: Serialization / Deserialization failed in ABAP Proxy
I have to create a consumer proxy in SAP, the proxy generation is OK (or no errors were reported), but when i tried yo consume the proxy (SE80), i have the next error:

SOAP:1.027 SRT: Serialization / Deserialization failed

System expected a value for the type g.

If i continue, i have the response, but when i tried to call the customer service in a report, i have the error and i can't continue.
In a report, when i tried yo consume the proxy using this code, i have the same error, and i don't have response:

```<code>CREATE OBJECT proxy
  EXPORTING
    logical_port_name = 'LOGICAL_01'.

CALL METHOD proxy->proccess_check_status_invoice
  EXPORTING
    process_check_status_invoice   = input
  IMPORTING
    process_check_status_invoice_r = output.
</code>```

Whow can i solve this error?

Thanks,

答: Type g is usually the constant for the TYPEKIND of STRING. My guess is you are binding values that are CHARs instead of the STRING datatype.</p>

Body:
I have to create a consumer proxy in SAP, the proxy generation is OK (or no errors were reported), but when i tried yo consume the proxy (SE80), i have the next error:

SOAP:1.027 SRT: Serialization / Deserialization failed

System expected a value for the type g.

If i continue, i have the response, but when i tried to call the customer service in a report, i have the error and i can't continue.
In a report, when i tried yo consume the proxy using this code, i have the same error, and i don't have response:

CREATE OBJECT proxy
  EXPORTING
    logical_port_name = 'LOGICAL_01'.

CALL METHOD proxy->proccess_check_status_invoice
  EXPORTING
    process_check_status_invoice   = input
  IMPORTING
    process_check_status_invoice_r = output.

Whow can i solve this error?

Thanks,


问:
Why isn't applied CSS selector

.colored p{
   color: red;
}

article > .colored{
   color:powderblue;
}

.blue{
   color: white;
}
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <div class="colored">
      <p>hello</p>
      <p class="blue">hello</p>
      <div>
        <p>hello</p>
      </div>
    </div>
    <p>hello</p>
    <article>
      <div class="colored">hello</div>
    </article>
</body>
</html></code>```

Why isn't the blue selector applied???
It's applied when I changed it(p.blue).
I don`t know the difference between first case and second case ..

答:
What is happening in second case is, p tag have parent class colored and that is why it is applying css of parent class to second p tag. Even though you have provided class blue but still parent class have high precedence.

You can use !important override precedence for color property in class blue. The !important instruction has the highest precedence of all precedence factors.

.colored p{
   color: red;
}

article > .colored{
   color:powderblue;
}

.blue{
   color: green!important;
}
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <div class="colored">
      <p>hello</p>
      <p class="blue">hello</p>
      <div>
        <p>hello</p>
      </div>
    </div>
    <p>hello</p>
    <article>
      <div class="colored">hello</div>
    </article>
</body>
</html></code>```

Title: Why isn't applied CSS selector

Body:
.colored p{
   color: red;
}

article > .colored{
   color:powderblue;
}

.blue{
   color: white;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

hello

hello

hello

hello

hello

Why isn't the blue selector applied???
It's applied when I changed it(p.blue).
I don`t know the difference between first case and second case ..

Body:
What is happening in second case is, p tag have parent class colored and that is why it is applying css of parent class to second p tag. Even though you have provided class blue but still parent class have high precedence.

You can use !important override precedence for color property in class blue. The !important instruction has the highest precedence of all precedence factors.

.colored p{
   color: red;
}

article > .colored{
   color:powderblue;
}

.blue{
   color: green!important;
}

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <div class="colored">
      <p>hello</p>
      <p class="blue">hello</p>
      <div>
        <p>hello</p>
      </div>
    </div>
    <p>hello</p>
    <article>
      <div class="colored">hello</div>
    </article>
</body>
</html>


问:
Scroll if element is not visible
how to determine, using jquery, if the element is visible on the current page view. I'd like to add a comment functionality, which works like in facebook, where you only scroll to element if it's not currently visible. By visible, I mean that it is not in the current page view, but you can scroll to the element.</p>

答:
Live Demo

Basically you just check the position of the element to see if its within the windows viewport.

```<code>function checkIfInView(element){
    var offset = element.offset().top - $(window).scrollTop();

    if(offset > window.innerHeight){
        // Not in view so scroll to it
        $('html,body').animate({scrollTop: offset}, 1000);
        return false;
    }
   return true;
}
</code>```

Title: Scroll if element is not visible

Body:
Live Demo

Basically you just check the position of the element to see if its within the windows viewport.

function checkIfInView(element){
    var offset = element.offset().top - $(window).scrollTop();

    if(offset > window.innerHeight){
        // Not in view so scroll to it
        $('html,body').animate({scrollTop: offset}, 1000);
        return false;
    }
   return true;
}


问:
Expire unix or time() code after x hours
I am trying to create a forgot password feature which will expire the link created after x hours. So I am storing time() data in database value when a user requests a password reset. So how can I expire it?

答: You're probably having a table entry with a reset link, just add a date field to it, and then either include a WHERE expiredate<NOW() or clean the table from time to time with a simple DELETE from table WHERE expiredata<NOW().


问:
replace element with string in an array of integers in java
I'm trying to replace specific elements of an array of integers, based on some condition, with strings. I'm identifying the int elements which has to be replaced by using modulus operator.

```<code>class Source {
    public static void main(String args[]) {
        int[] numbers = { 1, 2, 34, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
        fizzBuzz(numbers);
    }

    public static void fizzBuzz(int[] numbers) {
        // Write the function body here
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] % 3 == 0 && numbers[i] % 5 == 0) {
                numbers[i] = "FizzBuzz";
            } else if (numbers[i] % 5 == 0) {
                numbers[i] = "Buzz";
            } else if (numbers[i] % 3 == 0) {
                numbers[i] = "Fizz";
            } else {
                numbers[i] = numbers[i];
            }
            System.out.print(numbers[i] + " ");
        }
    }
}
</code>```

I'm getting the error:

```<code>Source.java:11: error: inconvertible types
            numbers[i] = (int) "FizzBuzz";
                               ^
  required: int
  found:    String
Source.java:13: error: inconvertible types
            numbers[i] = (int) "Buzz";
                               ^
  required: int
  found:    String
Source.java:15: error: inconvertible types
            numbers[i] = (int) "Fizz";
                               ^
  required: int
  found:    String
3 errors
</code>```

答:
I'm trying to replace specific elements of an array of integers, based on some condition, with strings.

In this particular case, the easiest way is to store the integers in the original array as Objects.  Then you just need to cast them to an int to work with them.

```<code>public static void main(String args[]) {
    Object[] numbers = {1,2,34,5,6,7,8,9,10,11,12,13,14,15};
    fizzBuzz(numbers);
    System.out.println(Arrays.toString(numbers));
}

public static void fizzBuzz(Object[] numbers) {
    int i = 0;
    for (Object o : numbers) {
        int n = (int)o;
        boolean t3 = n % 3 == 0;
        boolean t5 = n % 5 == 0;

        numbers[i] = t3 && t5 ? "FizzBuzz" : t3 ? "Fizz" :
                t5 ? "Buzz" : n;
        i++;
    }
}
</code>```

Prints

```<code>[1, 2, 34, Fizz, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz]
</code>```

Points to consider.

establish the boolean results once and then simply apply them to a chained ternary operator. The ternary operator a?b:c means if a is true then b, else c

since this uses Objects there is no issue of putting the result (either String or int) back into the array

and since you are using only integers to begin with, you won't get a class cast exception when doing (int)o

Body:
I'm trying to replace specific elements of an array of integers, based on some condition, with strings. I'm identifying the int elements which has to be replaced by using modulus operator.

class Source {
    public static void main(String args[]) {
        int[] numbers = { 1, 2, 34, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
        fizzBuzz(numbers);
    }

    public static void fizzBuzz(int[] numbers) {
        // Write the function body here
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] % 3 == 0 && numbers[i] % 5 == 0) {
                numbers[i] = "FizzBuzz";
            } else if (numbers[i] % 5 == 0) {
                numbers[i] = "Buzz";
            } else if (numbers[i] % 3 == 0) {
                numbers[i] = "Fizz";
            } else {
                numbers[i] = numbers[i];
            }
            System.out.print(numbers[i] + " ");
        }
    }
}

I'm getting the error:

Source.java:11: error: inconvertible types
            numbers[i] = (int) "FizzBuzz";
                               ^
  required: int
  found:    String
Source.java:13: error: inconvertible types
            numbers[i] = (int) "Buzz";
                               ^
  required: int
  found:    String
Source.java:15: error: inconvertible types
            numbers[i] = (int) "Fizz";
                               ^
  required: int
  found:    String
3 errors

Body:
I'm trying to replace specific elements of an array of integers, based on some condition, with strings.

In this particular case, the easiest way is to store the integers in the original array as Objects.  Then you just need to cast them to an int to work with them.

public static void main(String args[]) {
    Object[] numbers = {1,2,34,5,6,7,8,9,10,11,12,13,14,15};
    fizzBuzz(numbers);
    System.out.println(Arrays.toString(numbers));
}

public static void fizzBuzz(Object[] numbers) {
    int i = 0;
    for (Object o : numbers) {
        int n = (int)o;
        boolean t3 = n % 3 == 0;
        boolean t5 = n % 5 == 0;

        numbers[i] = t3 && t5 ? "FizzBuzz" : t3 ? "Fizz" :
                t5 ? "Buzz" : n;
        i++;
    }
}

Prints

[1, 2, 34, Fizz, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz]

Points to consider.

establish the boolean results once and then simply apply them to a chained ternary operator. The ternary operator a?b:c means if a is true then b, else c

since this uses Objects there is no issue of putting the result (either String or int) back into the array

and since you are using only integers to begin with, you won't get a class cast exception when doing (int)o


问:
Django Celery Logging Best Practice
I'm trying to get Celery logging working with Django. I have logging set-up in settings.py to go to console (that works fine as I'm hosting on Heroku). At the top of each module, I have:

```<code>import logging
logger = logging.getLogger(__name__)
</code>```

And in my tasks.py, I have:

```<code>from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
</code>```

That works fine for logging calls from a task and I get output like this:

```<code>2012-11-13T18:05:38+00:00 app[worker.1]: [2012-11-13 18:05:38,527: INFO/PoolWorker-2] Syc feed is starting
</code>```

But if that task then calls a method in another module, e.g. a queryset method, I get duplicate log entries, e.g.

```<code>2012-11-13T18:00:51+00:00 app[worker.1]: [INFO] utils.generic_importers.ftp_processor process(): File xxx.csv already imported. Not downloaded
2012-11-13T18:00:51+00:00 app[worker.1]: [2012-11-13 18:00:51,736: INFO/PoolWorker-6] File xxx.csv already imported. Not downloaded
</code>```

I think I could use

```<code>CELERY_HIJACK_ROOT_LOGGER = False
</code>```

to just use the Django logging but this didn't work when I tried it and even if I did get it to work, I would lose the "PoolWorker-6" bit which I do want. (Incidentally, I can't figure out how to get the task name to display in the log entry from Celery, as the docs seems to indicate that it should).

I suspect I'm missing something simple here.

答:
Maybe it will help someone, my problem was to send all celery logs to graylog. Here is solution.

celery.py:

```<code>app.config_from_object('django.conf:settings', namespace='CELERY')

# ====== Magic starts
from celery.signals import setup_logging

@setup_logging.connect
def config_loggers(*args, **kwargs):
    from logging.config import dictConfig
    from django.conf import settings
    dictConfig(settings.LOGGING)
# ===== Magic ends

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
</code>```

settings.py:

```<code>LOGGING = {
    'version': 1,
    'handlers': {
        'graypy': {
            'class': 'graypy.GELFTCPHandler',
            'host': GRAYLOG_HOST,
            'port': GRAYLOG_PORT,
        }
    },
    'loggers': {
        'my_project': {
            'handlers': ['graypy'],
            'level': 'INFO',
        },
        # ====== Magic starts
        'celery': {
            'handlers': ['graypy'],
            'level': 'INFO',
        }
        # ===== Magic ends
    }
}
</code>```

Title: Django Celery Logging Best Practice

Body:
I'm trying to get Celery logging working with Django. I have logging set-up in settings.py to go to console (that works fine as I'm hosting on Heroku). At the top of each module, I have:

import logging
logger = logging.getLogger(__name__)

And in my tasks.py, I have:

from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)

That works fine for logging calls from a task and I get output like this:

2012-11-13T18:05:38+00:00 app[worker.1]: [2012-11-13 18:05:38,527: INFO/PoolWorker-2] Syc feed is starting

But if that task then calls a method in another module, e.g. a queryset method, I get duplicate log entries, e.g.

2012-11-13T18:00:51+00:00 app[worker.1]: [INFO] utils.generic_importers.ftp_processor process(): File xxx.csv already imported. Not downloaded
2012-11-13T18:00:51+00:00 app[worker.1]: [2012-11-13 18:00:51,736: INFO/PoolWorker-6] File xxx.csv already imported. Not downloaded

I think I could use

CELERY_HIJACK_ROOT_LOGGER = False

to just use the Django logging but this didn't work when I tried it and even if I did get it to work, I would lose the "PoolWorker-6" bit which I do want. (Incidentally, I can't figure out how to get the task name to display in the log entry from Celery, as the docs seems to indicate that it should).

I suspect I'm missing something simple here.

Body:
Maybe it will help someone, my problem was to send all celery logs to graylog. Here is solution.

celery.py:

app.config_from_object('django.conf:settings', namespace='CELERY')

# ====== Magic starts
from celery.signals import setup_logging

@setup_logging.connect
def config_loggers(*args, **kwargs):
    from logging.config import dictConfig
    from django.conf import settings
    dictConfig(settings.LOGGING)
# ===== Magic ends

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()

settings.py:

LOGGING = {
    'version': 1,
    'handlers': {
        'graypy': {
            'class': 'graypy.GELFTCPHandler',
            'host': GRAYLOG_HOST,
            'port': GRAYLOG_PORT,
        }
    },
    'loggers': {
        'my_project': {
            'handlers': ['graypy'],
            'level': 'INFO',
        },
        # ====== Magic starts
        'celery': {
            'handlers': ['graypy'],
            'level': 'INFO',
        }
        # ===== Magic ends
    }
}


问:
Golang Postgres syntax error in If/Else statement
I have a postgres exec string. I have rows of users, with arrays of weight lifting data. I want to either update the current day log (ie replace last array element if there's already a lift logged for today), or append the lifting data to these arrays.

```<code>BEGIN
IF (SELECT date[array_upper(date, 1)] FROM userdata WHERE email = $8) = $7 THEN
UPDATE userdata SET age = $1,
weight[array_upper(weight, 1)] = $2,
deadlift[array_upper(deadlift, 1)] = $3,
squat[array_upper(squat, 1)] = $4,
bench[array_upper(bench, 1)] = $5,
overhead[array_upper(overhead, 1)] = $6,
WHERE email = $8;
ELSE
UPDATE userdata SET age = $1,
weight = array_append(weight, $2),
deadlift = array_append(deadlift, $3),
squat = array_append(squat, $4),
bench = array_append(bench, $5),
overhead = array_append(overhead, $6),
date = array_append(date, $7)
WHERE email = $8;
END IF;
END;
</code>```

First checks if date (ie last date array element) == today's date, if true, THEN set last element to given values.

ELSE, append given values to the ends of all these arrays

My Golang code is the following:

```<code>_, err := d.conn.Exec(context.Background(), execstring, user.Age, user.Weight, user.Deadlift, user.Squat,
        user.Bench, user.Overhead, fmt.Sprint(time.Now().Date()), user.Email)
</code>```

Executes execstring (the 1st code block), with the following variables.

Error:  ERROR: syntax error at or near "IF"

New to both golang and postgres, would love some help (problem likely lies with my execstring)

EDIT (CASE VERSION BELOW):

```<code>SELECT date[array_upper(date, 1)]
CASE
WHEN date[array_upper(date,1)] = $7 THEN
UPDATE userdata SET age = $1,
weight[array_upper(weight, 1)] = $2,
deadlift[array_upper(deadlift, 1)] = $3,
squat[array_upper(squat, 1)] = $4,
bench[array_upper(bench, 1)] = $5,
overhead[array_upper(overhead, 1)] = $6,
WHERE email = $8;
ELSE
UPDATE userdata SET age = $1,
weight = array_append(weight, $2),
deadlift = array_append(deadlift, $3),
squat = array_append(squat, $4),
bench = array_append(bench, $5),
overhead = array_append(overhead, $6),
date = array_append(date, $7)
WHERE email = $8;
END
FROM userdata WHERE email = $8
</code>```

Error: ERROR: syntax error at or near "CASE"

答:
Here is what I did to fix my problem (hope it helps anybody else trying to do something similar)

It seems that CASE can't be used to decide which statement to run, but rather, seems to only decide which text to put into the query/exec string. Therefore, I had to move things around to do this, using CASE to decide what to set my arrays equal to, rather than deciding what operation to perform on the arrays.

```<code>UPDATE userdata
SET age = $1,
weight = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(weight, weight[array_upper(weight, 1)], $2)
ELSE array_append(weight, $2) END,
deadlift = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(deadlift, deadlift[array_upper(deadlift, 1)], $3)
ELSE array_append(deadlift, $3) END,
squat = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(squat, squat[array_upper(squat, 1)], $4)
ELSE array_append(squat, $4) END,
bench = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(bench, bench[array_upper(bench, 1)], $5)
ELSE array_append(bench, $5) END,
overhead = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(overhead, overhead[array_upper(overhead, 1)], $6)
ELSE array_append(overhead, $6) END,
date = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(date, date[array_upper(date, 1)], $7)
ELSE array_append(date, $7) END
WHERE email = $8;
</code>```

Body:
I have a postgres exec string. I have rows of users, with arrays of weight lifting data. I want to either update the current day log (ie replace last array element if there's already a lift logged for today), or append the lifting data to these arrays.

BEGIN
IF (SELECT date[array_upper(date, 1)] FROM userdata WHERE email = $8) = $7 THEN
UPDATE userdata SET age = $1,
weight[array_upper(weight, 1)] = $2,
deadlift[array_upper(deadlift, 1)] = $3,
squat[array_upper(squat, 1)] = $4,
bench[array_upper(bench, 1)] = $5,
overhead[array_upper(overhead, 1)] = $6,
WHERE email = $8;
ELSE
UPDATE userdata SET age = $1,
weight = array_append(weight, $2),
deadlift = array_append(deadlift, $3),
squat = array_append(squat, $4),
bench = array_append(bench, $5),
overhead = array_append(overhead, $6),
date = array_append(date, $7)
WHERE email = $8;
END IF;
END;

First checks if date (ie last date array element) == today's date, if true, THEN set last element to given values.

ELSE, append given values to the ends of all these arrays

My Golang code is the following:

_, err := d.conn.Exec(context.Background(), execstring, user.Age, user.Weight, user.Deadlift, user.Squat,
        user.Bench, user.Overhead, fmt.Sprint(time.Now().Date()), user.Email)

Executes execstring (the 1st code block), with the following variables.

Error:  ERROR: syntax error at or near "IF"

New to both golang and postgres, would love some help (problem likely lies with my execstring)

EDIT (CASE VERSION BELOW):

SELECT date[array_upper(date, 1)]
CASE
WHEN date[array_upper(date,1)] = $7 THEN
UPDATE userdata SET age = $1,
weight[array_upper(weight, 1)] = $2,
deadlift[array_upper(deadlift, 1)] = $3,
squat[array_upper(squat, 1)] = $4,
bench[array_upper(bench, 1)] = $5,
overhead[array_upper(overhead, 1)] = $6,
WHERE email = $8;
ELSE
UPDATE userdata SET age = $1,
weight = array_append(weight, $2),
deadlift = array_append(deadlift, $3),
squat = array_append(squat, $4),
bench = array_append(bench, $5),
overhead = array_append(overhead, $6),
date = array_append(date, $7)
WHERE email = $8;
END
FROM userdata WHERE email = $8

Error: ERROR: syntax error at or near "CASE"

Body:
Here is what I did to fix my problem (hope it helps anybody else trying to do something similar)

It seems that CASE can't be used to decide which statement to run, but rather, seems to only decide which text to put into the query/exec string. Therefore, I had to move things around to do this, using CASE to decide what to set my arrays equal to, rather than deciding what operation to perform on the arrays.

UPDATE userdata
SET age = $1,
weight = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(weight, weight[array_upper(weight, 1)], $2)
ELSE array_append(weight, $2) END,
deadlift = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(deadlift, deadlift[array_upper(deadlift, 1)], $3)
ELSE array_append(deadlift, $3) END,
squat = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(squat, squat[array_upper(squat, 1)], $4)
ELSE array_append(squat, $4) END,
bench = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(bench, bench[array_upper(bench, 1)], $5)
ELSE array_append(bench, $5) END,
overhead = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(overhead, overhead[array_upper(overhead, 1)], $6)
ELSE array_append(overhead, $6) END,
date = CASE WHEN date[array_upper(date,1)] = $7 THEN array_replace(date, date[array_upper(date, 1)], $7)
ELSE array_append(date, $7) END
WHERE email = $8;


问:
In Habanero how would I restrict the number of objects returned from a database
I need to restrict the number of customer bo's returned from the database as I am searching for a partial customer name and at the moment I get over 600 bo's when searching for 'a'.  I would like to restrict this to 20.  My code at the moment is </p>

```<code>    public IEnumerable<Customer> FindCustomers(string partialCustomerName)
    {
        if (string.IsNullOrEmpty(partialCustomerName))
          throw new ArgumentException("partialCustomerName must be at least one character long");
        var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
        return Broker.GetBusinessObjectCollection<Customer>(criteria);
    }
</code>```

答:
Till is on the right track there, but did not give the correct syntax.
The broker is used to load collections from the current Data Accessor, not for creating new ones. So the code would then be:

```<code>public IEnumerable<Customer> FindCustomers(string partialCustomerName)
{
    if (string.IsNullOrEmpty(partialCustomerName))
      throw new ArgumentException("partialCustomerName must be at least one character long");

    var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
    int totalRecords;
    var col = new BusinessObjectCollection<Customer>();
    col.LoadWithLimit(criteria, "CustomerName", 0, 20, ref totalRecords);
    return col;
}
</code>```

That should do it!
Please award the answer to Till, not me. He did the most research. I just corrected the syntax :)

EDIT:
After comments below about the ugly API, I will include suggested changes to the method to make it look cleaner (Thanks for your suggestion @GloryDev):

```<code>public IEnumerable<Customer> FindCustomers(string partialCustomerName)
{
    if (string.IsNullOrEmpty(partialCustomerName))
      throw new ArgumentException("partialCustomerName must be at least one character long");
    var col = new BusinessObjectCollection<Customer>();
    col.LoadWithLimit("CustomerName Like " + partialCustomerName + "%", "CustomerName", 20);
    return col;
}
</code>```

The Second parameter is the field to order by, which is necessary for a fetch with limits to make any sense. Hope this helps.

Body:
I need to restrict the number of customer bo's returned from the database as I am searching for a partial customer name and at the moment I get over 600 bo's when searching for 'a'.  I would like to restrict this to 20.  My code at the moment is

    public IEnumerable<Customer> FindCustomers(string partialCustomerName)
    {
        if (string.IsNullOrEmpty(partialCustomerName))
          throw new ArgumentException("partialCustomerName must be at least one character long");
        var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
        return Broker.GetBusinessObjectCollection<Customer>(criteria);
    }

Body:
Till is on the right track there, but did not give the correct syntax.
The broker is used to load collections from the current Data Accessor, not for creating new ones. So the code would then be:

public IEnumerable<Customer> FindCustomers(string partialCustomerName)
{
    if (string.IsNullOrEmpty(partialCustomerName))
      throw new ArgumentException("partialCustomerName must be at least one character long");

    var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
    int totalRecords;
    var col = new BusinessObjectCollection<Customer>();
    col.LoadWithLimit(criteria, "CustomerName", 0, 20, ref totalRecords);
    return col;
}

That should do it!
Please award the answer to Till, not me. He did the most research. I just corrected the syntax :)

EDIT:
After comments below about the ugly API, I will include suggested changes to the method to make it look cleaner (Thanks for your suggestion @GloryDev):

public IEnumerable<Customer> FindCustomers(string partialCustomerName)
{
    if (string.IsNullOrEmpty(partialCustomerName))
      throw new ArgumentException("partialCustomerName must be at least one character long");
    var col = new BusinessObjectCollection<Customer>();
    col.LoadWithLimit("CustomerName Like " + partialCustomerName + "%", "CustomerName", 20);
    return col;
}

The Second parameter is the field to order by, which is necessary for a fetch with limits to make any sense. Hope this helps.


问:
Parsing values in and out a def functions
I am having a bit of a struggle with parsing values between these def functions. The base code getSensorData() and main() works fine, values are read from the sensor and sent to thingspeak. However, I wanted to add a calculation function called calcDewPoint() to the original code to calculate dewpoint from the sensor values (RH, T) but it seems that the code gets stuck :/

Output from terminal when I run the code as is:

```<code>starting...
sense1
sense2
dewpoint1
gamma1
exiting.
</code>```

Temperature/Humidity monitor using Raspberry Pi and DHT22. Data is displayed at thingspeak.com
Change list 02/06/2020
Add dewpoint calculations

```<code>import sys
import RPi.GPIO as GPIO
from time import sleep
import Adafruit_DHT
import urllib2
import math #(using numPy instead of math lib)
#import numPy as np
#import constant (Create a *.py file to be able to use constant accross multiple projects)

#Constant Variables - Magnus Parameters
m = 17.62 #Mass Constant (Water Vapour)
Tn = 243.12 #Tempreture Constant
Ah = 6.112 #hPa Pressure Constant
Ak = 0.611 #kPa Pressure Constant
K = 273.15 #Kelvin constant
Ta = 216.7 #Tempreture Constant

myAPI = 'FZZHL7N2R2AXXXXX'

def getSensorData():
   print 'sense1'
   RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 17)
   print 'sense2'
   return (str(RH), str(T))

def calcDewPoint(RH, T):
   print 'dewpoint1'
   Td = (K * gamma(RH, T)) / (m - gamma(RH, T))
   print 'dewpoint2'
   return str(Td)

def gamma(RH, T):
   print 'gamma1'
   g = math.log(RH/100.0) + ((m * T) / (c + T))
   print 'gamma2'
   return str(g)

def main():
   print 'starting...'
   baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
   while True:
       try:
           RH, T = getSensorData() #Call function to Read DHT22 sensor conencted to RaspberryPi
           Td = calcDewPoint(RH, T) #Call function to calculate dewpoint
           f = urllib2.urlopen(baseURL + "&field1=%s&field2=%s&field3=%s" % (RH, T, Td))
           print f.read()
           f.close()
           sleep(60) #uploads DHT22 sensor values every 1 minutes
       except:
           print 'exiting.'
           break
# call main
if __name__ == '__main__':
   main()
</code>```

答: Your variable c is not defined. When you call calcDewPoint, it then calls gamma, which tries to run your math expression. However, c does not exist at that point.

Body:
I am having a bit of a struggle with parsing values between these def functions. The base code getSensorData() and main() works fine, values are read from the sensor and sent to thingspeak. However, I wanted to add a calculation function called calcDewPoint() to the original code to calculate dewpoint from the sensor values (RH, T) but it seems that the code gets stuck :/

Output from terminal when I run the code as is:

starting...
sense1
sense2
dewpoint1
gamma1
exiting.

Temperature/Humidity monitor using Raspberry Pi and DHT22. Data is displayed at thingspeak.com
Change list 02/06/2020
Add dewpoint calculations

import sys
import RPi.GPIO as GPIO
from time import sleep
import Adafruit_DHT
import urllib2
import math #(using numPy instead of math lib)
#import numPy as np
#import constant (Create a *.py file to be able to use constant accross multiple projects)

#Constant Variables - Magnus Parameters
m = 17.62 #Mass Constant (Water Vapour)
Tn = 243.12 #Tempreture Constant
Ah = 6.112 #hPa Pressure Constant
Ak = 0.611 #kPa Pressure Constant
K = 273.15 #Kelvin constant
Ta = 216.7 #Tempreture Constant

myAPI = 'FZZHL7N2R2AXXXXX'

def getSensorData():
   print 'sense1'
   RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 17)
   print 'sense2'
   return (str(RH), str(T))

def calcDewPoint(RH, T):
   print 'dewpoint1'
   Td = (K * gamma(RH, T)) / (m - gamma(RH, T))
   print 'dewpoint2'
   return str(Td)

def gamma(RH, T):
   print 'gamma1'
   g = math.log(RH/100.0) + ((m * T) / (c + T))
   print 'gamma2'
   return str(g)

def main():
   print 'starting...'
   baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
   while True:
       try:
           RH, T = getSensorData() #Call function to Read DHT22 sensor conencted to RaspberryPi
           Td = calcDewPoint(RH, T) #Call function to calculate dewpoint
           f = urllib2.urlopen(baseURL + "&field1=%s&field2=%s&field3=%s" % (RH, T, Td))
           print f.read()
           f.close()
           sleep(60) #uploads DHT22 sensor values every 1 minutes
       except:
           print 'exiting.'
           break
# call main
if __name__ == '__main__':
   main()


问:
How can I trigger a process after a returned publisher would be subscribed?
I have a function that returns a publisher. This publisher gives the results of a background process. I only want to trigger the background process when the publisher would be subscribed, so that no results are lost. The background process can update its results many times, so the variant with Future is not suitable.

```<code>private let passthroughSubject = PassthroughSubject<Data, Error>()

// This function will be used outside.
func fetchResults() -> AnyPublisher<Data, Error> {
     return passthroughSubject
     .eraseToAnyPublisher()
     .somehowTriggerTheBackgroundProcess()
}

extension MyModule: MyDelegate {
     func didUpdateResult(newResult: Data) {
          self.passthroughSubject.send(newResult)
     }
}
</code>```

What have I tried?

Future:

```<code>Future<Data, Error> { [weak self] promise in
     self?.passthroughSubject
          .sink(receiveCompletion: { completion in
               // My logic
          }, receiveValue: { value in
               // My logic
          })
          .store(in: &self.cancellableSet)
      self?.triggerBackgroundProcess()
}.eraseToAnyPublisher()
</code>```

Works the way I want but the subscriber is called only once (logical).

Deffered:

```<code>Deferred<AnyPublisher<Data, Error>>(createPublisher: { [weak self] in
   defer {
      self?.triggerBackgroundProcess()
   }
   return passthroughSubject.eraseToAnyPublisher()
}
</code>```

Debugger shows that everything is correct: first return then trigger but the subscriber is not called for the first time.

receiveSubscription:

```<code>passthroughSubject
.handleEvents(receiveSubscription: { [weak self] subscription in
   self?.triggerBackgroundProcess()
})
.eraseToAnyPublisher()
</code>```

The same effect as with Deffered.

Is it even possible what I want to achieve?
Or, it is better to create a public publisher subscribe it and receive results from background process. And the fetchResults() function doesn't return anything?

Thanks in advance for your help.

答:
You can write your own type that conforms to Publisher and wraps a PassthroughSubject. In your implementation, you can start the background process when you get a subscription.

```<code>public struct MyPublisher: Publisher {
    public typealias Output = Data
    public typealias Failure = Error

    public func receive<Downstream: Subscriber>(subscriber: Downstream)
        where Downstream.Input == Output, Downstream.Failure == Failure
    {
        let subject = PassthroughSubject<Output, Failure>()
        subject.subscribe(subscriber)

        startBackgroundProcess(subject: subject)
    }

    private func startBackgroundProcess(subject: PassthroughSubject<Output, Failure>) {
        DispatchQueue.global(qos: .utility).async {
            print("background process running")
            subject.send(Data())
            subject.send(completion: .finished)
        }
    }
}
</code>```

Note that this publisher starts a new background process for each subscriber. That is a common implementation. For example URLSession.DataTaskPublisher issues a new request for each subscriber. If you want multiple subscribers to share the output of a single request, you can use the .multicast operator, add multiple subscribers, and then .connect() the multicast publisher to start the background process once:

```<code>let pub = MyPublisher().multicast { PassthroughSubject() }
pub.sink(...).store(in: &tickets) // first subscriber
pub.sink(...).store(in: &tickets) // second subscriber
pub.connect().store(in: &tickets) // start the background process
</code>```

Body:
I have a function that returns a publisher. This publisher gives the results of a background process. I only want to trigger the background process when the publisher would be subscribed, so that no results are lost. The background process can update its results many times, so the variant with Future is not suitable.

private let passthroughSubject = PassthroughSubject<Data, Error>()

// This function will be used outside.
func fetchResults() -> AnyPublisher<Data, Error> {
     return passthroughSubject
     .eraseToAnyPublisher()
     .somehowTriggerTheBackgroundProcess()
}

extension MyModule: MyDelegate {
     func didUpdateResult(newResult: Data) {
          self.passthroughSubject.send(newResult)
     }
}

What have I tried?

Future:

Future<Data, Error> { [weak self] promise in
     self?.passthroughSubject
          .sink(receiveCompletion: { completion in
               // My logic
          }, receiveValue: { value in
               // My logic
          })
          .store(in: &self.cancellableSet)
      self?.triggerBackgroundProcess()
}.eraseToAnyPublisher()

Works the way I want but the subscriber is called only once (logical).

Deffered:

Deferred<AnyPublisher<Data, Error>>(createPublisher: { [weak self] in
   defer {
      self?.triggerBackgroundProcess()
   }
   return passthroughSubject.eraseToAnyPublisher()
}

Debugger shows that everything is correct: first return then trigger but the subscriber is not called for the first time.

receiveSubscription:

passthroughSubject
.handleEvents(receiveSubscription: { [weak self] subscription in
   self?.triggerBackgroundProcess()
})
.eraseToAnyPublisher()

The same effect as with Deffered.

Is it even possible what I want to achieve?
Or, it is better to create a public publisher subscribe it and receive results from background process. And the fetchResults() function doesn't return anything?

Thanks in advance for your help.

Body:
You can write your own type that conforms to Publisher and wraps a PassthroughSubject. In your implementation, you can start the background process when you get a subscription.

public struct MyPublisher: Publisher {
    public typealias Output = Data
    public typealias Failure = Error

    public func receive<Downstream: Subscriber>(subscriber: Downstream)
        where Downstream.Input == Output, Downstream.Failure == Failure
    {
        let subject = PassthroughSubject<Output, Failure>()
        subject.subscribe(subscriber)

        startBackgroundProcess(subject: subject)
    }

    private func startBackgroundProcess(subject: PassthroughSubject<Output, Failure>) {
        DispatchQueue.global(qos: .utility).async {
            print("background process running")
            subject.send(Data())
            subject.send(completion: .finished)
        }
    }
}

Note that this publisher starts a new background process for each subscriber. That is a common implementation. For example URLSession.DataTaskPublisher issues a new request for each subscriber. If you want multiple subscribers to share the output of a single request, you can use the .multicast operator, add multiple subscribers, and then .connect() the multicast publisher to start the background process once:

let pub = MyPublisher().multicast { PassthroughSubject() }
pub.sink(...).store(in: &tickets) // first subscriber
pub.sink(...).store(in: &tickets) // second subscriber
pub.connect().store(in: &tickets) // start the background process


问:
how to get a str from terminal and decode as gbk
i need to get a str from terminal. Sometime, it's gbk, like:

```<code>\77\262\331\327\367
</code>```

what i should do to get what the str really is.
if it's in code, it can be decode and print correctly.

```<code>inpt=b"\77\262\331\327\367"
print(inpt.decode("gbk"))

inpt=input("input: ")
print(inpt.decode("gbk"))
</code>```

答:
The input() function reads a line from input, converts it to a string (stripping a trailing newline), and returns that. Hence, the 'str' object has no attribute 'decode' message is quite comprehensible.

You need to build a bytes object from that string. Here's my old-school (non-Pythonish) solution (the script produces some didactic and illustrative output):

```<code>inpt=b"\77\262\331\327\367"
print("\ninpt")
print(type(inpt),"\t",inpt )
print(type(inpt.decode("gbk")),"\t",inpt.decode("gbk"))

inps=r"\77\262\331\327\367" # instead of inps=input("input octals, \\ delimited: ")
print("\ninps")
print(type(inps),"\t",inps )

inpb=b''
for x in list(filter(None, inps.split("\\"))):
    inpb+=bytes.fromhex(hex(int(x,8)).replace('0x',''))

print("\ninpb")
print(type(inpb),"\t",inpb )
print(type(inpb.decode("gbk")),"\t",inpb.decode("gbk"))
</code>```

Output: 61134038.py

```<code>inpt
<class 'bytes'>          b'?\xb2\xd9\xd7\xf7'
<class 'str'>    ?操作

inps
<class 'str'>    \77\262\331\327\367

inpb
<class 'bytes'>          b'?\xb2\xd9\xd7\xf7'
<class 'str'>    ?操作
</code>```

Body:
i need to get a str from terminal. Sometime, it's gbk, like:

\77\262\331\327\367

what i should do to get what the str really is.
if it's in code, it can be decode and print correctly.

inpt=b"\77\262\331\327\367"
print(inpt.decode("gbk"))

inpt=input("input: ")
print(inpt.decode("gbk"))

Body:
The input() function reads a line from input, converts it to a string (stripping a trailing newline), and returns that. Hence, the 'str' object has no attribute 'decode' message is quite comprehensible.

You need to build a bytes object from that string. Here's my old-school (non-Pythonish) solution (the script produces some didactic and illustrative output):

inpt=b"\77\262\331\327\367"
print("\ninpt")
print(type(inpt),"\t",inpt )
print(type(inpt.decode("gbk")),"\t",inpt.decode("gbk"))

inps=r"\77\262\331\327\367" # instead of inps=input("input octals, \\ delimited: ")
print("\ninps")
print(type(inps),"\t",inps )

inpb=b''
for x in list(filter(None, inps.split("\\"))):
    inpb+=bytes.fromhex(hex(int(x,8)).replace('0x',''))

print("\ninpb")
print(type(inpb),"\t",inpb )
print(type(inpb.decode("gbk")),"\t",inpb.decode("gbk"))

Output: 61134038.py

inpt
<class 'bytes'>          b'?\xb2\xd9\xd7\xf7'
<class 'str'>    ?操作

inps
<class 'str'>    \77\262\331\327\367

inpb
<class 'bytes'>          b'?\xb2\xd9\xd7\xf7'
<class 'str'>    ?操作


问:
Android widget "app shortcut" on long press
I want my widget to have a "configure widget" option along the default "app info" and "remove from home" I   get when creating a widget.
Ive being looking into the android documentations for a few hours and I cant find if there's a standard way of doing this.
I'm not sure if there's a standard android approach of adding menu items to this context menu or if its only something specific to the installed launcher but on my Samsung device, the pre-installed clock widget has this exact feature as shown here:

I tried adding an app shortcut (but it is obviously not the case since a widget does not have a "LAUNCHER" activity)

I tried adding an option menu

I tried adding different actions to my configuration activity.

any guidance or direction to the correct documentation would be appreciated.

答:
I found the solution.
it is specifically to add a "widget settings" feature to the context menu.

under your provider info xml, simply add:

```<code>android:widgetFeatures="reconfigurable"
</code>```

Body:
I found the solution.
it is specifically to add a "widget settings" feature to the context menu.

under your provider info xml, simply add:

android:widgetFeatures="reconfigurable"