问:
Epoch millis kibana mapping 1970 year problem
Im new to ELK Stack and i am facing this problem. Whenever i try to map timestamp from csv file (im mapping in kibana with epoch_millis) in my field all the dates start with  18january 1970, not the year of the timestamp. How can I get rid of this  or should I map it differently? Should I do something in the logstash? I am aware od that that this epoch have something to do with this 1970 year, but is there any other way to map this type of timestamp 1545003901 ? </p>

答:
Replace datatype "epoch_milis"(default type for date) in your mapping with "date".
More here : https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html</p>


来源: stackexchange

问:
unable to get jsonEncode in magento2
Magento has its own json encode and decode functions:

```<code>Mage::helper('core')->jsonEncode($array);
</code>```

Above code in depreciated in Magento 2. So how to use jsonEncode, what I have to extend to use json Encode?

答:
You can also use the following static method:</p>

```<code>\Magento\Framework\Serialize\JsonConverter::convert($data)
</code>```

ContentLicense: CC BY-SA 3.0

Title: unable to get jsonEncode in magento2

Body:
Magento has its own json encode and decode functions:

Mage::helper('core')->jsonEncode($array);

Above code in depreciated in Magento 2. So how to use jsonEncode, what I have to extend to use json Encode?

Body:
You can also use the following static method:

\Magento\Framework\Serialize\JsonConverter::convert($data)

ContentLicense: CC BY-SA 4.0


问:
Is output always determined by the %eax register in inline assembly in C?
I was reading tutorials regarding inline assembly within C, and they tried a simple variable assignment with

int a=10, b;
asm ("movl %1, %%eax;
movl %%eax, %0;"
:"=r"(b)        /* output */
:"r"(a)         /* input */
:"%eax"         /* clobbered register */
);
```

which made sense to me (move input into eax then move eax to output). But when I removed the %movl %%eax, 0 line (which is supposed to move the proper value to the output), the variable b was still assigned the proper value from the inline assembly.

My main question is how does the output 'know' to read from this %eax register?

答:
An inline-assembly statement is not a function call.

The "return in EAX" thing is for functions; it's part of the calling convention that lets compilers make code that can interact with other code even when they're compiled separately.  A calling convention is defined as part of an ABI doc.

As well as defining how to return (e.g. small non-FP objects in EAX, floating point in XMM0 or ST0), they also define where callers put args, and which registers you can use without saving/restoring (call-clobbered) and which you can (call-preserved).  See https://en.wikipedia.org/wiki/Calling_convention in general, and https://www.agner.org/optimize/calling_conventions.pdf for more about x86 calling conventions.

This inflexible rigid set of rules doesn't apply to inline asm because it doesn't have to; the compiler necessarily can see the asm statement as part of the surrounding C code.  That would defeat the whole point of inline.  Instead, in GNU C inline asm you write operands / constraints that describe the asm to the compiler, effectively creating a custom calling convention for each asm statement.  (With parts of that convention left up to the compiler's choice for "=r" outputs.  Use "=a" if you want to force it to pick AL/AX/EAX/RAX.)

If you want to write asm that returns in EAX without having to tell the compiler about it, write a stand-alone function.  (e.g. in a .s file, or an asm("") statement as the body of an __attribute__((naked)) C function.  Either way you have to write the ret yourself and get args via the calling convention, too.)

Falling off the end of a non-void function after running an asm statement that leaves a value in EAX may appear to work with optimization disabled, but it's totally unsafe and will break as soon as you enable optimization and the compiler inlines it.

My main question is how does the output 'know' to read from this %eax register?

It probably just happened to pick EAX for the "=r" output when you compiled with optimization disabled.  EAX is always GCC's first choice for evaluating expressions.  Look at the compiler-generated asm output (gcc -S -fverbose-asm) to see what asm it generated around your asm, and which register it substituted into your asm template.  You probably have mov %eax, %eax ; mov %eax, %eax.

Using mov as the first or last instruction of an asm template almost always means you're doing it wrong and should have used better constraints to tell the compiler where to put or where to find your data.

e.g. asm("" : "=r"(b) : "0"(a)) will make the compiler put the input into the same register as it's expecting the output operand.  So that copies a value.  (And forces the compiler to materialize it in a register, and forget anything it knows about the current value, defeating constant-propagation and value range optimizations, as well as stopping the compiler from optimizing away that temporary entirely.)

Why does issuing empty asm commands swap variables? describes that happening by change, same as your case with the compiler picking the same reg for input and output "r" operands.  And illustrates using asm comments *inside the asm template to print out what the compiler chose for any %0 or %1 operands you don't otherwise reference explicitly**.

See also segmentation fault(core dumped) error while using inline assembly for more about the basics of using input and output constraints.

Also related: What happens to registers when you manipulate them using asm code in C++? for another example and writeup of how compilers handle register in GNU C inline asm statements.

Body:
I was reading tutorials regarding inline assembly within C, and they tried a simple variable assignment with

int a=10, b;
asm ("movl %1, %%eax;
movl %%eax, %0;"
:"=r"(b)        /* output */
:"r"(a)         /* input */
:"%eax"         /* clobbered register */
);

which made sense to me (move input into eax then move eax to output). But when I removed the %movl %%eax, 0 line (which is supposed to move the proper value to the output), the variable b was still assigned the proper value from the inline assembly.

My main question is how does the output 'know' to read from this %eax register?


问:
Spark 2.0 groupBy column and then get max(date) on a datetype column
I'm using Spark 2.0 in Java.
I have a Dataset which look like this:

```<code>------+----+----+----+----------------+
    ID|col1|col2|col3|            date|
------+----+----+----+----------------+
981200| a  | q  | z  |      2010-12-30|
968800| s  | w  | x  |      2010-12-31|
966500| d  | e  | c  |      2010-11-02|
966500| f  | r  | v  |      2010-12-01|
981200| g  | t  | b  |      2010-12-03|
</code>```

I wanto to groupBy ID and get only the row with the "last" date (the most recent one). The type of column "date" is date.

In my case the result would be

```<code>------+----------------+
    ID|       max(date)|
------+----------------+
981200|      2010-12-30|
968800|      2010-12-31|
966500|      2010-12-01|
</code>```

I tried

```<code>    Dataset<Row> df = old_df.groupBy("ID").max("date");
</code>```

but fails with error

Exception in thread "main" org.apache.spark.sql.AnalysisException:
      "date" is not a numeric column.
      Aggregation function can only be applied on a numeric column.;

Is there a way to get the max date (using type date) in Spark?

Thanks in advance.

答:
This workaround showed the result for me in Palantir (an environment for Scala) in PySpark:

```<code>def get_max_from_date(country_ref):
    return country_ref\
        .selectExpr("cast(date_format(from_date, 'YYYYMMDD') as decimal(8,0)) as c")\
        .agg(F.max('c').alias('max_c'))\
        .selectExpr("cast(max_c as varchar(8)) as max_c_string")\
        .select(F.to_date(F.col('max_c_string'), 'YYYYMMDD')).alias("max_from_date")
</code>```

So:

convert to string

convert to integer

get the maximum

convert to string

convert back to date

See also PySpark groupby and max value selection

Side note: Ah, remember how easy and quick it is in SQL! How immature Scala seems to be! Not diminishing all its Big Data capabilities in any way!

Body:
I'm using Spark 2.0 in Java.
I have a Dataset which look like this:

------+----+----+----+----------------+
    ID|col1|col2|col3|            date|
------+----+----+----+----------------+
981200| a  | q  | z  |      2010-12-30|
968800| s  | w  | x  |      2010-12-31|
966500| d  | e  | c  |      2010-11-02|
966500| f  | r  | v  |      2010-12-01|
981200| g  | t  | b  |      2010-12-03|

I wanto to groupBy ID and get only the row with the "last" date (the most recent one). The type of column "date" is date.

In my case the result would be

------+----------------+
    ID|       max(date)|
------+----------------+
981200|      2010-12-30|
968800|      2010-12-31|
966500|      2010-12-01|

I tried

    Dataset<Row> df = old_df.groupBy("ID").max("date");

but fails with error

Exception in thread "main" org.apache.spark.sql.AnalysisException:
      "date" is not a numeric column.
      Aggregation function can only be applied on a numeric column.;

Is there a way to get the max date (using type date) in Spark?

Thanks in advance.

Body:
This workaround showed the result for me in Palantir (an environment for Scala) in PySpark:

def get_max_from_date(country_ref):
    return country_ref\
        .selectExpr("cast(date_format(from_date, 'YYYYMMDD') as decimal(8,0)) as c")\
        .agg(F.max('c').alias('max_c'))\
        .selectExpr("cast(max_c as varchar(8)) as max_c_string")\
        .select(F.to_date(F.col('max_c_string'), 'YYYYMMDD')).alias("max_from_date")

So:

convert to string

convert to integer

get the maximum

convert to string

convert back to date

See also PySpark groupby and max value selection

Side note: Ah, remember how easy and quick it is in SQL! How immature Scala seems to be! Not diminishing all its Big Data capabilities in any way!


问:
Firestore document to Flutter Problem : Exception( type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>')
Can't get my head around this problem.
I set the following document to firestore.
And i need to convert 'attendance' field to a List.

```<code> Map<String, dynamic> data = {
  "name": "memberName",
  "attendance": {
    "0": {"morning": false, "noon": true, "night": true},
    "1": {"morning": false, "noon": true, "night": true}
  },
  "deposits": {
    "0": {"date": "date", "amount": 100},
    "1": {"date": "date", "amount": 100}
  }
};
</code>```

Using StreamProvider . Stream has no problem.
using toList()

Documents are fetched. But models are failing. Getting a Exception : [type '_InternalLinkedHashMap' is not a subtype of type 'Map']
Model Classes:

```<code>class Member {
  String id;
  String name;
  List<Attendance> attendances;
  List<Deposit> deposits;

  Member({this.id, this.name, this.attendances, this.deposits});

  Member.fromSnapshot(DocumentSnapshot doc) {
    Map<String, dynamic> json = doc.data;
    id = doc.documentID;
    name = json['name'];
    if (json['attendance'] != null) {
      Map<String, dynamic> atdmap = json['attendance'];
      attendances = new List<Attendance>();
      atdmap.forEach((k, v) {
        attendances.add(new Attendance.fromJson(v));
      });
    }
    if (json['deposits'] != null) {
      Map<String, dynamic> dmap = json['deposits'];
      deposits = new List<Deposit>();
      dmap.forEach((k, v) {
        deposits.add(new Deposit.fromJson(v));
      });
    }
  }
}

class Attendance {
  bool morning;
  bool noon;
  bool night;

  Attendance({this.morning, this.noon, this.night});

  Attendance.fromJson(Map<String, dynamic> json) {
    morning = json['morning'];
    noon = json['noon'];
    night = json['night'];
  }
}

class Deposit {
  String date;
  int amount;

  Deposit({this.date, this.amount});

  Deposit.fromJson(Map<String, dynamic> json) {
    date = json['date'];
    amount = json['amount'];
  }
}
</code>```

Where is it getting wrong. need a little help.
thank you.

答:
try an explicit cast</p>

```<code>Map<String, dynamic> json = doc.data as Map<String, dynamic>;
</code>```

Body:
Can't get my head around this problem.
I set the following document to firestore.
And i need to convert 'attendance' field to a List.

 Map<String, dynamic> data = {
  "name": "memberName",
  "attendance": {
    "0": {"morning": false, "noon": true, "night": true},
    "1": {"morning": false, "noon": true, "night": true}
  },
  "deposits": {
    "0": {"date": "date", "amount": 100},
    "1": {"date": "date", "amount": 100}
  }
};

Using StreamProvider . Stream has no problem.
using toList()

Documents are fetched. But models are failing. Getting a Exception : [type '_InternalLinkedHashMap' is not a subtype of type 'Map']
Model Classes:

class Member {
  String id;
  String name;
  List<Attendance> attendances;
  List<Deposit> deposits;

  Member({this.id, this.name, this.attendances, this.deposits});

  Member.fromSnapshot(DocumentSnapshot doc) {
    Map<String, dynamic> json = doc.data;
    id = doc.documentID;
    name = json['name'];
    if (json['attendance'] != null) {
      Map<String, dynamic> atdmap = json['attendance'];
      attendances = new List<Attendance>();
      atdmap.forEach((k, v) {
        attendances.add(new Attendance.fromJson(v));
      });
    }
    if (json['deposits'] != null) {
      Map<String, dynamic> dmap = json['deposits'];
      deposits = new List<Deposit>();
      dmap.forEach((k, v) {
        deposits.add(new Deposit.fromJson(v));
      });
    }
  }
}

class Attendance {
  bool morning;
  bool noon;
  bool night;

  Attendance({this.morning, this.noon, this.night});

  Attendance.fromJson(Map<String, dynamic> json) {
    morning = json['morning'];
    noon = json['noon'];
    night = json['night'];
  }
}

class Deposit {
  String date;
  int amount;

  Deposit({this.date, this.amount});

  Deposit.fromJson(Map<String, dynamic> json) {
    date = json['date'];
    amount = json['amount'];
  }
}

Where is it getting wrong. need a little help.
thank you.

Body:
try an explicit cast

Map<String, dynamic> json = doc.data as Map<String, dynamic>;


问:
Unable to download remote image with PHP CURL
Edit: I contact the support at scrapestack and confirmed that their api doesn't support image files.

I am trying to download a remote image using CURL with php. Below is my code. But whenever I try to open the downloaded image, I always get:

```<code>Cannot read this file. This is not a valid bitmap file, or its format is not currently supported.
</code>```

Anyone know what is wrong with my code? Thank you.

```<code>$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://i.imgur.com/Cbiu8Ef.png";
$imageName = pathinfo( $image, PATHINFO_BASENAME );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $image );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTP_CONTENT_DECODING, false);
$source = curl_exec( $ch );
$info = curl_getinfo($ch);
curl_close( $ch );
file_put_contents( $imageName, $source );
</code>```

I am not able to open the file, when I tried to open it with sublime, it is stuck at Loading Image. When I open it with notepad, I got the following that looks like PNG image, but it is not a valid image. File starts with
    �PNG

```<code>IHDR       �   q�I�    IDATx�k�]�u�o��(��_�M��m�8:���_r�G
</code>```

You can see the file here: https://gofile.io/?c=cfsYf2

Looks like the problem is making the curl request through Scrapestack, because if I point the curl to image url directly, the image is downloaded correctly, like below:

```<code>$image ="https://i.imgur.com/Cbiu8Ef.png";
</code>```

答:
Your problem is with this url.

```<code>$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://imgur.com/a/E5ehGuv";
</code>```

If you go to this url

https://imgur.com/a/E5ehGuv

You will see the image page but NOT the image path. pathinfo() function does not work here and raises error.

If you right click on that image and Open image in new tab you will then see the image path, in this case that is

https://i.imgur.com/Cbiu8Ef.png

So you may try with this url

```<code>$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://i.imgur.com/Cbiu8Ef.png";
</code>```

Body:
Edit: I contact the support at scrapestack and confirmed that their api doesn't support image files.

I am trying to download a remote image using CURL with php. Below is my code. But whenever I try to open the downloaded image, I always get:

Cannot read this file. This is not a valid bitmap file, or its format is not currently supported.

Anyone know what is wrong with my code? Thank you.

$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://i.imgur.com/Cbiu8Ef.png";
$imageName = pathinfo( $image, PATHINFO_BASENAME );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $image );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTP_CONTENT_DECODING, false);
$source = curl_exec( $ch );
$info = curl_getinfo($ch);
curl_close( $ch );
file_put_contents( $imageName, $source );

I am not able to open the file, when I tried to open it with sublime, it is stuck at Loading Image. When I open it with notepad, I got the following that looks like PNG image, but it is not a valid image. File starts with
    �PNG

IHDR       �   q�I�    IDATx�k�]�u�o��(��_�M��m�8:���_r�G

You can see the file here: https://gofile.io/?c=cfsYf2

Looks like the problem is making the curl request through Scrapestack, because if I point the curl to image url directly, the image is downloaded correctly, like below:

$image ="https://i.imgur.com/Cbiu8Ef.png";

Body:
Your problem is with this url.

$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://imgur.com/a/E5ehGuv";

If you go to this url

https://imgur.com/a/E5ehGuv

You will see the image page but NOT the image path. pathinfo() function does not work here and raises error.

If you right click on that image and Open image in new tab you will then see the image path, in this case that is

https://i.imgur.com/Cbiu8Ef.png

So you may try with this url

$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://i.imgur.com/Cbiu8Ef.png";


问:
use macro to test function return value in C
I want to have a macro which does something like:

#define TEST(_ptr) ({ if ((_ptr) == NULL) ERROR; (_ptr); })

which check _ptr and calls ERROR macro or return its value.

However, if I use something like var = TEST(fun()) this results in fun() being called two times.

I can do something like:

#define TEST(_tmp, _ptr) ({ _tmp = _ptr; if ((_tmp) == NULL) ERROR; (_tmp); })

is there any clean way of doing this without passing temporary storage, e.g. using typeof operator!?

答:
Rather than using a macro definition, why not use a regular function as in:

```<code>void *funcCaller (void *f) {
    if (f == NULL) {
        ERROR;    // not sure what the ERROR thing is supposed to do or look like.
    }

    return f;
}
</code>```

Then call it as in:

```<code>p = funcCaller (func());
</code>```

Since the argument list for funcCaller() is using a void * then the return type of func() could be any pointer type.

Body:
Rather than using a macro definition, why not use a regular function as in:

void *funcCaller (void *f) {
    if (f == NULL) {
        ERROR;    // not sure what the ERROR thing is supposed to do or look like.
    }

    return f;
}

Then call it as in:

p = funcCaller (func());

Since the argument list for funcCaller() is using a void * then the return type of func() could be any pointer type.


问:
What's the preferred method in the community for having python 2.x and 3.x in the same codebase?
I am starting a project in Python 3.x, (I'm quite new to Python) and there exists the possibility that I will need to use say Thrift or any other library that is not yet ported to Python 3.x.

I don't mind about devoting some (substantial) amount of time to convert an external library to Python 3.x if with that others can benefit from that, but I'm curious if there's any preferred way in the Open Source community to deal with this problem.

I have been reading here and there in the python.org site and in some other websites, but I haven't found anything conclusive.  The only thing that I found is that this is a chicken-and-egg problem.

It's out of the question (unless there's no other option) that I ship a dump of a library with my own modifications just to make it 3.x compliant.

Should I...

prepare all the code with __future imports and change here and there appropriately and leave it ready to work with both 2.x and 3.x?  Am I going to find any problem with this, other than the natural resistance of upstream to integrate such amount of changes?

create another branch of the code?  That, to me, should be quite useless, as nobody will maintain that branch except me, probably, and it's a huge duplication effort.

use some type of wrapper that I am not aware of to use those libraries as-is (like using some intermediate bindings in another language) and just create the glue in my code?

Many thanks!

答: http://docs.python.org/dev/howto/pyporting.html is the source for the most up-to-date advice from the CPython core devs (although it sounds like you have already looked at that).</p>


问:
Post Tweet with YouTube Video URL using Tweepy
I notice that if I Tweet normally (from the browser) with a message followed by a YouTube video link, Twitter displays the video's thumbnail, as follows:

However, if I use the following code to send the Tweet instead:

```<code>import tweepy
import json
youtube_url = r'https://www.youtube.com/watch?v=tj-fmOnbBpU&t=0s'
# account tokens
twitter_keys = json.load(open('twitter_keys.json'))
auth = tweepy.OAuthHandler(twitter_keys["consumer_key"], twitter_keys["consumer_secret"]) # authentication of consumer key and secret
auth.set_access_token(twitter_keys["access_token"], twitter_keys["access_token_secret"]) # authentication of access token and secret
api = tweepy.API(auth)
twitter_text = "My message " + youtube_url
api.update_status(status ="{}".format(twitter_text)) # send a tweet
</code>```

I get something like this:

As you can see, Twitter doesn't show the preview for the URL, even after a few days. I don't understand why this is. How can I fix my code so that the Tweet sent through the API shows the preview of the YouTube video link?

答:
See this Stack Overflow post on how the youtube thumbnail URL is structured.

Use this post to see how you can programmatically download the thumbnail locally with the requests library.

Then you can use Tweepy's update_with_media() to upload it as part of the tweet.

The end result will look something like this:

```<code>import tweepy
import json
import requests

# video info
youtube_id = "tj-fmOnbBpU"
youtube_url = f"https://www.youtube.com/watch?v={youtube_id}&t=0s"

# account tokens
twitter_keys = json.load(open('twitter_keys.json'))
auth = tweepy.OAuthHandler(twitter_keys["consumer_key"], twitter_keys["consumer_secret"]) # authentication of consumer key and secret
auth.set_access_token(twitter_keys["access_token"], twitter_keys["access_token_secret"]) # authentication of access token and secret
api = tweepy.API(auth)
twitter_text = f"My message: {youtube_url}"

# downloading thumbnail
url = f"https://img.youtube.com/vi/{youtube_id}/1.jpg"

filename = url.split("/")[-1]
r = requests.get(url, timeout=0.5)

if r.status_code == 200:
    with open(filename, 'wb') as f:
        f.write(r.content)

# Send tweet
api.update_with_media(filename, status=twitter_text)
</code>```

Body:
I notice that if I Tweet normally (from the browser) with a message followed by a YouTube video link, Twitter displays the video's thumbnail, as follows:

However, if I use the following code to send the Tweet instead:

import tweepy
import json
youtube_url = r'https://www.youtube.com/watch?v=tj-fmOnbBpU&t=0s'
# account tokens
twitter_keys = json.load(open('twitter_keys.json'))
auth = tweepy.OAuthHandler(twitter_keys["consumer_key"], twitter_keys["consumer_secret"]) # authentication of consumer key and secret
auth.set_access_token(twitter_keys["access_token"], twitter_keys["access_token_secret"]) # authentication of access token and secret
api = tweepy.API(auth)
twitter_text = "My message " + youtube_url
api.update_status(status ="{}".format(twitter_text)) # send a tweet

I get something like this:

As you can see, Twitter doesn't show the preview for the URL, even after a few days. I don't understand why this is. How can I fix my code so that the Tweet sent through the API shows the preview of the YouTube video link?

Body:
See this Stack Overflow post on how the youtube thumbnail URL is structured.

Use this post to see how you can programmatically download the thumbnail locally with the requests library.

Then you can use Tweepy's update_with_media() to upload it as part of the tweet.

The end result will look something like this:

import tweepy
import json
import requests

# video info
youtube_id = "tj-fmOnbBpU"
youtube_url = f"https://www.youtube.com/watch?v={youtube_id}&t=0s"

# account tokens
twitter_keys = json.load(open('twitter_keys.json'))
auth = tweepy.OAuthHandler(twitter_keys["consumer_key"], twitter_keys["consumer_secret"]) # authentication of consumer key and secret
auth.set_access_token(twitter_keys["access_token"], twitter_keys["access_token_secret"]) # authentication of access token and secret
api = tweepy.API(auth)
twitter_text = f"My message: {youtube_url}"

# downloading thumbnail
url = f"https://img.youtube.com/vi/{youtube_id}/1.jpg"

filename = url.split("/")[-1]
r = requests.get(url, timeout=0.5)

if r.status_code == 200:
    with open(filename, 'wb') as f:
        f.write(r.content)

# Send tweet
api.update_with_media(filename, status=twitter_text)


问:
Image Upload using Retrofit in Android
I am trying to upload an image to the Webserver using retrofit.

The API has been developed using Dot Net.
The API is working fine on postman but shows error in android.

```<code>URL: https://m13tp89pn9.execute-api.us-west-2.amazonaws.com/Prod/api/user/UploadImag/userid=67

Authorization = Bearer token
</code>```

This is my interface

```<code>@Headers("Content-Type: multipart/form-data")
@Multipart
@POST("user/UploadImage")
Call<GeneralPOJO> uploadProfileImage(@Query ("userid") int uid,
                                     @Part MultipartBody.Part image, @Header("Authorization")String header);
</code>```

This is my Code

```<code>    final String path = getPathFromURI(selectedImageUri);
                    if (path != null) {
                        File file = new File(path);

   RequestBody mFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getAbsolutePath(), mFile);
                        RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

new RestCaller(ProfileActivity.this, MainApplication.getRestClient().getApiServices().
                                    uploadProfileImage(AppSession.getInt(Constants.LOGIN_UDID), fileToUpload, AppSession.get(Constants.LOGIN_TOKEN)), Constants.REQUEST_CODE_PROFILE_PICTURE);
</code>```

Please help me in uploading the image to the server successfully. Please correct my code and tell me what change is required. Thanks

答:
```<code>// Interface

@Multipart
@POST("user/UploadImage/{userid}")
Call<GeneralPOJO> uploadProfileImage(@Path ("userid") int uid,
                                     @Part MultipartBody.Part image, @Header("Authorization")String header);
</code>```

Title: Image Upload using Retrofit in Android

Body:
I am trying to upload an image to the Webserver using retrofit.

The API has been developed using Dot Net.
The API is working fine on postman but shows error in android.

URL: https://m13tp89pn9.execute-api.us-west-2.amazonaws.com/Prod/api/user/UploadImag/userid=67

Authorization = Bearer token

This is my interface

@Headers("Content-Type: multipart/form-data")
@Multipart
@POST("user/UploadImage")
Call<GeneralPOJO> uploadProfileImage(@Query ("userid") int uid,
                                     @Part MultipartBody.Part image, @Header("Authorization")String header);

This is my Code

    final String path = getPathFromURI(selectedImageUri);
                    if (path != null) {
                        File file = new File(path);

   RequestBody mFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getAbsolutePath(), mFile);
                        RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

new RestCaller(ProfileActivity.this, MainApplication.getRestClient().getApiServices().
                                    uploadProfileImage(AppSession.getInt(Constants.LOGIN_UDID), fileToUpload, AppSession.get(Constants.LOGIN_TOKEN)), Constants.REQUEST_CODE_PROFILE_PICTURE);

Please help me in uploading the image to the server successfully. Please correct my code and tell me what change is required. Thanks


问:
SwiftUI -- Detect DragGesture cancellation when iPad dock is pulled up
Here is a very simple example to show what I try to do. The red circle can be dragged around and when it is released it will go back to the original place, as shown in the first image. The problem occurs when iPad dock is pulled up in the middle of dragging and then the DragGesture's .onEnded will never be called and the red circle is stuck, as shown in the second image. I don't understand why .onEndedisn't called. What am I missing here?

I thought of a workaround by resetting offset in SceneDelegate's sceneDidBecomeActive, but it doesn't work if iPad dock is just pulled up but doesn't cause the app to become inactive, i.e. going to background mode. In this case, no functions in SceneDelegate will be called and I find it impossible to detect that DragGesture has been interrupted. Any possible solution?

```<code>struct ContentView: View {
  @State private var offset = CGSize.zero

  var body: some View {
    ZStack {
      Rectangle()
        .fill(Color.clear)
        .frame(width: 100, height: 100)
        .border(Color.black, width: 5)

      Circle()
        .fill(Color.red)
        .frame(width: 90, height: 90)
        .offset(offset)
        .gesture(
          DragGesture()
            .onChanged() { self.offset = $0.translation }
            .onEnded() { _ in self.offset = CGSize.zero })
    }
  }
}
</code>```

答:
Try with GestureState as follows. It is temporary, by default, and when ended is reset to initial value by design.

```<code>struct ContentView: View {
  @GestureState private var offset = CGSize.zero

  var body: some View {
    ZStack {
      Rectangle()
        .fill(Color.clear)
        .frame(width: 100, height: 100)
        .border(Color.black, width: 5)

      Circle()
        .fill(Color.red)
        .frame(width: 90, height: 90)
        .offset(offset)
        .gesture(
          DragGesture()
            .updating($offset) { (value, gestureState, transaction) in
                gestureState = CGSize(width: value.location.x - value.startLocation.x, height: value.location.y - value.startLocation.y)
            })
    }
  }
}
</code>```

Body:
Here is a very simple example to show what I try to do. The red circle can be dragged around and when it is released it will go back to the original place, as shown in the first image. The problem occurs when iPad dock is pulled up in the middle of dragging and then the DragGesture's .onEnded will never be called and the red circle is stuck, as shown in the second image. I don't understand why .onEndedisn't called. What am I missing here?

I thought of a workaround by resetting offset in SceneDelegate's sceneDidBecomeActive, but it doesn't work if iPad dock is just pulled up but doesn't cause the app to become inactive, i.e. going to background mode. In this case, no functions in SceneDelegate will be called and I find it impossible to detect that DragGesture has been interrupted. Any possible solution?

struct ContentView: View {
  @State private var offset = CGSize.zero

  var body: some View {
    ZStack {
      Rectangle()
        .fill(Color.clear)
        .frame(width: 100, height: 100)
        .border(Color.black, width: 5)

      Circle()
        .fill(Color.red)
        .frame(width: 90, height: 90)
        .offset(offset)
        .gesture(
          DragGesture()
            .onChanged() { self.offset = $0.translation }
            .onEnded() { _ in self.offset = CGSize.zero })
    }
  }
}

Body:
Try with GestureState as follows. It is temporary, by default, and when ended is reset to initial value by design.

struct ContentView: View {
  @GestureState private var offset = CGSize.zero

  var body: some View {
    ZStack {
      Rectangle()
        .fill(Color.clear)
        .frame(width: 100, height: 100)
        .border(Color.black, width: 5)

      Circle()
        .fill(Color.red)
        .frame(width: 90, height: 90)
        .offset(offset)
        .gesture(
          DragGesture()
            .updating($offset) { (value, gestureState, transaction) in
                gestureState = CGSize(width: value.location.x - value.startLocation.x, height: value.location.y - value.startLocation.y)
            })
    }
  }
}


问:
pip installation succeeds but Python says module not found
I am trying to install a package with pip. The installation is successful but when trying to import the modules in a subpackage it shows me an error message that says "ModuleNotFoundError: No module named...".

The structure of the package is as follows:

Gestor_Clientes_v2/

   ├─   LICENCE.txt

   ├─   manager_main/

     ├─   __init__.py

     ├─   run.py

     ├─   support.py

     ├─   manager_clients.py

     └─   menu.py

   ├─   README.md

   ├─   setup.py

   └─   test/

     ├─   __init__.py

     └─   test_manager_clients.py

The setup file has the following information:

#!/usr/bin/env python

from setuptools import setup, find_packages

with open('README.md') as file: readme = file.read()

setup(name = 'gestor-clientes',
      version = '2.0',
      author = 'author',
      author_email = 'info@server.com',
      url = 'https://www.server.com/',
      description = 'Un simple gestor de clientes',
      long_description = readme,
      packages = ['manager'],
      test_suite = 'program.test',
      entry_points = {'console_scripts': ['program = manager.run:main']},
      license = 'MIT Licence',
      keywords = 'gestor clientes proyecto',
      classifiers = [
          'Development Status :: 2 - Pre-Alpha',
          'Topic :: Education',
          'Intended Audience :: Education',
          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python :: 3 :: Only',
          'Operating System :: Linux',
          'Operating System :: MacOS',
          'Operating System :: Windows'
      ]

      )
```

<p><strong>__init__.py</strong></p>

<pre class="lang-py prettyprint-override"><code>__all__ = ['run', 'manager_clients', 'menu', 'support']
</code>```

menu.py

"""Fichero principal del programa"""

from sys import path
path.append('..')

from menu import Menu

def main():
    Menu.options()

if __name__ == '__main__':
    main()
```

<p><strong>manager_clients.py</strong></p>

<pre class="lang-py prettyprint-override"><code>""" Administrador de clientes """
import sys
sys.path.append("..")
from manager import support

class ClientData:

    def __init__(self, name: str, first_surname:str, second_surname:str, birth_date:str, nationality:str, nip:str):
        self.name = name
        self.first_surname = first_surname
        self.second_surname = second_surname
        self.birth_date = birth_date
        self.nationality = nationality
        self.nip = nip

    def __str__(self):
        return f"{self.nip}: {self.first_surname} {self.second_surname} {self.name} {self.birth_date} {self.nationality}"

#more code...

</code>```

menu.py

""" Menú del programa """
from sys import path
path.append('..')

from manager.support import clear_screen
from manager.manager_clients import ClientAdmin

class Menu:

    def options():
        while True:
            clear_screen()
            print("========================\n",\
                  "|BIENVENIDO AL GESTOR|",\
                  "\n========================",\
                  "\n    Elija una opción    ",\
                  "\n------------------------",\
                  "\n[1] Lista de clientes.",\
                  "\n[2] Buscar cliente.",\
                  "\n[3] Añadir nuevo cliente.",\
                  "\n[4] Actualizar datos del cliente.",\
                  "\n[5] Borrar cliente.",\
                  "\n[6] Salir.")

            option = input(">>> ")
            clear_screen()
            if option == '1':
                print("--INFORMACIÓN DE CLIENTES DISPONIBLES--\n")
                ClientAdmin.info_all_clients()

#more code...
```

<p><strong>support.py</strong></p>

<pre class="lang-py prettyprint-override"><code>"""Funciones de ayuda"""
from sys import path
from os import system
import re
from platform import system as OS
path.append("..")

from manager import manager_clients

def clear_screen():
    if OS() == "Windows":
        system('cls')
    else:
        system('clear')

def input_text(min_len, max_len):
    while True:
        text = input("> ")
        if len(text) >= min_len and len(text) <= max_len:
            return text

def is_valid(nip: str):
    if not re.match('[0-9]{2}[A-Z]{3}', nip):
        return False
    for c in manager_clients.ClientAdmin.clients:
        if c.nip == nip:
            return False
    return True
</code>```

When I run the "run.py" script from the command line the program works correctly just like when I run the tests. When I install the package using pip install Gestor_Clientes_v2/ I get the following:

Processing ./Gestor_Clientes_v2
Building wheels for collected packages: gestor-clientes
  Building wheel for gestor-clientes (setup.py) ... done
  Created wheel for gestor-clientes: filename=gestor_clientes-2.0-cp37-none-any.whl size=6120 sha256=50337e3ed6672cf714d81103c53dd3b957f6c10722c14f952b49baa1a814dbac
  Stored in directory: /tmp/pip-ephem-wheel-cache-be04i_g5/wheels/e4/03/c1/ce19d5766499ca97b57afbdc34598a26f32ca3b9eb01754979
Successfully built gestor-clientes
Installing collected packages: gestor-clientes
Successfully installed gestor-clientes-2.0
```

<p>The packages appear in <code>pip list</code> as <kbd>gestor-clientes</kbd> but when I want to import any of the modules in "manager /" I get the error:</p>

<pre class="lang-py prettyprint-override"><code>In [1]: import manager
----------------------------------------------------------------------
ModuleNotFoundError                  Traceback (most recent call last)
<ipython-input-1-26cb231bd30e> in <module>
----> 1 import manager

~/anaconda3/lib/python3.7/site-packages/manager/__init__.py in <module>
----> 1 from manager import run
      2 from manager import manager_clients
      3 from manager import menu
      4 from manager import support

~/anaconda3/lib/python3.7/site-packages/manager/run.py in <module>
      4 path.append('..')
      5
----> 6 from menu import Menu
      7
      8

ModuleNotFoundError: No module named 'menu'

In [2]:
</code>```

I have been guided by different examples of packages with a similar structure and when I install them I can import their modules.

I am relatively new to Python and there are still many things that I don't know well and I think there is something missing in my modules and my setup file.

I hope you can help me review the structure of my package and give me some ideas to solve my problem. Thanks in advance.

答:
I think you should try to install the package using pip3, based on the previous syntax

pip3 install packagename

In some cases, when you have a preinstalled Python 2, this can be the solution, because even though you’ve installed the package, it can only be accessed by the Python 2 interpreter as they are different installations.

Body:
I am trying to install a package with pip. The installation is successful but when trying to import the modules in a subpackage it shows me an error message that says "ModuleNotFoundError: No module named...".

The structure of the package is as follows:

Gestor_Clientes_v2/

   ├─   LICENCE.txt

   ├─   manager_main/

     ├─   __init__.py

     ├─   run.py

     ├─   support.py

     ├─   manager_clients.py

     └─   menu.py

   ├─   README.md

   ├─   setup.py

   └─   test/

     ├─   __init__.py

     └─   test_manager_clients.py

The setup file has the following information:

#!/usr/bin/env python

from setuptools import setup, find_packages

with open('README.md') as file: readme = file.read()

setup(name = 'gestor-clientes',
      version = '2.0',
      author = 'author',
      author_email = 'info@server.com',
      url = 'https://www.server.com/',
      description = 'Un simple gestor de clientes',
      long_description = readme,
      packages = ['manager'],
      test_suite = 'program.test',
      entry_points = {'console_scripts': ['program = manager.run:main']},
      license = 'MIT Licence',
      keywords = 'gestor clientes proyecto',
      classifiers = [
          'Development Status :: 2 - Pre-Alpha',
          'Topic :: Education',
          'Intended Audience :: Education',
          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python :: 3 :: Only',
          'Operating System :: Linux',
          'Operating System :: MacOS',
          'Operating System :: Windows'
      ]

      )

__init__.py

__all__ = ['run', 'manager_clients', 'menu', 'support']

menu.py

"""Fichero principal del programa"""

from sys import path
path.append('..')

from menu import Menu

def main():
    Menu.options()

if __name__ == '__main__':
    main()

manager_clients.py

""" Administrador de clientes """
import sys
sys.path.append("..")
from manager import support

class ClientData:

    def __init__(self, name: str, first_surname:str, second_surname:str, birth_date:str, nationality:str, nip:str):
        self.name = name
        self.first_surname = first_surname
        self.second_surname = second_surname
        self.birth_date = birth_date
        self.nationality = nationality
        self.nip = nip

    def __str__(self):
        return f"{self.nip}: {self.first_surname} {self.second_surname} {self.name} {self.birth_date} {self.nationality}"

#more code...

menu.py

""" Menú del programa """
from sys import path
path.append('..')

from manager.support import clear_screen
from manager.manager_clients import ClientAdmin

class Menu:

    def options():
        while True:
            clear_screen()
            print("========================\n",\
                  "|BIENVENIDO AL GESTOR|",\
                  "\n========================",\
                  "\n    Elija una opción    ",\
                  "\n------------------------",\
                  "\n[1] Lista de clientes.",\
                  "\n[2] Buscar cliente.",\
                  "\n[3] Añadir nuevo cliente.",\
                  "\n[4] Actualizar datos del cliente.",\
                  "\n[5] Borrar cliente.",\
                  "\n[6] Salir.")

            option = input(">>> ")
            clear_screen()
            if option == '1':
                print("--INFORMACIÓN DE CLIENTES DISPONIBLES--\n")
                ClientAdmin.info_all_clients()

#more code...

support.py

"""Funciones de ayuda"""
from sys import path
from os import system
import re
from platform import system as OS
path.append("..")

from manager import manager_clients

def clear_screen():
    if OS() == "Windows":
        system('cls')
    else:
        system('clear')

def input_text(min_len, max_len):
    while True:
        text = input("> ")
        if len(text) >= min_len and len(text) <= max_len:
            return text

def is_valid(nip: str):
    if not re.match('[0-9]{2}[A-Z]{3}', nip):
        return False
    for c in manager_clients.ClientAdmin.clients:
        if c.nip == nip:
            return False
    return True

When I run the "run.py" script from the command line the program works correctly just like when I run the tests. When I install the package using pip install Gestor_Clientes_v2/ I get the following:

Processing ./Gestor_Clientes_v2
Building wheels for collected packages: gestor-clientes
  Building wheel for gestor-clientes (setup.py) ... done
  Created wheel for gestor-clientes: filename=gestor_clientes-2.0-cp37-none-any.whl size=6120 sha256=50337e3ed6672cf714d81103c53dd3b957f6c10722c14f952b49baa1a814dbac
  Stored in directory: /tmp/pip-ephem-wheel-cache-be04i_g5/wheels/e4/03/c1/ce19d5766499ca97b57afbdc34598a26f32ca3b9eb01754979
Successfully built gestor-clientes
Installing collected packages: gestor-clientes
Successfully installed gestor-clientes-2.0

The packages appear in pip list as gestor-clientes but when I want to import any of the modules in "manager /" I get the error:

In [1]: import manager
----------------------------------------------------------------------
ModuleNotFoundError                  Traceback (most recent call last)
<ipython-input-1-26cb231bd30e> in <module>
----> 1 import manager

~/anaconda3/lib/python3.7/site-packages/manager/__init__.py in <module>
----> 1 from manager import run
      2 from manager import manager_clients
      3 from manager import menu
      4 from manager import support

~/anaconda3/lib/python3.7/site-packages/manager/run.py in <module>
      4 path.append('..')
      5
----> 6 from menu import Menu
      7
      8

ModuleNotFoundError: No module named 'menu'

In [2]:

I have been guided by different examples of packages with a similar structure and when I install them I can import their modules.

I am relatively new to Python and there are still many things that I don't know well and I think there is something missing in my modules and my setup file.

I hope you can help me review the structure of my package and give me some ideas to solve my problem. Thanks in advance.


问:
Drawing on one device to be visible on other
I want to create a Pictionary kind of app where multiple users can play and guess the drawing made by one person. How is it possible to sync the drawing one device to others globally?</p>

答:
This can be achieve through Socket Programming.

You should use socket to sync in realtime by converting your drawing into
bitmap string.

And refesh you Local DB by using NSURLSession

Firebase is a Realtime Database, you can use it as well as other option.

The good explanation about socket : Tutorial1  & Tutrial 2

Happy coding!


问:
Combining (concatenating) date and time into a datetime
Using SQL Server 2008, this query works great:

```<code>select CAST(CollectionDate as DATE), CAST(CollectionTime as TIME)
from field
</code>```

Gives me two columns like this:

```<code>2013-01-25  18:53:00.0000000
2013-01-25  18:53:00.0000000
2013-01-25  18:53:00.0000000
2013-01-25  18:53:00.0000000
    .
    .
    .
</code>```

I'm trying to combine them into a single datetime using the plus sign, like this:

```<code>select CAST(CollectionDate as DATE) + CAST(CollectionTime as TIME)
from field
</code>```

I've looked on about ten web sites, including answers on this site (like this one), and they all seem to agree that the plus sign should work but I get the error:

Msg 8117, Level 16, State 1, Line 1

  Operand data type date is invalid for add operator.

All fields are non-zero and non-null. I've also tried the CONVERT function and tried to cast these results as varchars, same problem. This can't be as hard as I'm making it.

Can somebody tell me why this doesn't work? Thanks for any help.

答:
Concat date of one column with a time of another column in MySQL.</p>

```<code>SELECT CONVERT(concat(CONVERT('dateColumn',DATE),' ',CONVERT('timeColumn', TIME)), DATETIME) AS 'formattedDate' FROM dbs.tableName;
</code>```

Body:
Using SQL Server 2008, this query works great:

select CAST(CollectionDate as DATE), CAST(CollectionTime as TIME)
from field

Gives me two columns like this:

2013-01-25  18:53:00.0000000
2013-01-25  18:53:00.0000000
2013-01-25  18:53:00.0000000
2013-01-25  18:53:00.0000000
    .
    .
    .

I'm trying to combine them into a single datetime using the plus sign, like this:

select CAST(CollectionDate as DATE) + CAST(CollectionTime as TIME)
from field

I've looked on about ten web sites, including answers on this site (like this one), and they all seem to agree that the plus sign should work but I get the error:

Msg 8117, Level 16, State 1, Line 1

  Operand data type date is invalid for add operator.

All fields are non-zero and non-null. I've also tried the CONVERT function and tried to cast these results as varchars, same problem. This can't be as hard as I'm making it.

Can somebody tell me why this doesn't work? Thanks for any help.

Body:
Concat date of one column with a time of another column in MySQL.

SELECT CONVERT(concat(CONVERT('dateColumn',DATE),' ',CONVERT('timeColumn', TIME)), DATETIME) AS 'formattedDate' FROM dbs.tableName;


问:
Different LatLng imports
I have some type conflict while using LatLng's.
While this issue does not prevent the app from running without any problems, I want to optimize imports.

I import LatLng like this:

```<code>import com.google.android.gms.maps.model.LatLng;
</code>```

I can successfully use the imported LatLng like tis:

```<code>private LatLng[] places = {new LatLng(xx.xxxx, xx.xxxx)
};
</code>```

However after using the Directions API and using the resulting route:

```<code>List<com.google.maps.model.LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());
</code>```

The decode function belongs to PolylineEncoding.java, when I check the source code and search for LatLng import I came across with the import:

```<code>import com.google.maps.model.LatLng;
</code>```

Which differs from my original import

```<code>import com.google.android.gms.maps.model.LatLng;
</code>```

My goal here is to use LatLng like this:

```<code>List<LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());
</code>```

When I do that, I get the error(naturally):
Type conflict

How can I resolve this conflict?

Thank you in advance.

答:
I'm not sure if this is what you need, you can just write a static method to convert type:

```<code>static List<com.google.maps.model.LatLng> convertCoordType(List<com.google.android.gms.maps.model.LatLng> list) {
  List<com.google.maps.model.LatLng> resultList = new ArrayList<>();
  for (com.google.android.gms.maps.model.LatLng item : list) {
    resultList.add(new com.google.maps.model.LatLng(item.latitude, item.longitude));
  }
  return resultList;
}
</code>```

Then call convertCoordType to wrap around decode:

```<code>List<LatLng> decodedPath = convertCoordType(PolylineEncoding.decode(route.overviewPolyline.getEncodedPath()));
</code>```

Title: Different LatLng imports

Body:
I have some type conflict while using LatLng's.
While this issue does not prevent the app from running without any problems, I want to optimize imports.

I import LatLng like this:

import com.google.android.gms.maps.model.LatLng;

I can successfully use the imported LatLng like tis:

private LatLng[] places = {new LatLng(xx.xxxx, xx.xxxx)
};

However after using the Directions API and using the resulting route:

List<com.google.maps.model.LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());

The decode function belongs to PolylineEncoding.java, when I check the source code and search for LatLng import I came across with the import:

import com.google.maps.model.LatLng;

Which differs from my original import

import com.google.android.gms.maps.model.LatLng;

My goal here is to use LatLng like this:

List<LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());

When I do that, I get the error(naturally):
Type conflict

How can I resolve this conflict?

Thank you in advance.

Body:
I'm not sure if this is what you need, you can just write a static method to convert type:

static List<com.google.maps.model.LatLng> convertCoordType(List<com.google.android.gms.maps.model.LatLng> list) {
  List<com.google.maps.model.LatLng> resultList = new ArrayList<>();
  for (com.google.android.gms.maps.model.LatLng item : list) {
    resultList.add(new com.google.maps.model.LatLng(item.latitude, item.longitude));
  }
  return resultList;
}

Then call convertCoordType to wrap around decode:

List<LatLng> decodedPath = convertCoordType(PolylineEncoding.decode(route.overviewPolyline.getEncodedPath()));


问:
Get column value with COUNT of 0 in filtered result to display with count of 0
I have a simple SQL table that is tracking local backup status across a number of sites. I've got a view that tracks each site and backup run time, and whether it was overall successful or not. It looks something like this:

```<code>+--------+------------------+---------+
| SiteID | BackupTime       | Status  |
+--------+------------------+---------+
|   001  | 01/01/2020 04:00 | Success |
|   002  | 01/01/2020 04:00 | Success |
|   003  | 01/01/2020 04:00 | Success |
|   001  | 01/01/2020 08:00 | Success |
|   002  | 01/01/2020 08:00 | Unknown |
|   003  | 01/01/2020 08:00 | Success |
|   001  | 01/01/2020 12:00 | Unknown |
|   002  | 01/01/2020 12:00 | Success |
|   003  | 01/01/2020 12:00 | Success |
+--------+------------------+---------+
</code>```

For reporting, I've been asked to get the overall status for the last 24 hours, with each slice marked with a percentage. So I have this query to get me the last 24 hours (offset by 4 hours because of frequency of backups and timezones involved):

```<code>SELECT t1.Status,
       COUNT(*) AS Total,
       ROUND((CAST(COUNT(*) AS FLOAT) / CAST(t2.TotalCount AS FLOAT)) * 100.00, 2) AS TotalPct
FROM [Backup].[dbo].[BackupStatus] AS t1,
  (SELECT CAST(COUNT(*) AS FLOAT) AS TotalCount
   FROM [Backup].[dbo].[BackupStatus]
   WHERE BackupTime > DATEADD(HH, -28, GETDATE())
     AND BackupTime < DATEADD(HH, -4, GETDATE())) AS t2
WHERE t1.BackupTime > DATEADD(HH, -28, GETDATE())
  AND t1.BackupTime < DATEADD(HH, -4, GETDATE())
GROUP BY Status, TotalCount
ORDER BY Status
</code>```

The one issue I have with this is that if there were no problems during that time span, I'd only get a single row back for a Status of "Success".  As this dataset is then being bound to a pie chart (using PowerShell), it results in an error when there's no second row, so I need that second row ("Unknown", 0, 0.00%) so it can bind the second slice and put the info in the legend.

I've tried creating a temp table with both of those values, each with a count of 0, and using a union to add them to the result, but that just created them as additional rows to my previous results.

Am I going about this wrong? Should I be looking into a different way of accomplishing this? Or have I missed something about the way I've tried already?

答:
You can try like following by adding a 'Unknown' row using UNION and exclude it if it already exists.

```<code>;WITH cte
AS (
    SELECT t1.STATUS
        ,COUNT(*) AS Total
        ,ROUND((CAST(COUNT(*) AS FLOAT) / CAST(t2.TotalCount AS FLOAT)) * 100.00, 2) AS TotalPct
    FROM [Backup].[dbo].[BackupStatus] AS t1
        ,(
            SELECT CAST(COUNT(*) AS FLOAT) AS TotalCount
            FROM [Backup].[dbo].[BackupStatus]
            WHERE BackupTime > DATEADD(HH, - 28, GETDATE())
                AND BackupTime < DATEADD(HH, - 4, GETDATE())
            ) AS t2
    WHERE t1.BackupTime > DATEADD(HH, - 28, GETDATE())
        AND t1.BackupTime < DATEADD(HH, - 4, GETDATE())
    GROUP BY STATUS
        ,TotalCount

    UNION ALL

    SELECT 'Unknown'
        ,0
        ,0
    )
,cte2 AS (
SELECT *
    ,row_number() OVER (PARTITION BY STATUS ORDER BY TotalPct DESC) rn
FROM cte
)
SELECT *
FROM cte2
WHERE rn = 1
</code>```

Body:
I have a simple SQL table that is tracking local backup status across a number of sites. I've got a view that tracks each site and backup run time, and whether it was overall successful or not. It looks something like this:

+--------+------------------+---------+
| SiteID | BackupTime       | Status  |
+--------+------------------+---------+
|   001  | 01/01/2020 04:00 | Success |
|   002  | 01/01/2020 04:00 | Success |
|   003  | 01/01/2020 04:00 | Success |
|   001  | 01/01/2020 08:00 | Success |
|   002  | 01/01/2020 08:00 | Unknown |
|   003  | 01/01/2020 08:00 | Success |
|   001  | 01/01/2020 12:00 | Unknown |
|   002  | 01/01/2020 12:00 | Success |
|   003  | 01/01/2020 12:00 | Success |
+--------+------------------+---------+

For reporting, I've been asked to get the overall status for the last 24 hours, with each slice marked with a percentage. So I have this query to get me the last 24 hours (offset by 4 hours because of frequency of backups and timezones involved):

SELECT t1.Status,
       COUNT(*) AS Total,
       ROUND((CAST(COUNT(*) AS FLOAT) / CAST(t2.TotalCount AS FLOAT)) * 100.00, 2) AS TotalPct
FROM [Backup].[dbo].[BackupStatus] AS t1,
  (SELECT CAST(COUNT(*) AS FLOAT) AS TotalCount
   FROM [Backup].[dbo].[BackupStatus]
   WHERE BackupTime > DATEADD(HH, -28, GETDATE())
     AND BackupTime < DATEADD(HH, -4, GETDATE())) AS t2
WHERE t1.BackupTime > DATEADD(HH, -28, GETDATE())
  AND t1.BackupTime < DATEADD(HH, -4, GETDATE())
GROUP BY Status, TotalCount
ORDER BY Status

The one issue I have with this is that if there were no problems during that time span, I'd only get a single row back for a Status of "Success".  As this dataset is then being bound to a pie chart (using PowerShell), it results in an error when there's no second row, so I need that second row ("Unknown", 0, 0.00%) so it can bind the second slice and put the info in the legend.

I've tried creating a temp table with both of those values, each with a count of 0, and using a union to add them to the result, but that just created them as additional rows to my previous results.

Am I going about this wrong? Should I be looking into a different way of accomplishing this? Or have I missed something about the way I've tried already?

Body:
You can try like following by adding a 'Unknown' row using UNION and exclude it if it already exists.

;WITH cte
AS (
    SELECT t1.STATUS
        ,COUNT(*) AS Total
        ,ROUND((CAST(COUNT(*) AS FLOAT) / CAST(t2.TotalCount AS FLOAT)) * 100.00, 2) AS TotalPct
    FROM [Backup].[dbo].[BackupStatus] AS t1
        ,(
            SELECT CAST(COUNT(*) AS FLOAT) AS TotalCount
            FROM [Backup].[dbo].[BackupStatus]
            WHERE BackupTime > DATEADD(HH, - 28, GETDATE())
                AND BackupTime < DATEADD(HH, - 4, GETDATE())
            ) AS t2
    WHERE t1.BackupTime > DATEADD(HH, - 28, GETDATE())
        AND t1.BackupTime < DATEADD(HH, - 4, GETDATE())
    GROUP BY STATUS
        ,TotalCount

    UNION ALL

    SELECT 'Unknown'
        ,0
        ,0
    )
,cte2 AS (
SELECT *
    ,row_number() OVER (PARTITION BY STATUS ORDER BY TotalPct DESC) rn
FROM cte
)
SELECT *
FROM cte2
WHERE rn = 1


问:
Can't click moving div element in jQuery
I'm not sure whats happening as I have divs on the page that are clickable.

The only difference with the one that isn't working is it is moving up the page.

You can see here that an element with the 'rising' class will move up the page. (1px every 50ms) until it reaches the top, then it will be removed...

```<code>setInterval(function () {
$('.rising').css('bottom', '+=1');

$(".rising").each(function () {
  if ($(this).offset().top <= -60) {
    $(this).remove();
  }
});
}, 50);
</code>```

..before it reaches the top it should be clickable, here i've tried to add a class to it when clicked...

```<code>$('.rising').click(function () {
   $(this).addClass('blue');
});
</code>```

but this doesn't work.

I've made sure it has a high z-index and is recognised when hovered over but no click.

http://www.gogeye.com/ - here is an example (click the grey play button after you've waited for all to load)

答:
Try to bind click using $('.rising').on('click.someNameSpace',function(){...}); in click event handler of "play" button from where you create rising elements. Once they all removed use
$('.rising').off('click.someNameSpace'); --> this is because it will not consume more memory.

This will definitely solve your issue.

Body:
I'm not sure whats happening as I have divs on the page that are clickable.

The only difference with the one that isn't working is it is moving up the page.

You can see here that an element with the 'rising' class will move up the page. (1px every 50ms) until it reaches the top, then it will be removed...

setInterval(function () {
$('.rising').css('bottom', '+=1');

$(".rising").each(function () {
  if ($(this).offset().top <= -60) {
    $(this).remove();
  }
});
}, 50);

..before it reaches the top it should be clickable, here i've tried to add a class to it when clicked...

$('.rising').click(function () {
   $(this).addClass('blue');
});

but this doesn't work.

I've made sure it has a high z-index and is recognised when hovered over but no click.

http://www.gogeye.com/ - here is an example (click the grey play button after you've waited for all to load)


问:
Azure CLI Login within Docker Container
I have successfully created a docker image that runs inside a docker container.  The container successfully executes the image (a .NET app) but the image crashes shortly after startup because it encounters an error with Azure Services.  The reason is because the docker container is attempting to access Azure Services to fetch an authorization token (to fetch secrets from a key vault) and does not have authority to do so.

I should note that it is possible to run the app locally outside of a container via the Azure CLI after using az login to verify my credentials.  Then, when the app is started via Azure CLI, it is 'allowed' to access Azure Services to get autho tokens and consequentially fetch data from my key vault.

Would like to know if there is a way to run an az login script with credentials inside a docker container before the .NET app image executes, so that I can start the application from within the Azure CLI (inside the container) after my credentials have been verified.  I have looked through the documentation and have not seen a way to configure something like this.

答:
To use the Azure CLI and login inside the container, you need to install the Azure CLI inside the container, then login with an non-interactive model. I would recommend the service principal. You can take a look at the command:

```<code>az login --service-principal -u <app-url> -p <password-or-cert> --tenant <tenant>
</code>```

For more details, see Create an Azure service principal with Azure CLI. After login, then you can start your application as need.

Title: Azure CLI Login within Docker Container

Body:
To use the Azure CLI and login inside the container, you need to install the Azure CLI inside the container, then login with an non-interactive model. I would recommend the service principal. You can take a look at the command:

az login --service-principal -u <app-url> -p <password-or-cert> --tenant <tenant>

For more details, see Create an Azure service principal with Azure CLI. After login, then you can start your application as need.


问:
how to fetch the latest message from the user at the top position in recyclerview in kotlin with firebase
when I message to a user like Seraj, the message is updated in the recyclerview + timestamp. But the row of seraj data is not coming to top position in the recyclerview list.

```<code>class LatestActivity : AppCompatActivity() {

    val adapter = GroupAdapter<com.xwray.groupie.GroupieViewHolder>()

    companion object{
        var currentUser : User? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_latest)

//        recyclerview_lattestMessageActivity.isNestedScrollingEnabled = true
        recyclerview_lattestMessageActivity.setHasFixedSize(true)

        recyclerview_lattestMessageActivity.adapter = adapter

        val Layout_Manager = LinearLayoutManager(this)
//        Layout_Manager.stackFromEnd  = true
//        Layout_Manager.reverseLayout = true

        recyclerview_lattestMessageActivity.layoutManager = Layout_Manager
        Layout_Manager.findLastVisibleItemPosition()

        val decoration = DividerItemDecoration(applicationContext, LinearLayoutManager.VERTICAL)
        decoration.setDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.itemdecoration_by_line)!!)
        recyclerview_lattestMessageActivity.addItemDecoration(decoration)

        adapter.setOnItemClickListener { item, view ->
            val row = item as LattestMessageRow

            val intent = Intent(this, ChatLogActivity::class.java)
            intent.putExtra(New_Message_Activity.USER_KEY, row.chatPartnerUser)
            startActivity(intent)
        }

            fetchCurrentUser()
            verifyTheUserLoggedIn()
            ListenForLattestMessages()

        }

    val lattestMessageMap = HashMap<String, ChatMessage>()

    private fun ListenForLattestMessages(){

        val fromId =  FirebaseAuth.getInstance().uid
        val timestamp = System.currentTimeMillis()/1000
        val ref = FirebaseDatabase.getInstance().getReference("lattest-messages/$fromId")

        ref.addChildEventListener(object : ChildEventListener {

            override fun onChildChanged(dataSnapshot: DataSnapshot, previousChildName: String?) {
                dataSnapshot.getValue(ChatMessage::class.java)?.let {
                    lattestMessageMap[dataSnapshot.key!!] = it
                    refreshRecyclerViewMessages()
                }
            }
            override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) {
                dataSnapshot.getValue(ChatMessage::class.java)?.let {
                    lattestMessageMap[dataSnapshot.key!!] = it
                    refreshRecyclerViewMessages()
                }
            }

            override fun onCancelled(p0: DatabaseError) {
            }

            override fun onChildMoved(p0: DataSnapshot, p1: String?) {
            }

            override fun onChildRemoved(p0: DataSnapshot) {
            }

        })

    }

    private fun refreshRecyclerViewMessages(){

        adapter.clear()

        lattestMessageMap.values.forEach {
            adapter.add(LattestMessageRow(it))
            adapter.notifyItemInserted(0)
        }

    }

    private fun fetchCurrentUser(){

        val uid = FirebaseAuth.getInstance().uid
        val ref = FirebaseDatabase.getInstance().getReference("/users/$uid")

        ref.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onCancelled(p0: DatabaseError) {

            }

            override fun onDataChange(p0: DataSnapshot) {
                currentUser = p0.getValue(User::class.java)
                Log.d("LatestActivity", "The current user is : ${currentUser?.profile_image}")
            }
        })
    }

    private fun verifyTheUserLoggedIn() {

        val uid = FirebaseAuth.getInstance().uid
        if (uid == null) {

            val intent = Intent(this, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        when(item.itemId){
            R.id.new_message->{

                val intent = Intent(this, New_Message_Activity::class.java)
                startActivity(intent)

            }

            R.id.sign_out->{
                FirebaseAuth.getInstance().signOut()

                val intent = Intent(this, MainActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)
            }

        }

        return super.onOptionsItemSelected(item)

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.nav_menu,menu)
        return super.onCreateOptionsMenu(menu)
    }

}

private operator fun Boolean.invoke(b: Boolean) {

}
</code>```

class LattestMessageRow

```<code>    class LattestMessageRow(val chatMessage: ChatMessage) : Item<GroupieViewHolder>(){

        var chatPartnerUser : com.example.myapplication.User? = null
        var testing_abc = DateUtils.getFormattedTime(chatMessage.timestamp)

        override fun getLayout(): Int {
            return R.layout.lattest_message_row
        }

        override fun bind(viewHolder:GroupieViewHolder, position: Int) {
        viewHolder.itemView.lattestMessage_textView_lattest_message_row.text = chatMessage.text

            val chatPartnerId : String

            if (chatMessage.sendFromId == FirebaseAuth.getInstance().uid){
                chatPartnerId = chatMessage.sendToId!!
            }

            else{
                chatPartnerId = chatMessage.sendFromId!!
            }

            val ref = FirebaseDatabase.getInstance().getReference("users/$chatPartnerId")
            ref.child("lattest-messages").orderByChild("timestamp")
//                orderByKey().equalTo("timestamp")
//                .orderByChild("timestamp")
            ref.addListenerForSingleValueEvent(object : ValueEventListener {
                override fun onDataChange(p0: DataSnapshot) {

                    val message: String = p0.child("timestamp").getValue().toString()

                    chatPartnerUser = p0.getValue(User::class.java)

                    viewHolder.itemView.username_textView_lattest_messages_row.text = chatPartnerUser?.username
                    viewHolder.itemView.latest_msg_time.text = testing_abc

                    val targetUserProfileImage = viewHolder.itemView.userimage_imageView_lattest_message_row
                    Picasso.get().load(chatPartnerUser?.profile_image).into(targetUserProfileImage)

                }

                override fun onCancelled(p0: DatabaseError) {
                }
            })

        }

    }
</code>```

答: Collections.reverse(list); uses for reverse the data as lifo</p>

Body:
when I message to a user like Seraj, the message is updated in the recyclerview + timestamp. But the row of seraj data is not coming to top position in the recyclerview list.

class LatestActivity : AppCompatActivity() {

    val adapter = GroupAdapter<com.xwray.groupie.GroupieViewHolder>()

    companion object{
        var currentUser : User? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_latest)

//        recyclerview_lattestMessageActivity.isNestedScrollingEnabled = true
        recyclerview_lattestMessageActivity.setHasFixedSize(true)

        recyclerview_lattestMessageActivity.adapter = adapter

        val Layout_Manager = LinearLayoutManager(this)
//        Layout_Manager.stackFromEnd  = true
//        Layout_Manager.reverseLayout = true

        recyclerview_lattestMessageActivity.layoutManager = Layout_Manager
        Layout_Manager.findLastVisibleItemPosition()

        val decoration = DividerItemDecoration(applicationContext, LinearLayoutManager.VERTICAL)
        decoration.setDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.itemdecoration_by_line)!!)
        recyclerview_lattestMessageActivity.addItemDecoration(decoration)

        adapter.setOnItemClickListener { item, view ->
            val row = item as LattestMessageRow

            val intent = Intent(this, ChatLogActivity::class.java)
            intent.putExtra(New_Message_Activity.USER_KEY, row.chatPartnerUser)
            startActivity(intent)
        }

            fetchCurrentUser()
            verifyTheUserLoggedIn()
            ListenForLattestMessages()

        }

    val lattestMessageMap = HashMap<String, ChatMessage>()

    private fun ListenForLattestMessages(){

        val fromId =  FirebaseAuth.getInstance().uid
        val timestamp = System.currentTimeMillis()/1000
        val ref = FirebaseDatabase.getInstance().getReference("lattest-messages/$fromId")

        ref.addChildEventListener(object : ChildEventListener {

            override fun onChildChanged(dataSnapshot: DataSnapshot, previousChildName: String?) {
                dataSnapshot.getValue(ChatMessage::class.java)?.let {
                    lattestMessageMap[dataSnapshot.key!!] = it
                    refreshRecyclerViewMessages()
                }
            }
            override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) {
                dataSnapshot.getValue(ChatMessage::class.java)?.let {
                    lattestMessageMap[dataSnapshot.key!!] = it
                    refreshRecyclerViewMessages()
                }
            }

            override fun onCancelled(p0: DatabaseError) {
            }

            override fun onChildMoved(p0: DataSnapshot, p1: String?) {
            }

            override fun onChildRemoved(p0: DataSnapshot) {
            }

        })

    }

    private fun refreshRecyclerViewMessages(){

        adapter.clear()

        lattestMessageMap.values.forEach {
            adapter.add(LattestMessageRow(it))
            adapter.notifyItemInserted(0)
        }

    }

    private fun fetchCurrentUser(){

        val uid = FirebaseAuth.getInstance().uid
        val ref = FirebaseDatabase.getInstance().getReference("/users/$uid")

        ref.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onCancelled(p0: DatabaseError) {

            }

            override fun onDataChange(p0: DataSnapshot) {
                currentUser = p0.getValue(User::class.java)
                Log.d("LatestActivity", "The current user is : ${currentUser?.profile_image}")
            }
        })
    }

    private fun verifyTheUserLoggedIn() {

        val uid = FirebaseAuth.getInstance().uid
        if (uid == null) {

            val intent = Intent(this, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        when(item.itemId){
            R.id.new_message->{

                val intent = Intent(this, New_Message_Activity::class.java)
                startActivity(intent)

            }

            R.id.sign_out->{
                FirebaseAuth.getInstance().signOut()

                val intent = Intent(this, MainActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)
            }

        }

        return super.onOptionsItemSelected(item)

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.nav_menu,menu)
        return super.onCreateOptionsMenu(menu)
    }

}

private operator fun Boolean.invoke(b: Boolean) {

}

class LattestMessageRow

    class LattestMessageRow(val chatMessage: ChatMessage) : Item<GroupieViewHolder>(){

        var chatPartnerUser : com.example.myapplication.User? = null
        var testing_abc = DateUtils.getFormattedTime(chatMessage.timestamp)

        override fun getLayout(): Int {
            return R.layout.lattest_message_row
        }

        override fun bind(viewHolder:GroupieViewHolder, position: Int) {
        viewHolder.itemView.lattestMessage_textView_lattest_message_row.text = chatMessage.text

            val chatPartnerId : String

            if (chatMessage.sendFromId == FirebaseAuth.getInstance().uid){
                chatPartnerId = chatMessage.sendToId!!
            }

            else{
                chatPartnerId = chatMessage.sendFromId!!
            }

            val ref = FirebaseDatabase.getInstance().getReference("users/$chatPartnerId")
            ref.child("lattest-messages").orderByChild("timestamp")
//                orderByKey().equalTo("timestamp")
//                .orderByChild("timestamp")
            ref.addListenerForSingleValueEvent(object : ValueEventListener {
                override fun onDataChange(p0: DataSnapshot) {

                    val message: String = p0.child("timestamp").getValue().toString()

                    chatPartnerUser = p0.getValue(User::class.java)

                    viewHolder.itemView.username_textView_lattest_messages_row.text = chatPartnerUser?.username
                    viewHolder.itemView.latest_msg_time.text = testing_abc

                    val targetUserProfileImage = viewHolder.itemView.userimage_imageView_lattest_message_row
                    Picasso.get().load(chatPartnerUser?.profile_image).into(targetUserProfileImage)

                }

                override fun onCancelled(p0: DatabaseError) {
                }
            })

        }

    }


问:
How to deploy a dynamic webpack javascript chunkfile
We have a webpack setup where a base javascript file loads other chunkfiles with dynamic import. Now we want to deploy a patch with some js changes in a single chunkfile and renamed it with the same hash. But we are getting following error after deploying changed chunkfile:

```<code>libsMin.js.resource.1581412688349.js:1 Possible Unhandled Promise Rejection: ChunkLoadError: Loading chunk 57 failed.
(missing: https://www.domain.name/dist/js/templates.aa8e374955a21a7f93be.js)
</code>```

Is there any way to deploy a chunkfile to work with existing webpack bundles.

答:
Instead of generating a chunk, we have generated an entry file and loaded it asynchronously with webpack magic comments:</p>

```<code>// webpack code
const WEBPACK_ASSET_PATH = IS_PROD_ENV ? '/prod/assets/js/': '/dist/javascript/';

module.exports = {
    entry: {
        // other entries
        main: './src/main.js',
        templates: './src/templates.js',
    },
    new webpack.DefinePlugin({
        'WEBPACK_ASSET_PATH': JSON.stringify(WEBPACK_ASSET_PATH)
    })
}

// main.js code
import(/* webpackIgnore: true */ WEBPACK_PUBLIC_PATH + 'templates.js')
</code>```

Body:
We have a webpack setup where a base javascript file loads other chunkfiles with dynamic import. Now we want to deploy a patch with some js changes in a single chunkfile and renamed it with the same hash. But we are getting following error after deploying changed chunkfile:

libsMin.js.resource.1581412688349.js:1 Possible Unhandled Promise Rejection: ChunkLoadError: Loading chunk 57 failed.
(missing: https://www.domain.name/dist/js/templates.aa8e374955a21a7f93be.js)

Is there any way to deploy a chunkfile to work with existing webpack bundles.

Body:
Instead of generating a chunk, we have generated an entry file and loaded it asynchronously with webpack magic comments:

// webpack code
const WEBPACK_ASSET_PATH = IS_PROD_ENV ? '/prod/assets/js/': '/dist/javascript/';

module.exports = {
    entry: {
        // other entries
        main: './src/main.js',
        templates: './src/templates.js',
    },
    new webpack.DefinePlugin({
        'WEBPACK_ASSET_PATH': JSON.stringify(WEBPACK_ASSET_PATH)
    })
}

// main.js code
import(/* webpackIgnore: true */ WEBPACK_PUBLIC_PATH + 'templates.js')


问:
send excelsheet to azure function for processing
In our current project we want users to be able to upload excel files on our website, and those excel sheets should be processed (read every row and store them in database) using an Azure Function.

This functionality used to be in the backend from our .Net Core MVC project, using a Task<IActionResult> post method which accepted an IFormFile parameter. The sheet was processed (reading all the rows).

However, Azure functions doesn't seem to accept an IFormFile parameter. My question is how can I add this excelsheet data to the request?

This is post method that from the web app, that activates the azure function:

```<code>[HttpPost]
public async Task<ActionResult> Bulkimport(IFormFile excelsheet)
    {

        string azFunctionUri = "https://azfunctionsUri.azurewebsites.net";
        if (customerExists)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                 await excelsheet.CopyToAsync(ms).ConfigureAwait(false);
                 string content = Encoding.ASCII.GetString(ms.ToArray());
                 // use content as parameter in api builder method
                 IApiBuilder apiBuilder = new ApiBuilder();
                 HttpResponseMessage buildRequest = await apiBuilder.BuildFileRequest(azFunctionUri, content); // This builds the request and sends it to the azure function.
             }
         }
         return View();
      }
</code>```

BuildFileRequest.cs (helper method that constructs the request):

```<code>public async Task<HttpResponseMessage> BuildFileRequest(string uri, string content)
{
     MultipartFormDataContent multiContent = new MultipartFormDataContent();

     byte[] payload = Encoding.UTF8.GetBytes(content);
     multiContent.Add(new ByteArrayContent(payload), "files"); // name must be "files"
     HttpResponseMessage response = await httpClient.PostAsync($"{uri}", multiContent).ConfigureAwait(false);

     return response;
}
</code>```

I am stuck on how to receive this request in the Function and construct the excelfile from the request, so the rows can be read and processed in the database.

答:
According to my test, we can use the following code to receive the excel file.

Client Code. This is my test xlsx file

```<code>using (var httpClient = new HttpClient())
            {
                using (var form = new MultipartFormDataContent())
                {
                    using (var fs = File.OpenRead(filePath))
                    {
                        using (var streamContent = new StreamContent(fs))
                        {
                            using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()))
                            {
                                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

                                form.Add(fileContent, "file", Path.GetFileName(filePath));
                                HttpResponseMessage response = await httpClient.PostAsync(url, form);
                            }
                        }
                    }
                }
            }
</code>```

Azure function

```<code> public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            foreach (var file in req.Form.Files) {
             //Process excel file
             /* For example  use sdk : DocumentFormat.OpenXml.
For more details, please refer to https://learn.microsoft.com/en-us/office/open-xml/how-to-parse-and-read-a-large-spreadsheet

*/
                using (var stream = new MemoryStream()) {
                    await file.CopyToAsync(stream);
                    stream.Position = 0;
                    using (SpreadsheetDocument doc = SpreadsheetDocument.Open(stream, false)) {
                        WorkbookPart workbookPart = doc.WorkbookPart;
                        SharedStringTablePart sstpart = workbookPart.GetPartsOfType<SharedStringTablePart>().First();
                        SharedStringTable sst = sstpart.SharedStringTable;

                        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
                        Worksheet sheet = worksheetPart.Worksheet;

                        var cells = sheet.Descendants<Cell>();
                        var rows = sheet.Descendants<Row>();

                        log.LogInformation(string.Format("Row count = {0}", rows.LongCount()));
                        log.LogInformation(string.Format("Cell count = {0}", cells.LongCount()));

                    }

                }

            }
 return new OkObjectResult("Ok")
}
</code>```

Body:
In our current project we want users to be able to upload excel files on our website, and those excel sheets should be processed (read every row and store them in database) using an Azure Function.

This functionality used to be in the backend from our .Net Core MVC project, using a Task<IActionResult> post method which accepted an IFormFile parameter. The sheet was processed (reading all the rows).

However, Azure functions doesn't seem to accept an IFormFile parameter. My question is how can I add this excelsheet data to the request?

This is post method that from the web app, that activates the azure function:

[HttpPost]
public async Task<ActionResult> Bulkimport(IFormFile excelsheet)
    {

        string azFunctionUri = "https://azfunctionsUri.azurewebsites.net";
        if (customerExists)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                 await excelsheet.CopyToAsync(ms).ConfigureAwait(false);
                 string content = Encoding.ASCII.GetString(ms.ToArray());
                 // use content as parameter in api builder method
                 IApiBuilder apiBuilder = new ApiBuilder();
                 HttpResponseMessage buildRequest = await apiBuilder.BuildFileRequest(azFunctionUri, content); // This builds the request and sends it to the azure function.
             }
         }
         return View();
      }

BuildFileRequest.cs (helper method that constructs the request):

public async Task<HttpResponseMessage> BuildFileRequest(string uri, string content)
{
     MultipartFormDataContent multiContent = new MultipartFormDataContent();

     byte[] payload = Encoding.UTF8.GetBytes(content);
     multiContent.Add(new ByteArrayContent(payload), "files"); // name must be "files"
     HttpResponseMessage response = await httpClient.PostAsync($"{uri}", multiContent).ConfigureAwait(false);

     return response;
}

I am stuck on how to receive this request in the Function and construct the excelfile from the request, so the rows can be read and processed in the database.

Body:
According to my test, we can use the following code to receive the excel file.

Client Code. This is my test xlsx file

using (var httpClient = new HttpClient())
            {
                using (var form = new MultipartFormDataContent())
                {
                    using (var fs = File.OpenRead(filePath))
                    {
                        using (var streamContent = new StreamContent(fs))
                        {
                            using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()))
                            {
                                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

                                form.Add(fileContent, "file", Path.GetFileName(filePath));
                                HttpResponseMessage response = await httpClient.PostAsync(url, form);
                            }
                        }
                    }
                }
            }

Azure function

 public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            foreach (var file in req.Form.Files) {
             //Process excel file
             /* For example  use sdk : DocumentFormat.OpenXml.
For more details, please refer to https://learn.microsoft.com/en-us/office/open-xml/how-to-parse-and-read-a-large-spreadsheet

*/
                using (var stream = new MemoryStream()) {
                    await file.CopyToAsync(stream);
                    stream.Position = 0;
                    using (SpreadsheetDocument doc = SpreadsheetDocument.Open(stream, false)) {
                        WorkbookPart workbookPart = doc.WorkbookPart;
                        SharedStringTablePart sstpart = workbookPart.GetPartsOfType<SharedStringTablePart>().First();
                        SharedStringTable sst = sstpart.SharedStringTable;

                        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
                        Worksheet sheet = worksheetPart.Worksheet;

                        var cells = sheet.Descendants<Cell>();
                        var rows = sheet.Descendants<Row>();

                        log.LogInformation(string.Format("Row count = {0}", rows.LongCount()));
                        log.LogInformation(string.Format("Cell count = {0}", cells.LongCount()));

                    }

                }

            }
 return new OkObjectResult("Ok")
}


问:
SASL error when trying to connect to hive(hue) by python from my PC - Windows10
Need your help!

I read all the documentation that I found on the internet (StackOverflow, Github, etc.), but nothing helped.

I am trying to connect to hive(hue) by python from my PC, my script is:

When I run this code I got this error message:

```<code> Traceback (most recent call last):
 File "C:/Users/myuser/Documents/Python/testing.py", line 6, in <module>
 cursor = hive.connect('myconnect', port=10000, username='root').cursor()
 File "C:\Users\myuser\AppData\Local\Continuum\anaconda3\lib\site-packages\pyhive\hive.py", line 94,
 in connect
 return Connection(*args, **kwargs)
 File "C:\Users\myuser\AppData\Local\Continuum\anaconda3\lib\site-packages\pyhive\hive.py", line
 192, in __init__self._transport.open()File
 "C:\Users\myuser\AppData\Local\Continuum\anaconda3\lib\site-packages\thrift_sasl\__init__.py", line
 79, in open message=("Could not start SASL: %s" % self.sasl.getError()))
 thrift.transport.TTransport.TTransportException: Could not start SASL: b'Error in sasl_client_start
 (-4) SASL(-4): no mechanism available: Unable to find a callback: 2'
</code>```

My system detailes:

OS: Windows 10 Pro

Python version: Python 3.7.4

Distribution: Anaconda, Inc. on win32

答:
I found a way to work around the problem.

Actions taken:

Installed VirtualBox with Ubuntu OS on my PC.

Run Ubuntu as root.

Installed python, pip3 and the relevant libraries(pyhive, sasl, thrift_sasl, and thrift)

Run my code - works great!

My conclusion that my problem caused due to security(I am not an admin on my station) and windows issues.

Body:
Need your help!

I read all the documentation that I found on the internet (StackOverflow, Github, etc.), but nothing helped.

I am trying to connect to hive(hue) by python from my PC, my script is:

When I run this code I got this error message:

 Traceback (most recent call last):
 File "C:/Users/myuser/Documents/Python/testing.py", line 6, in <module>
 cursor = hive.connect('myconnect', port=10000, username='root').cursor()
 File "C:\Users\myuser\AppData\Local\Continuum\anaconda3\lib\site-packages\pyhive\hive.py", line 94,
 in connect
 return Connection(*args, **kwargs)
 File "C:\Users\myuser\AppData\Local\Continuum\anaconda3\lib\site-packages\pyhive\hive.py", line
 192, in __init__self._transport.open()File
 "C:\Users\myuser\AppData\Local\Continuum\anaconda3\lib\site-packages\thrift_sasl\__init__.py", line
 79, in open message=("Could not start SASL: %s" % self.sasl.getError()))
 thrift.transport.TTransport.TTransportException: Could not start SASL: b'Error in sasl_client_start
 (-4) SASL(-4): no mechanism available: Unable to find a callback: 2'

My system detailes:

OS: Windows 10 Pro

Python version: Python 3.7.4

Distribution: Anaconda, Inc. on win32


问:
Getting 400- Bad request for OGG file format while using Microsoft Speech to text REST API
I am using the Microsoft azure Speech to text REST API.
According to the docs, Ogg and Wav formats are supported in REST API. But, when I am sending the request for OGG audio file getting 400- Bad request error.

I am using following code to prepare request, And this is working for WAV audio format:

```<code>String url= "https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=simple";

private void connect(String extension) throws IOException {
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        if (extension.equalsIgnoreCase(Constants.WAV))
            connection.setRequestProperty("Content-type", "audio/wav; codecs=\"audio/pcm\"; samplerate=16000");
        else if (extension.equalsIgnoreCase(Constants.OGG))
            connection.setRequestProperty("Content-type", "audio/ogg; codecs=\"audio/opus\"");
        connection.setRequestProperty("Accept", "application/json;text/xml");
        connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
        connection.setRequestProperty("Transfer-Encoding", "chunked");
        connection.setRequestProperty("Expect", "100-continue");
        connection.setChunkedStreamingMode(0); // 0 == default chunk size
        connection.connect();
}
</code>```

Using this for uploading file:

```<code>private void upload(InputStream inputStream) throws IOException {
    try (OutputStream output = connection.getOutputStream()) {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            output.write(buffer, 0, length);
        }
        output.flush();
    }}
</code>```

答:
API is working fine for both WAV and OGG format. The request is also looking fine. The problem may be with the audio file sending in the request.
If you want to use OGG audio file format then the audio file must have the following properties:
          OGG (Codec: Opus, Bitrate: 16-bit, Sample rate: 16 kHz, Chanel: mono)

Otherwise, you will get 400 bad request error.
Make sure that codec is Opus because most of the OGG files have Vorbis codec which is not supported by the API.

You can use this website to convert an audio file in the required format.

Body:
I am using the Microsoft azure Speech to text REST API.
According to the docs, Ogg and Wav formats are supported in REST API. But, when I am sending the request for OGG audio file getting 400- Bad request error.

I am using following code to prepare request, And this is working for WAV audio format:

String url= "https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=simple";

private void connect(String extension) throws IOException {
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        if (extension.equalsIgnoreCase(Constants.WAV))
            connection.setRequestProperty("Content-type", "audio/wav; codecs=\"audio/pcm\"; samplerate=16000");
        else if (extension.equalsIgnoreCase(Constants.OGG))
            connection.setRequestProperty("Content-type", "audio/ogg; codecs=\"audio/opus\"");
        connection.setRequestProperty("Accept", "application/json;text/xml");
        connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
        connection.setRequestProperty("Transfer-Encoding", "chunked");
        connection.setRequestProperty("Expect", "100-continue");
        connection.setChunkedStreamingMode(0); // 0 == default chunk size
        connection.connect();
}

Using this for uploading file:

private void upload(InputStream inputStream) throws IOException {
    try (OutputStream output = connection.getOutputStream()) {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            output.write(buffer, 0, length);
        }
        output.flush();
    }}