问:
Retreiving ship-to-party country SAP QuickViewer
I've created a QuickView, where I enter Sales Document data as search criterias.
Selection fields are

```<code>VBAP-VBELN, VBAP-POSNR, VBAP-MATNR and VBAP-KWMENG
</code>```

As the Sales Document Item data.

Furthermore I retrieve the Schedule line date from

```<code>VBEP-EDATU
</code>```

From General Data in Customer Header KNA1, I use

```<code>KNA1-KUNNR and KNA1-LAND1
</code>```

Now, all connections and keys works out. My issue is, I wish to list the Country Key for ship-to-part rather than sold-to-party (which is represented by KUNNR). How could this be solved?

Tables are joined as follows:

```<code>VBAK-VBELN -> (VBAP-VBELN,-POSNR) -> (VBEP-VBELN, -POSNR)
VBAK-KUNNR -> KNA1-KUNNR
</code>```

I do know I would probably need a new table in here to retreive what Iæm looking for, but I'm completely blank. Any help would be greatly appriciated. I

答:
Ship-To-Party is stored in table VPBA (Sales Document Partners) in field KUNNR1 for partner function SH, so to select it you should join KNA1 not with VBAK but with VBPA-KUNNR restricting function to SH.

However, SQVI is a very primitive tool which doesn't allow setting complex (neither trivial) conditions so you should switch to ABAP queries tool (SQ01).

But just in case you wanna do this in SQVI here is the workaround:

Join necessary tables in SQVI builder

Add necessary KNA1 fields to layout: KUNNR and LANDX

Go to layout mode and enable selection by partner function PARVW

Run your query by SH partner function

and voilá! You will be shown only the orders with ship-to-party specified with their countries

Body:
I've created a QuickView, where I enter Sales Document data as search criterias.
Selection fields are

VBAP-VBELN, VBAP-POSNR, VBAP-MATNR and VBAP-KWMENG

As the Sales Document Item data.

Furthermore I retrieve the Schedule line date from

VBEP-EDATU

From General Data in Customer Header KNA1, I use

KNA1-KUNNR and KNA1-LAND1

Now, all connections and keys works out. My issue is, I wish to list the Country Key for ship-to-part rather than sold-to-party (which is represented by KUNNR). How could this be solved?

Tables are joined as follows:

VBAK-VBELN -> (VBAP-VBELN,-POSNR) -> (VBEP-VBELN, -POSNR)
VBAK-KUNNR -> KNA1-KUNNR

I do know I would probably need a new table in here to retreive what Iæm looking for, but I'm completely blank. Any help would be greatly appriciated. I


来源: stackexchange

问:
Python if statement not working inside function
I'm trying to make a guess the number game in python. However, in the again() function I cannot seem to get the if statement to run.

When I don't use the again function and copy and paste all the code in the respective positions, it works fine. However when I use the again function, the "play again?" question is asked but the if statement is ignored, causing the while loop to continue endlessly. I have tried using the global function but on the second time I input a guess, it comes up with TypeError: 'str' object is not callable .

```<code>import random

def guess():
    global num
    num = random.randint(1,3)
    guessat  = input("Out of 1 to 3, which number do you guess? ")
    return(guessat)

def again():
    global again
    again = input("Play again? ")
    if again in ["y","yes"]:
        guessing = True
    else:
        guessing = False

print("Welcome to Guess the Number!")

guessing = True

while guessing:
    guessy = guess()
    guessy = int(guessy)
    if guessy == num:
        print("You got it right!")
        again()

    elif guessy != num:
        print("Wrong number!")
        again()
quit()
</code>```

When I input "no" or anything else for the question "Play Again?" I expect the program to exit the while loop and quit.

答:
Avoid naming your variable again inside a function called again. However in regards to your infinite loop problem, you set local variable guessing inside the again function, no the global variable guessing, hence the variable checking the while loop condition is not affected at all.  Might I suggest:

```<code>def again():
    global guessing
    play_again_input = input("Play again? ")
    if play_again_input in ["y","yes"]:
        guessing = True
    else:
        guessing = False

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a guess the number game in python. However, in the again() function I cannot seem to get the if statement to run.

When I don't use the again function and copy and paste all the code in the respective positions, it works fine. However when I use the again function, the "play again?" question is asked but the if statement is ignored, causing the while loop to continue endlessly. I have tried using the global function but on the second time I input a guess, it comes up with TypeError: 'str' object is not callable .

import random

def guess():
    global num
    num = random.randint(1,3)
    guessat  = input("Out of 1 to 3, which number do you guess? ")
    return(guessat)

def again():
    global again
    again = input("Play again? ")
    if again in ["y","yes"]:
        guessing = True
    else:
        guessing = False

print("Welcome to Guess the Number!")

guessing = True

while guessing:
    guessy = guess()
    guessy = int(guessy)
    if guessy == num:
        print("You got it right!")
        again()

    elif guessy != num:
        print("Wrong number!")
        again()
quit()

When I input "no" or anything else for the question "Play Again?" I expect the program to exit the while loop and quit.

Body:
Avoid naming your variable again inside a function called again. However in regards to your infinite loop problem, you set local variable guessing inside the again function, no the global variable guessing, hence the variable checking the while loop condition is not affected at all.  Might I suggest:

def again():
    global guessing
    play_again_input = input("Play again? ")
    if play_again_input in ["y","yes"]:
        guessing = True
    else:
        guessing = False


问:
Why is basemap plotting this latitude and longitude off land when I know it to be on land?
I'm creating a scatter plot on top of a map of NSW, Australia in basemap and the location of a radar (which i know to be lon=151.2095, lat=-33.7008) is plotted as being in the ocean when it's actually inland. Why is this happening?</p>

```<code>from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt

def plot_gauges_on_map():

    lon_0, lat_0 = 151.2095, -33.7008
    width = 1000000
    m = Basemap(width=width,height=width,projection='aeqd',
            lat_0=lat_0,lon_0=lon_0)
    # fill background.
    m.drawmapboundary(fill_color='dodgerblue')
    # draw coasts and fill continents.
    m.drawcoastlines(linewidth=0.5)
    m.fillcontinents(color='peru',lake_color='dodgerblue')
    # draw a black dot at the radar.
    xpt, ypt = m(lon_0, lat_0)
    m.plot([xpt],[ypt],'ko')
    # draw the title.
    plt.title('Terrey Hills Radar')
    plt.show()

plot_gauges_on_map()
</code>```

答: You did not specify the resolution of the map boundary database to use, hence, the crude database is in effect. To get proper resolution in your case, the option resolution="i" should be added in Basemap() statement, where "i" stands for intermediate. Possible resolutions are:- c(crude, the default), l(low), i, h(high) and f(full). The output of your plot will look like the following.

Body:
I'm creating a scatter plot on top of a map of NSW, Australia in basemap and the location of a radar (which i know to be lon=151.2095, lat=-33.7008) is plotted as being in the ocean when it's actually inland. Why is this happening?

from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt

def plot_gauges_on_map():

    lon_0, lat_0 = 151.2095, -33.7008
    width = 1000000
    m = Basemap(width=width,height=width,projection='aeqd',
            lat_0=lat_0,lon_0=lon_0)
    # fill background.
    m.drawmapboundary(fill_color='dodgerblue')
    # draw coasts and fill continents.
    m.drawcoastlines(linewidth=0.5)
    m.fillcontinents(color='peru',lake_color='dodgerblue')
    # draw a black dot at the radar.
    xpt, ypt = m(lon_0, lat_0)
    m.plot([xpt],[ypt],'ko')
    # draw the title.
    plt.title('Terrey Hills Radar')
    plt.show()

plot_gauges_on_map()


问:
Exporting Access Query to Excel
I've got an Access 2007 database on which I have created around 15 SQL queries to process specific data, I have created a main frame navigation menu using menus in Access, I now need to extract all th queries to Excel using VBA code, I have managed to do this with the code below by creating a button and specifying this code to it.

```<code>Private Sub query1_Click()
DoCmd.TransferSpreadsheet acExport, _
acSpreadsheetTypeExcel9, "Total Users and Sessions", _
"C:\UsersandSessions.xls", , "Total Users & Sessions"
End Sub
</code>```

Now my problem at the moment is that fine the query is exported to Excel, but it is done so without any formatting applied at all, I would like to add some formatting at least to the headers and maybe a title inside the spreadsheet, and one thing I dont really like is that all records are being started from the first cell. Also I would prefer that if I hit that button again in Access and the Excel spreadsheet has already exists with that query output then when clicked again it will write again to a the next available sheet.

Any suggestions or ideas a very welcome.

答:
The short story, is you can't. You might be able to do some scripting on the Excel side to format the resulting file. If you want something pretty, you probably want to create a report.

You could, instead mount the excel sheet as a table, and then on a separated sheet in the excel file, reference the first sheet, and format the second sheet for viewing.

ContentLicense: CC BY-SA 2.5

Title: Exporting Access Query to Excel

Body:
I've got an Access 2007 database on which I have created around 15 SQL queries to process specific data, I have created a main frame navigation menu using menus in Access, I now need to extract all th queries to Excel using VBA code, I have managed to do this with the code below by creating a button and specifying this code to it.

Private Sub query1_Click()
DoCmd.TransferSpreadsheet acExport, _
acSpreadsheetTypeExcel9, "Total Users and Sessions", _
"C:\UsersandSessions.xls", , "Total Users & Sessions"
End Sub

Now my problem at the moment is that fine the query is exported to Excel, but it is done so without any formatting applied at all, I would like to add some formatting at least to the headers and maybe a title inside the spreadsheet, and one thing I dont really like is that all records are being started from the first cell. Also I would prefer that if I hit that button again in Access and the Excel spreadsheet has already exists with that query output then when clicked again it will write again to a the next available sheet.

Any suggestions or ideas a very welcome.

ContentLicense: CC BY-SA 3.0


问:
Unexpected exception: java.io.IOException: RESTEASY007550: Unable to get boundary for multipart
Using nexus-repository-apt plugin and trying to upload *.deb packages with curl according to this instructions:

```<code>curl -u user:pass -X POST -H "Content-Type: multipart/form-data" --data-binary "@package.deb" http://nexus_url:8081/repository/repo_name/
</code>```

Also tried to upload from API section in the Nexus GUI. Could not make it work.

Any help?

答: I've solved the problem and issued to the maintainer. It might be a bug of 3.15.2 version of Nexus including Apt repository. After upgrading to 3.16.1 the issue has been wiped out. So, It works fine now.</p>

Body:
Using nexus-repository-apt plugin and trying to upload *.deb packages with curl according to this instructions:

curl -u user:pass -X POST -H "Content-Type: multipart/form-data" --data-binary "@package.deb" http://nexus_url:8081/repository/repo_name/

Also tried to upload from API section in the Nexus GUI. Could not make it work.

Any help?


问:
Display serializer field as 'named' field instead of a primary key field
I am working on a Django REST framework API and are running into some issues with using the Serializers. I'll try to isolate the problem a little.  Basically there are the Room and a Location models.

```<code>class Room(models.Model):
    uuid = UUIDField(primary_key=True)
    ...
    location = models.ForeignKey(Location, related_name='room')
    ...
class Location(models.Model):
    uuid = UUIDField(primary_key=True)
    name = models.CharField(max_length=255)
    def __unicode__(self):
        return unicode(self.name)
</code>```

and the corresponding serializers,

```<code>class RoomSerializer(serializers.ModelSerializer):
    location = serializers.RelatedField()
    class Meta:
        model = Room
        fields = ('uuid', 'location')
class LocationSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Location
        fields = ('uuid', 'name')
</code>```

I've explored the many ways to change the display of uuid to the location name including the use of serializers.SerializerMethodField() and also using the above serializers.RelatedField(), and they do work.  As a reference, see the JSON output below.

```<code>{
    "uuid": "491ab09d-qqqq-wwww-eeee-5801dbac0fef",
    "location": "Kota Kinabalu",
    "created": "2014-09-03T07:52:45.399Z",
    "modified": "2014-09-03T07:52:45.530Z"
}
</code>```

However, I am not able to do a model.save() on Room since Django or rather the database (postgresql in my case) complains that the location_id is empty.  I think its due to the fact that when I send a POST request to the API endpoint /api/rooms/ the location_id is left blank when I modify my RoomSerializer.

If one uses a default ModelViewSet, you would see that the Location field is missing from the default form.

How do I use serializers properly such that I could display the name of the location ("Kota Kinabalu" instead of a uuid string like 6e6acbbb-xxxx-yyyy-zzzz-1cf1a5bac22c) and I am still able to accept a correct POST request?

答: I know it had been a long time and you might have already got the solution. But I am posting here the solution how I implemented this. After reading a bit of docs, I came across a method named to_representation(). I used this method to convert the data which is being returned in form of primary key to any other form. You can refer about this method in the docs here.

Body:
I am working on a Django REST framework API and are running into some issues with using the Serializers. I'll try to isolate the problem a little.  Basically there are the Room and a Location models.

class Room(models.Model):
    uuid = UUIDField(primary_key=True)
    ...
    location = models.ForeignKey(Location, related_name='room')
    ...
class Location(models.Model):
    uuid = UUIDField(primary_key=True)
    name = models.CharField(max_length=255)
    def __unicode__(self):
        return unicode(self.name)

and the corresponding serializers,

class RoomSerializer(serializers.ModelSerializer):
    location = serializers.RelatedField()
    class Meta:
        model = Room
        fields = ('uuid', 'location')
class LocationSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Location
        fields = ('uuid', 'name')

I've explored the many ways to change the display of uuid to the location name including the use of serializers.SerializerMethodField() and also using the above serializers.RelatedField(), and they do work.  As a reference, see the JSON output below.

{
    "uuid": "491ab09d-qqqq-wwww-eeee-5801dbac0fef",
    "location": "Kota Kinabalu",
    "created": "2014-09-03T07:52:45.399Z",
    "modified": "2014-09-03T07:52:45.530Z"
}

However, I am not able to do a model.save() on Room since Django or rather the database (postgresql in my case) complains that the location_id is empty.  I think its due to the fact that when I send a POST request to the API endpoint /api/rooms/ the location_id is left blank when I modify my RoomSerializer.

If one uses a default ModelViewSet, you would see that the Location field is missing from the default form.

How do I use serializers properly such that I could display the name of the location ("Kota Kinabalu" instead of a uuid string like 6e6acbbb-xxxx-yyyy-zzzz-1cf1a5bac22c) and I am still able to accept a correct POST request?


问:
Writing a django view that does not return an object
I am writing a django view that just post some data and update a variable in the database. The view will not return anything as I am submitting the data using jquery-ajax.

I am getting the following error:

```<code>The view mysite.views.home didn't return an HttpResponse object
</code>```

Again I do not wish to return an html page or anything of that sort. How can I achieve that?

答:
```<code>return HttpResponse("")
</code>```

I usually do:

```<code>return HttpResponse("OK")
</code>```

just because. In case I want to add error codes in later.

Body:
I am writing a django view that just post some data and update a variable in the database. The view will not return anything as I am submitting the data using jquery-ajax.

I am getting the following error:

The view mysite.views.home didn't return an HttpResponse object

Again I do not wish to return an html page or anything of that sort. How can I achieve that?

Body:
return HttpResponse("")

I usually do:

return HttpResponse("OK")

just because. In case I want to add error codes in later.


问:
make iframe height dynamic based on content inside- JQUERY/Javascript
I am loading an aspx web page in an iframe. The content in the Iframe can be of more height than the iframe's height. The iframe should not have scroll bars.

I have a wrapper div tag inside the iframe which basically is all the content.  I wrote some jQuery to make the resize happen :

```<code>$("#TB_window", window.parent.document).height($("body").height() + 50);
</code>```

where
TB_window is the div in which the Iframe is contained.

body - the body tag of the aspx in the iframe.

This script is attached to the iframe content. I am getting the TB_window element from the parent page. While this works fine on Chrome, but the TB_window collapses in Firefox. I am really confused/lost on why that happens.

答:
Other answers were not working for me so i did some changes. Hope this will help</p>

```<code>$('#iframe').on("load", function() {
    var iframe = $(window.top.document).find("#iframe");
    iframe.height(iframe[0].ownerDocument.body.scrollHeight+'px' );
});
</code>```

Body:
I am loading an aspx web page in an iframe. The content in the Iframe can be of more height than the iframe's height. The iframe should not have scroll bars.

I have a wrapper div tag inside the iframe which basically is all the content.  I wrote some jQuery to make the resize happen :

$("#TB_window", window.parent.document).height($("body").height() + 50);

where
TB_window is the div in which the Iframe is contained.

body - the body tag of the aspx in the iframe.

This script is attached to the iframe content. I am getting the TB_window element from the parent page. While this works fine on Chrome, but the TB_window collapses in Firefox. I am really confused/lost on why that happens.

Body:
Other answers were not working for me so i did some changes. Hope this will help

$('#iframe').on("load", function() {
    var iframe = $(window.top.document).find("#iframe");
    iframe.height(iframe[0].ownerDocument.body.scrollHeight+'px' );
});


问:
spring boot how to handle fault tolerance in async method?
Suppose I have a caller to distribute work to multiple async tasks:

```<code>public class Caller{
    public boolean run() {
        for (int i = 0: i< 100; i++) {
            worker.asyncFindOrCreate(entites[i]);
        }
        return true;
    }

public class Worker{
    @Autowired
    Dao dao;

    @Async
    public E asyncFindOrCreate(User entity) {
        return dao.findByName(entity.getName).elseGet(() -> dao.save(entity));
    }
}
</code>```

If we have 2 same entities:
with the synchronized method, the first one will be created and then the second one will be retrieved from the existing entity;
with async, the second entities might pass the findByName and go to save because the first entity hasn't been saved yet, which cause the save of the second entity throws unique identifier error.

Is there a way to add some fault tolerance mechanic to have some features like retry and skipAfterRetry, in particular for database operations.

答:
In this special case you should convert your array to a map. Use the name property as a key, so there will be no duplicated entries.

However, if this method also can be called by multiple threads (ie. it's in a web-server) or there are multiple instances running it's still not fail-safe.

In generic, you should let the DB to check the uniqueness. There is no safest/easiest way to do that. Put the save method inside a try-catch block and check/handle the unique identifier exception.

Body:
Suppose I have a caller to distribute work to multiple async tasks:

public class Caller{
    public boolean run() {
        for (int i = 0: i< 100; i++) {
            worker.asyncFindOrCreate(entites[i]);
        }
        return true;
    }

public class Worker{
    @Autowired
    Dao dao;

    @Async
    public E asyncFindOrCreate(User entity) {
        return dao.findByName(entity.getName).elseGet(() -> dao.save(entity));
    }
}

If we have 2 same entities:
with the synchronized method, the first one will be created and then the second one will be retrieved from the existing entity;
with async, the second entities might pass the findByName and go to save because the first entity hasn't been saved yet, which cause the save of the second entity throws unique identifier error.

Is there a way to add some fault tolerance mechanic to have some features like retry and skipAfterRetry, in particular for database operations.


问:
How can I add up the cost?
What I need to do so that I can add every element of LbCount to LbSum when I click the button.

When I click button it will cover up my previous number like this:

Here is my code:

```<code>private void button1_Click(object sender, EventArgs e)
        {
            int sum = 0;
            sum += Convert.ToInt32(LbCount.Text);
            LbSum.Text = Convert.ToString(sum);
        }
</code>```

答:
Judging from the names of the text fields, you seem to want to add the number in LbCount to LbSum when the button is clicked.

sum should not start with 0, then. sum should start with whatever is in LbSum, right?

```<code>int sum = Convert.ToInt32(LbSum.Text);
sum += Convert.ToInt32(LbCount.Text);
LbSum.Text = Convert.ToString(sum);
</code>```

Title: How can I add up the cost?

Body:
What I need to do so that I can add every element of LbCount to LbSum when I click the button.

When I click button it will cover up my previous number like this:

Here is my code:

private void button1_Click(object sender, EventArgs e)
        {
            int sum = 0;
            sum += Convert.ToInt32(LbCount.Text);
            LbSum.Text = Convert.ToString(sum);
        }

Body:
Judging from the names of the text fields, you seem to want to add the number in LbCount to LbSum when the button is clicked.

sum should not start with 0, then. sum should start with whatever is in LbSum, right?

int sum = Convert.ToInt32(LbSum.Text);
sum += Convert.ToInt32(LbCount.Text);
LbSum.Text = Convert.ToString(sum);


问:
Laravel query fiter review in with relation
```<code>$listing = Listing::orderBy('created_at','DESC')->where('user_id', Auth::User()->id)
->with('reviews')
->with('posts')
->get();
</code>```

How can i filter review order when i try this

```<code> ->whereHas('reviews', function ($query) {
            $query->where('status', 'Public');
        })->orderBy('created_at','DESC')
</code>```

I want am trying to use orderBy on review but when i try orderBy on review its filter post also but i do not want to post so please Help !

答:
You can apply more filters in the whereHas functon, but to apply more conditions like ordering and limiting you should do that in the with function call on the correct relationship you will be loading.</p>

```<code>$listing = Listing::where('user_id', Auth::User()->id)
    ->with(['reviews' => function ($query) {
        return $query->orderByDesc('created_at');
    }, 'posts'])
    ->whereHas('reviews', function ($query) {
        return $query->where('status', 'Public');
    })
    ->orderByDesc('created_at')
    ->get();
</code>```

Body:
$listing = Listing::orderBy('created_at','DESC')->where('user_id', Auth::User()->id)
->with('reviews')
->with('posts')
->get();

How can i filter review order when i try this

 ->whereHas('reviews', function ($query) {
            $query->where('status', 'Public');
        })->orderBy('created_at','DESC')

I want am trying to use orderBy on review but when i try orderBy on review its filter post also but i do not want to post so please Help !

Body:
You can apply more filters in the whereHas functon, but to apply more conditions like ordering and limiting you should do that in the with function call on the correct relationship you will be loading.

$listing = Listing::where('user_id', Auth::User()->id)
    ->with(['reviews' => function ($query) {
        return $query->orderByDesc('created_at');
    }, 'posts'])
    ->whereHas('reviews', function ($query) {
        return $query->where('status', 'Public');
    })
    ->orderByDesc('created_at')
    ->get();


答:
Hi please insert int sum = 0 out of click event Like

```<code>public int sum = 0;

private void button1_Click(object sender, EventArgs e)
{
  sum += Convert.ToInt32(LbCount.Text);
  LbSum.Text = Convert.ToString(sum);
}
</code>```

And I suggest use try catch for Convert , Because it'll be Take Exception

Title: How can I add up the cost?

Body:
Hi please insert int sum = 0 out of click event Like

public int sum = 0;

private void button1_Click(object sender, EventArgs e)
{
  sum += Convert.ToInt32(LbCount.Text);
  LbSum.Text = Convert.ToString(sum);
}

And I suggest use try catch for Convert , Because it'll be Take Exception


问:
Azure Function App with no function and Running background threads
Is it possible to run an Azure Function app that has no function, but running threads that will read messages from Azure Service Bus?

It seems the thread is not reading mesasge from ASB.

Update

My Function app (has no functions) works locally, but not on Azure.

答:
Azure Functions are marketed as

More than just event-driven serverless compute

The event-driven part is key here. The actual Function in a Function app is the code that's triggered by for instance a timer, a message on a Service Bus or an Event Grid event. All other code should be supporting in getting that job done. If you have a Functions App that doesn't have any functions, you don't have any entry point for your code to run.

Two main remarks:

It kinda feels like you're trying to abuse Functions

Why not use Service Bus triggers instead of a thread doing the same thing manually?

Have a look at this example, taken from Azure Service Bus bindings for Azure Functions - Trigger - C# example:

```<code>[FunctionName("ServiceBusQueueTriggerCSharp")]
public static void Run(
    [ServiceBusTrigger("myqueue", AccessRights.Manage, Connection = "ServiceBusConnection")]
    string myQueueItem,
    Int32 deliveryCount,
    DateTime enqueuedTimeUtc,
    string messageId,
    ILogger log)
{
    log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
    log.LogInformation($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.LogInformation($"DeliveryCount={deliveryCount}");
    log.LogInformation($"MessageId={messageId}");
}
</code>```

This example shows a C# function that reads message metadata and logs a Service Bus queue message.

Body:
Azure Functions are marketed as

More than just event-driven serverless compute

The event-driven part is key here. The actual Function in a Function app is the code that's triggered by for instance a timer, a message on a Service Bus or an Event Grid event. All other code should be supporting in getting that job done. If you have a Functions App that doesn't have any functions, you don't have any entry point for your code to run.

Two main remarks:

It kinda feels like you're trying to abuse Functions

Why not use Service Bus triggers instead of a thread doing the same thing manually?

Have a look at this example, taken from Azure Service Bus bindings for Azure Functions - Trigger - C# example:

[FunctionName("ServiceBusQueueTriggerCSharp")]
public static void Run(
    [ServiceBusTrigger("myqueue", AccessRights.Manage, Connection = "ServiceBusConnection")]
    string myQueueItem,
    Int32 deliveryCount,
    DateTime enqueuedTimeUtc,
    string messageId,
    ILogger log)
{
    log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
    log.LogInformation($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.LogInformation($"DeliveryCount={deliveryCount}");
    log.LogInformation($"MessageId={messageId}");
}

This example shows a C# function that reads message metadata and logs a Service Bus queue message.


问:
Should Builder.build() return a default state?
Using the Builder pattern there is always the question whether the fields do have a default value or not? I cannot find a reliable source where that's clearly defined...

The problem is readability: What is Car.Builder().build() returning? I always need to check the specific implementation of the Builder to see which default values are used. Shouldn't Builder be used to create complex objects which do not have a simple default state by definition?

An alternative would be to check whether all mandatory fields are set inside of the build() method:

```<code>fun build() : Car {
    return if (doors != null && hp != null) Car(doors, hp, color) // color can be null
    else throw IllegalArgumentException("Door count and HP is mandatory!")
}
</code>```

...or is this considered bad practice?

答:
You  didn't find a general answer to your question, because there is none. It depends on the context the builder is used in or the object's details that the builder is constructing.

Sometimes it makes perfect sense to return a default object, where all of its members are initialized to default values. But then this default object must be valid. E.g. to build a logger object, it would be valid to return a logger that logs to the console with a default formatting and default log level. Someone could instantly use it.

But sometimes a pure default object doesn't make sense. Creating a completely configured default HTTP client is not sensible, because it won't deliver the minimum expected behavior, since the target URL might be something unexpected. In this case you could write a constructor for the builder class that takes an URL as parameter (maybe some data object as well) and then preconfigure the client object with default values (e.g. default request header, default timeout, default buffer size, etc). This object then would satisfy the minimum usage expectations. Every subsequent call of a setter will then overwrite the default, where each setter should check for validity of the arguments before accepting them.

But you should always, when possible, try to use defaults over exceptions. When an object's construction requires mandatory information, then make this public by putting them in a constructor. This way you are safe that your object is always in a valid and useful state. In case of the HTTP client builder you could throw an exception if the URL is malformed, to give the developer a hint that his code that constructs the URL might have flaws. Maybe read Best practices for exceptions.

With the solution in mind to write constructors in order to collect all required parameters (that cannot be set to useful default values), your build() finalize method can and should always and at any time return a valid and useful object. This makes your builder convenient. (Otherwise the user of the builder would be forced to read documentation to know which setters to call. Everybody knows that you don't like to write documentations. Everybody knows that you don't like to read documentation before the use of some classes. Everybody feels the same).

Body:
Using the Builder pattern there is always the question whether the fields do have a default value or not? I cannot find a reliable source where that's clearly defined...

The problem is readability: What is Car.Builder().build() returning? I always need to check the specific implementation of the Builder to see which default values are used. Shouldn't Builder be used to create complex objects which do not have a simple default state by definition?

An alternative would be to check whether all mandatory fields are set inside of the build() method:

fun build() : Car {
    return if (doors != null && hp != null) Car(doors, hp, color) // color can be null
    else throw IllegalArgumentException("Door count and HP is mandatory!")
}

...or is this considered bad practice?


问:
Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'
I am a greenhorn in gradle and i just tried to create a new Android Gradle Project in IntelliJ. After filling up the necessities it started to download something which took hours so i decided to force quit my IDE and open the project again.

And now I am getting this:

And when I open the IDE logs, I see this:

```<code>2014-12-13 22:27:37,940 [103759372]   INFO - .BaseProjectImportErrorHandler - Failed to import Gradle project at '/Users/ramswaroop/Documents/My Workspace/PopoPics'
org.gradle.tooling.GradleConnectionException: Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:124)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:112)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
    at org.gradle.tooling.internal.consumer.DefaultBuildActionExecuter.run(DefaultBuildActionExecuter.java:46)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.doResolveProjectInfo(GradleProjectResolver.java:177)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.access$300(GradleProjectResolver.java:63)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:363)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:335)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:214)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:95)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:63)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:137)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:123)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:475)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$2.run(ExternalSystemUtil.java:552)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:621)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$3.run(ProgressManagerImpl.java:194)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.a(ProgressManagerImpl.java:281)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:233)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:181)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$9.run(ProgressManagerImpl.java:530)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)
Caused by: java.nio.channels.OverlappingFileLockException
    at sun.nio.ch.FileChannelImpl$SharedFileLockTable.checkList(FileChannelImpl.java:1166)
    at sun.nio.ch.FileChannelImpl$SharedFileLockTable.add(FileChannelImpl.java:1068)
    at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:868)
    at java.nio.channels.FileChannel.tryLock(FileChannel.java:962)
    at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:51)
    at org.gradle.wrapper.Install.createDist(Install.java:44)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:118)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:112)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
2014-12-13 22:27:37,941 [103759373]   WARN - nal.AbstractExternalSystemTask - Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
com.intellij.openapi.externalSystem.model.ExternalSystemException: Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectImportErrorHandler.createUserFriendlyError(AbstractProjectImportErrorHandler.java:106)
    at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.getUserFriendlyError(BaseProjectImportErrorHandler.java:158)
    at org.jetbrains.plugins.gradle.service.project.BaseGradleProjectResolverExtension.getUserFriendlyError(BaseGradleProjectResolverExtension.java:401)
    at com.android.tools.idea.gradle.project.AndroidGradleProjectResolver.getUserFriendlyError(AndroidGradleProjectResolver.java:309)
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:164)
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:164)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:369)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:335)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:214)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:95)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:63)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:137)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:123)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:475)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$2.run(ExternalSystemUtil.java:552)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:621)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$3.run(ProgressManagerImpl.java:194)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.a(ProgressManagerImpl.java:281)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:233)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:181)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$9.run(ProgressManagerImpl.java:530)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)

2014-12-13 22:27:37,942 [103759374]   WARN - radle.project.ProjectSetUpTask -
2014-12-13 22:27:37,942 [103759374]   INFO - radle.project.ProjectSetUpTask - Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.

Consult IDE log for more details (Help | Show Log)
 </code>```

INFO: Running on Mac Yosemite with Gradle 2.2 and IntelliJ IDEA 14 Ultimate.

答:
https://services.gradle.org/distributions/gradle-2.1-all.zip

open this link in the browser and download the zip file and extract it to folder

Before extraction please delete the old folder whose name ends gradle-2.1-all and then you can start extracting

if you are window user extract it to this folder

C:\Users{Your-Name}.gradle\wrapper\dists

after that just restart your android studio.
I hope it works it works for me .

Body:
I am a greenhorn in gradle and i just tried to create a new Android Gradle Project in IntelliJ. After filling up the necessities it started to download something which took hours so i decided to force quit my IDE and open the project again.

And now I am getting this:

And when I open the IDE logs, I see this:

2014-12-13 22:27:37,940 [103759372]   INFO - .BaseProjectImportErrorHandler - Failed to import Gradle project at '/Users/ramswaroop/Documents/My Workspace/PopoPics'
org.gradle.tooling.GradleConnectionException: Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:124)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:112)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
    at org.gradle.tooling.internal.consumer.DefaultBuildActionExecuter.run(DefaultBuildActionExecuter.java:46)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.doResolveProjectInfo(GradleProjectResolver.java:177)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.access$300(GradleProjectResolver.java:63)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:363)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:335)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:214)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:95)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:63)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:137)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:123)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:475)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$2.run(ExternalSystemUtil.java:552)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:621)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$3.run(ProgressManagerImpl.java:194)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.a(ProgressManagerImpl.java:281)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:233)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:181)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$9.run(ProgressManagerImpl.java:530)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)
Caused by: java.nio.channels.OverlappingFileLockException
    at sun.nio.ch.FileChannelImpl$SharedFileLockTable.checkList(FileChannelImpl.java:1166)
    at sun.nio.ch.FileChannelImpl$SharedFileLockTable.add(FileChannelImpl.java:1068)
    at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:868)
    at java.nio.channels.FileChannel.tryLock(FileChannel.java:962)
    at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:51)
    at org.gradle.wrapper.Install.createDist(Install.java:44)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:118)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:112)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
2014-12-13 22:27:37,941 [103759373]   WARN - nal.AbstractExternalSystemTask - Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
com.intellij.openapi.externalSystem.model.ExternalSystemException: Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectImportErrorHandler.createUserFriendlyError(AbstractProjectImportErrorHandler.java:106)
    at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.getUserFriendlyError(BaseProjectImportErrorHandler.java:158)
    at org.jetbrains.plugins.gradle.service.project.BaseGradleProjectResolverExtension.getUserFriendlyError(BaseGradleProjectResolverExtension.java:401)
    at com.android.tools.idea.gradle.project.AndroidGradleProjectResolver.getUserFriendlyError(AndroidGradleProjectResolver.java:309)
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:164)
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:164)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:369)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:335)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:214)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:95)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:63)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:137)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:123)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:475)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$2.run(ExternalSystemUtil.java:552)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:621)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$3.run(ProgressManagerImpl.java:194)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.a(ProgressManagerImpl.java:281)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:233)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:181)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$9.run(ProgressManagerImpl.java:530)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)

2014-12-13 22:27:37,942 [103759374]   WARN - radle.project.ProjectSetUpTask -
2014-12-13 22:27:37,942 [103759374]   INFO - radle.project.ProjectSetUpTask - Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.

Consult IDE log for more details (Help | Show Log)

INFO: Running on Mac Yosemite with Gradle 2.2 and IntelliJ IDEA 14 Ultimate.


问:
How to get the foreground app and/or activity?
I am working on a remote control for integration between Android TV devices and Smartthings Hub. I want to be able to see which app is active (foreground, displayed to the user).

My app is a soft Keyboard and thus it is running as a service (Input Method Service)

I found the following code and tried it:

```<code>ActivityManager.RunningAppProcessInfo result=null;
String pname="process: ";
ActivityManager activityManager = (ActivityManager) ctx.getSystemService( Context.ACTIVITY_SERVICE );
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();

Iterator <ActivityManager.RunningAppProcessInfo> i = appProcesses.iterator();

while(i.hasNext()){
    ActivityManager.RunningAppProcessInfo info = i.next();
    Log.d("LOG : " , info.processName);

    if(info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
    {
         result=info;
         break;
    }
}
</code>```

But it doesn't displa any apps. If I remove the condition

```<code>"info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND"
</code>```

then it displays my app (keyboard) as the running app.

So it seems like this only shows apps or activities that are part of my app. How can I reach this information for the whole Android system ?
Does it require a permission ?

If this is not doable with a normal app, and is possible only with some additional permissions, or accessibility features, I am open to use it, because the app is not a commercial app and will not be distributed if any other Smartthings user doesn't ask for it.
I just can't use rooted device. Other than that I can try anything.

答:
Try this :</p>

```<code>public static boolean isAppStatus(Context context) {
    boolean isAppStatus = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isAppStatus = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isAppStatus = false;
        }
    }
    return isAppStatus;
}
</code>```

Body:
I am working on a remote control for integration between Android TV devices and Smartthings Hub. I want to be able to see which app is active (foreground, displayed to the user).

My app is a soft Keyboard and thus it is running as a service (Input Method Service)

I found the following code and tried it:

ActivityManager.RunningAppProcessInfo result=null;
String pname="process: ";
ActivityManager activityManager = (ActivityManager) ctx.getSystemService( Context.ACTIVITY_SERVICE );
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();

Iterator <ActivityManager.RunningAppProcessInfo> i = appProcesses.iterator();

while(i.hasNext()){
    ActivityManager.RunningAppProcessInfo info = i.next();
    Log.d("LOG : " , info.processName);

    if(info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
    {
         result=info;
         break;
    }
}

But it doesn't displa any apps. If I remove the condition

"info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND"

then it displays my app (keyboard) as the running app.

So it seems like this only shows apps or activities that are part of my app. How can I reach this information for the whole Android system ?
Does it require a permission ?

If this is not doable with a normal app, and is possible only with some additional permissions, or accessibility features, I am open to use it, because the app is not a commercial app and will not be distributed if any other Smartthings user doesn't ask for it.
I just can't use rooted device. Other than that I can try anything.

Body:
Try this :

public static boolean isAppStatus(Context context) {
    boolean isAppStatus = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isAppStatus = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isAppStatus = false;
        }
    }
    return isAppStatus;
}


问:
Error java.lang.OutOfMemoryError: GC overhead limit exceeded
I get this error message as I execute my JUnit tests:

```<code>java.lang.OutOfMemoryError: GC overhead limit exceeded
</code>```

I know what an OutOfMemoryError is, but what does GC overhead limit mean? How can I solve this?

答:
It's usually the code. Here's a simple example:

```<code>import java.util.*;

public class GarbageCollector {

    public static void main(String... args) {

        System.out.printf("Testing...%n");
        List<Double> list = new ArrayList<Double>();
        for (int outer = 0; outer < 10000; outer++) {

            // list = new ArrayList<Double>(10000); // BAD
            // list = new ArrayList<Double>(); // WORSE
            list.clear(); // BETTER

            for (int inner = 0; inner < 10000; inner++) {
                list.add(Math.random());
            }

            if (outer % 1000 == 0) {
                System.out.printf("Outer loop at %d%n", outer);
            }

        }
        System.out.printf("Done.%n");
    }
}
</code>```

Using Java 1.6.0_24-b07 on a Windows 7 32 bit.

```<code>java -Xloggc:gc.log GarbageCollector
</code>```

Then look at gc.log

Triggered 444 times using BAD method

Triggered 666 times using WORSE method

Triggered 354 times using BETTER method

Now granted, this is not the best test or the best design but when faced with a situation where you have no choice but implementing such a loop or when dealing with existing code that behaves badly, choosing to reuse objects instead of creating new ones can reduce the number of times the garbage collector gets in the way...

Body:
I get this error message as I execute my JUnit tests:

java.lang.OutOfMemoryError: GC overhead limit exceeded

I know what an OutOfMemoryError is, but what does GC overhead limit mean? How can I solve this?

Body:
It's usually the code. Here's a simple example:

import java.util.*;

public class GarbageCollector {

    public static void main(String... args) {

        System.out.printf("Testing...%n");
        List<Double> list = new ArrayList<Double>();
        for (int outer = 0; outer < 10000; outer++) {

            // list = new ArrayList<Double>(10000); // BAD
            // list = new ArrayList<Double>(); // WORSE
            list.clear(); // BETTER

            for (int inner = 0; inner < 10000; inner++) {
                list.add(Math.random());
            }

            if (outer % 1000 == 0) {
                System.out.printf("Outer loop at %d%n", outer);
            }

        }
        System.out.printf("Done.%n");
    }
}

Using Java 1.6.0_24-b07 on a Windows 7 32 bit.

java -Xloggc:gc.log GarbageCollector

Then look at gc.log

Triggered 444 times using BAD method

Triggered 666 times using WORSE method

Triggered 354 times using BETTER method

Now granted, this is not the best test or the best design but when faced with a situation where you have no choice but implementing such a loop or when dealing with existing code that behaves badly, choosing to reuse objects instead of creating new ones can reduce the number of times the garbage collector gets in the way...


问:
Cannot upgrade or otherwise change tex-live installation on Heroku
Pushes of updates to my app to Heroku are now rejected because of a tex-live incompatibility.  See the error message below.

Heroku error message

```<code>remote: tlmgr: Remote repository is newer than local (2018 < 2019)
remote: Cross release updates are only supported with
remote:   update-tlmgr-latest(.sh/.exe) --update
remote: Please see https://tug.org/texlive/upgrade.html for
details.
remote:  !     Push rejected, failed to compile TeX Live app.
</code>```

I have tried the following:

Add a file texlive.repository with contents ftp://tug.org/historic/systems/texlive/2018/tlnet-final.  This does not work because the texlive repository lacks a required cryptographic certificate.

Delete the texlive buildpack and start over.  Below is my buildpack config. However, when I try to remove it, I get this message:

$ heroku buildpacks:remove syphar/heroku-buildpack-tex
›   Error: invalid json response body at https://buildpack-registry.heroku.com/buildpacks/syphar%2Fheroku-buildpack-tex reason: Unexpected end of JSON input

At this point I am stuck!

Heroku buildpacks

```<code>$ heroku buildpacks
=== nshost Buildpack URLs
1. https://github.com/HashNuke/heroku-buildpack-elixir.git
2. https://github.com/syphar/heroku-buildpack-tex.git
</code>```

答:
This works: in the file texlive.packages, replace

```<code>ftp://tug.org/historic/systems/texlive/2018/tlnet-final
</code>```

with

```<code>https://www.math.utah.edu/pub/texlive/historic/systems/texlive/2018/tlnet-final
</code>```

Solution courtesy of Nelson Beebe, University of Utah Mathematics Department

Body:
Pushes of updates to my app to Heroku are now rejected because of a tex-live incompatibility.  See the error message below.

Heroku error message

remote: tlmgr: Remote repository is newer than local (2018 < 2019)
remote: Cross release updates are only supported with
remote:   update-tlmgr-latest(.sh/.exe) --update
remote: Please see https://tug.org/texlive/upgrade.html for
details.
remote:  !     Push rejected, failed to compile TeX Live app.

I have tried the following:

Add a file texlive.repository with contents ftp://tug.org/historic/systems/texlive/2018/tlnet-final.  This does not work because the texlive repository lacks a required cryptographic certificate.

Delete the texlive buildpack and start over.  Below is my buildpack config. However, when I try to remove it, I get this message:

$ heroku buildpacks:remove syphar/heroku-buildpack-tex
›   Error: invalid json response body at https://buildpack-registry.heroku.com/buildpacks/syphar%2Fheroku-buildpack-tex reason: Unexpected end of JSON input

At this point I am stuck!

Heroku buildpacks

$ heroku buildpacks
=== nshost Buildpack URLs
1. https://github.com/HashNuke/heroku-buildpack-elixir.git
2. https://github.com/syphar/heroku-buildpack-tex.git

Body:
This works: in the file texlive.packages, replace

ftp://tug.org/historic/systems/texlive/2018/tlnet-final

with

https://www.math.utah.edu/pub/texlive/historic/systems/texlive/2018/tlnet-final

Solution courtesy of Nelson Beebe, University of Utah Mathematics Department


问:
How to force a webpage to think that it is in or out focus in FireFox?
Note: This is the EXACT same question as this, but for FireFox.

Is there a way to "force" the tab to think that it is in or out of focus, like toggle pseudo classes in Developer Tools, but for the entire tab.

I am running FireFox on Windows 10. I could not find a way to do this using Developer Tools, and do not want to setup a whole testing framework just for such a simple thing.

Thank you for your time.

答: In the Firefox DevTools this is not possible (as of Firefox 67), so I've created an enhancement request to add this feature.</p>


问:
fetch multiple rows, store in 1 variable and insert into table
I have to fetch bulk record and insert into table using loop
I have little confusion how to fetch and insert record using loop. Below I have shared  what I have done so far .</p>

```<code>declare
    stud_Id varchar;
begin
    stud_Id := select student_id from student_backup where is_active_flg ='Y';

    for i in 1 ..stud_Id.count
    loop
        insert into users(student_id,password,status) values(stud_Id(i),'password','status')
        where not exists (select student_id from users where student_id=stud_Id(i))
    end loop;

    commit;
end;
/
</code>```

答:
You can use the following :

```<code>declare
  stud_Id student_backup.student_id%type;
begin
     select nvl(max(student_id),0) into stud_Id
       from student_backup
      where is_active_flg ='Y';

   if stud_Id >0 then
    for i in 1 ..stud_Id
    loop
       insert into users(student_id,password,status)
       select b.student_id,'password','status'
         from student_backup b
         left join users u on b.student_id = u.student_id
        where is_active_flg ='Y'
          and b.student_id = i;
    end loop;
   end if;
    commit;
end;
/
</code>```

Demo

P.S. If I understood you want to perform, you don't need to use for loop(including if statement) and the select statement in the beginning, but directly apply the insert statement by removing the part and b.student_id = i.
So, convert your block to the one as below :

```<code>declare
  stud_Id student_backup.student_id%type;
begin

       insert into users(student_id,password,status)
       select b.student_id,'password','status'
         from student_backup b
         left join users u on b.student_id = u.student_id
        where is_active_flg ='Y' ;
    commit;
end;
/
</code>```

Body:
I have to fetch bulk record and insert into table using loop
I have little confusion how to fetch and insert record using loop. Below I have shared  what I have done so far .

declare
    stud_Id varchar;
begin
    stud_Id := select student_id from student_backup where is_active_flg ='Y';

    for i in 1 ..stud_Id.count
    loop
        insert into users(student_id,password,status) values(stud_Id(i),'password','status')
        where not exists (select student_id from users where student_id=stud_Id(i))
    end loop;

    commit;
end;
/

Body:
You can use the following :

declare
  stud_Id student_backup.student_id%type;
begin
     select nvl(max(student_id),0) into stud_Id
       from student_backup
      where is_active_flg ='Y';

   if stud_Id >0 then
    for i in 1 ..stud_Id
    loop
       insert into users(student_id,password,status)
       select b.student_id,'password','status'
         from student_backup b
         left join users u on b.student_id = u.student_id
        where is_active_flg ='Y'
          and b.student_id = i;
    end loop;
   end if;
    commit;
end;
/

Demo

P.S. If I understood you want to perform, you don't need to use for loop(including if statement) and the select statement in the beginning, but directly apply the insert statement by removing the part and b.student_id = i.
So, convert your block to the one as below :

declare
  stud_Id student_backup.student_id%type;
begin

       insert into users(student_id,password,status)
       select b.student_id,'password','status'
         from student_backup b
         left join users u on b.student_id = u.student_id
        where is_active_flg ='Y' ;
    commit;
end;
/


问:
How can I store variable having high range in C program?
Suppose I want to store variable having datatype integer.
Integer provide certain range 2 byte or 4 byte.
Also range of -32768 to 32767.
I want to store 32768.
How can I?</p>

答:
There is a data type that is guaranteed to hold that range in all C implementations. It is called long int. Perhaps use that one instead.

Additionally 32-bit platforms will usually have it 32-bit; the only difference here is 64-bit platforms where some might use a 64-bit datatype for it.

If storage requirements are important, use int32_t.


问:
how to fetch a images from database using retrofit 2
Hi I am new to Retrofit framework for Android. I could get JSON responses from REST services using it but I don't know how to fetch a image using retrofit2. I am trying to fetch the image in recyclerview from the database

Code is Here:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_product);
    Intent intent = getIntent();
    parent = intent.getStringExtra("Parent");
    child = intent.getStringExtra("Child");
    Toast.makeText(this, parent+child, Toast.LENGTH_SHORT).show();
    //init firebase
    //load menu
    recycler_menu =(RecyclerView)findViewById(R.id.recycler_view);
    apiInterface =
    ApiClient.getRetrofit().create(ApiInterface.class);
    recycler_menu.setLayoutManager(new GridLayoutManager(this, 2));
    recycler_menu.setHasFixedSize(true);

    mUploads = new ArrayList<>();
    loadMenu();

   }
     private void loadMenu(){

     Toast.makeText(Product.this, "Hello",
     Toast.LENGTH_SHORT).show();
     Call<Upload> call = apiInterface.performProduct(parent,child);
     call.enqueue(new Callback<Upload>() {
         @Override
         public void onResponse(Call<Upload> call, Response<Upload>
        response) {
             Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
             mAdapter = new ImageAdapter(Product.this, mUploads);
             mRecyclerView.setAdapter(mAdapter);
         }
         @Override
         public void onFailure(Call<Upload> call, Throwable t) {

         }
     });
 }}
</code>```

ImageAdapter.java .

```<code>public ImageAdapter(Context context, List<Upload> uploads) {
    mContext = context;
    mUploads = uploads;
}

@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
    return new ImageViewHolder(v);
}

@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getImgName());
    holder.textViewPrice.setText(uploadCurrent.getPrice());
    Picasso.get()
            .load(uploadCurrent.getImgUrl())
            .placeholder(R.mipmap.ic_launcher)
            .fit()
            .centerCrop()
            .into(holder.imageView);
    //holder.collection.setText(uploadCurrent.getmRadioGroup());
}

@Override
public int getItemCount() {
    return mUploads.size();
}

public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
        View.OnCreateContextMenuListener {
    public TextView textViewName;
    public TextView textViewPrice;
    public ImageView imageView;

    public ImageViewHolder(View itemView) {
        super(itemView);

        textViewName = itemView.findViewById(R.id.menu_name);
        textViewPrice = itemView.findViewById(R.id.menu_price);
        imageView = itemView.findViewById(R.id.menu_price);

        itemView.setOnClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onClick(View v) {
        if (mListener != null) {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                mListener.onItemClick(position);
            }
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select Action");
        MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
        MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
    }

}

public interface OnItemClickListener {
    void onItemClick(int position);
}

public void setOnItemClickListener(OnItemClickListener listener) {
    mListener = listener;
}
</code>```

Upload.class

```<code>public class Upload {
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@SerializedName("id")
private String id;
@SerializedName("image")
private String imgName;
@SerializedName("imgUrl")
private String imgUrl;
@SerializedName("price")
private String price;
@SerializedName("description")
private String Description;
@SerializedName("response")
private String Response;

public  String getResponse(){
    return Response;
}

public Upload() {
}

public Upload(String id,String imgName, String imgUrl, String price, String Description) {
    this.id = id;
    this.imgName = imgName;
    this.imgUrl = imgUrl;
    this.price = price;
    this.Description = Description;
}

public String getImgName() {
    return imgName;
}

public void setImgName(String imgName) {
    this.imgName = imgName;
}

public String getImgUrl() {
    return imgUrl;
}

public void setImgUrl(String imgUrl) {
    this.imgUrl = imgUrl;
}

public String getDescription() {
    return Description;
}

public void setDescription(String Description) {
    this.Description = Description;
}
public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}
</code>```

}

PHP File:

```<code> <?php include ("conn.php");
 $type = $_GET["parent"];
 $ttype = $_GET["child"];
 $sth = $conn->prepare("SELECT * from product where type='$type' &&
 s_type='$ttype'");
 $sth->execute();
 While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
 $name = $data['name'];
 $id = $data['id'];
 $des = $data['description'];
 $price = $data['price'];
 $image = $data['image'];
 $status = "ok";
 echo
 json_encode(array("response"=>$status,
 "img"=>$image,"name"=>$name,
 "id"=>$id,"description"=>$des,"price"=>$price));
  }?>
</code>```

this code does nothing a blank screen appers

答:
You are sending blank ArrayList to Adapter

look here In onCreate() you assign mUploads = new ArrayList<>();

then you just pass mUploads to mAdapter = new ImageAdapter(Product.this, mUploads);

chnage code from

```<code> @Override
     public void onResponse(Call<Upload> call, Response<Upload>
    response) {
         Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
         mAdapter = new ImageAdapter(Product.this, mUploads);
         mRecyclerView.setAdapter(mAdapter);
     }
</code>```

to ,

```<code> @Override
     public void onResponse(Call<Upload> call, Response<Upload>
    response) {
         Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
         mUploads=responese.body();  //@ add this line
         mAdapter = new ImageAdapter(Product.this, mUploads);
         mRecyclerView.setAdapter(mAdapter);
     }
</code>```

Body:
Hi I am new to Retrofit framework for Android. I could get JSON responses from REST services using it but I don't know how to fetch a image using retrofit2. I am trying to fetch the image in recyclerview from the database

Code is Here:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_product);
    Intent intent = getIntent();
    parent = intent.getStringExtra("Parent");
    child = intent.getStringExtra("Child");
    Toast.makeText(this, parent+child, Toast.LENGTH_SHORT).show();
    //init firebase
    //load menu
    recycler_menu =(RecyclerView)findViewById(R.id.recycler_view);
    apiInterface =
    ApiClient.getRetrofit().create(ApiInterface.class);
    recycler_menu.setLayoutManager(new GridLayoutManager(this, 2));
    recycler_menu.setHasFixedSize(true);

    mUploads = new ArrayList<>();
    loadMenu();

   }
     private void loadMenu(){

     Toast.makeText(Product.this, "Hello",
     Toast.LENGTH_SHORT).show();
     Call<Upload> call = apiInterface.performProduct(parent,child);
     call.enqueue(new Callback<Upload>() {
         @Override
         public void onResponse(Call<Upload> call, Response<Upload>
        response) {
             Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
             mAdapter = new ImageAdapter(Product.this, mUploads);
             mRecyclerView.setAdapter(mAdapter);
         }
         @Override
         public void onFailure(Call<Upload> call, Throwable t) {

         }
     });
 }}

ImageAdapter.java .

public ImageAdapter(Context context, List<Upload> uploads) {
    mContext = context;
    mUploads = uploads;
}

@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
    return new ImageViewHolder(v);
}

@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getImgName());
    holder.textViewPrice.setText(uploadCurrent.getPrice());
    Picasso.get()
            .load(uploadCurrent.getImgUrl())
            .placeholder(R.mipmap.ic_launcher)
            .fit()
            .centerCrop()
            .into(holder.imageView);
    //holder.collection.setText(uploadCurrent.getmRadioGroup());
}

@Override
public int getItemCount() {
    return mUploads.size();
}

public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
        View.OnCreateContextMenuListener {
    public TextView textViewName;
    public TextView textViewPrice;
    public ImageView imageView;

    public ImageViewHolder(View itemView) {
        super(itemView);

        textViewName = itemView.findViewById(R.id.menu_name);
        textViewPrice = itemView.findViewById(R.id.menu_price);
        imageView = itemView.findViewById(R.id.menu_price);

        itemView.setOnClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onClick(View v) {
        if (mListener != null) {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                mListener.onItemClick(position);
            }
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select Action");
        MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
        MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
    }

}

public interface OnItemClickListener {
    void onItemClick(int position);
}

public void setOnItemClickListener(OnItemClickListener listener) {
    mListener = listener;
}

Upload.class

public class Upload {
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@SerializedName("id")
private String id;
@SerializedName("image")
private String imgName;
@SerializedName("imgUrl")
private String imgUrl;
@SerializedName("price")
private String price;
@SerializedName("description")
private String Description;
@SerializedName("response")
private String Response;

public  String getResponse(){
    return Response;
}

public Upload() {
}

public Upload(String id,String imgName, String imgUrl, String price, String Description) {
    this.id = id;
    this.imgName = imgName;
    this.imgUrl = imgUrl;
    this.price = price;
    this.Description = Description;
}

public String getImgName() {
    return imgName;
}

public void setImgName(String imgName) {
    this.imgName = imgName;
}

public String getImgUrl() {
    return imgUrl;
}

public void setImgUrl(String imgUrl) {
    this.imgUrl = imgUrl;
}

public String getDescription() {
    return Description;
}

public void setDescription(String Description) {
    this.Description = Description;
}
public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}

}

PHP File:

 <?php include ("conn.php");
 $type = $_GET["parent"];
 $ttype = $_GET["child"];
 $sth = $conn->prepare("SELECT * from product where type='$type' &&
 s_type='$ttype'");
 $sth->execute();
 While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
 $name = $data['name'];
 $id = $data['id'];
 $des = $data['description'];
 $price = $data['price'];
 $image = $data['image'];
 $status = "ok";
 echo
 json_encode(array("response"=>$status,
 "img"=>$image,"name"=>$name,
 "id"=>$id,"description"=>$des,"price"=>$price));
  }?>

this code does nothing a blank screen appers

Body:
You are sending blank ArrayList to Adapter

look here In onCreate() you assign mUploads = new ArrayList<>();

then you just pass mUploads to mAdapter = new ImageAdapter(Product.this, mUploads);

chnage code from

 @Override
     public void onResponse(Call<Upload> call, Response<Upload>
    response) {
         Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
         mAdapter = new ImageAdapter(Product.this, mUploads);
         mRecyclerView.setAdapter(mAdapter);
     }

to ,

 @Override
     public void onResponse(Call<Upload> call, Response<Upload>
    response) {
         Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
         mUploads=responese.body();  //@ add this line
         mAdapter = new ImageAdapter(Product.this, mUploads);
         mRecyclerView.setAdapter(mAdapter);
     }


问:
Automatically checking for a new version of my application
Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available.

The problem is that I have no idea about what have to be done on the server side.

I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP ?) to the server, but what is going to respond to this request ? In order to go through firewalls, I guess I'll have to use port 80 ? Is this correct ?

Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate ?

@pilif : thanks for your detailed answer. There is still something which is unclear for me :

like

http://www.example.com/update?version=1.2.4

Then you can return what ever you want, probably also the download-URL of the installer of the new version.

How do I return something ? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess) ? How can I decode the ?version=1.2.4 part in order to return something accordingly ?

答: Just put an (XML) file on your server with the version number of the latest version, and a URL to the download the new version from. Your application can then request the XML file, look if the version differs from its own, and take action accordingly.</p>

OwnerDisplayName: Jérôme

LastEditorDisplayName: Jérôme

OwnerDisplayName: wvdschel


问:
Program to view what a webpage would look through a mobile phone
I know this might off subject but what's a good program let's me view what a website might look like on a iPhone or other mobile device which connects to the Internet. Dreamweaver cs3 might have this but I can't find it anyone know?</p>

答: Aptana has an iPhone plug-in which also includes a built in display. All of which are free.</p>

OwnerDisplayName: Sarmenhb

OwnerDisplayName: Pat


问:
Trying to convert string to datetime using ParseExact
I am trying to convert a string like this '5/29/2019 8:46:47 PM' to a datetime for use as a PowerShell object but I am getting an error

I am trying to use the [datetime]::ParseExact method

```<code>$Date = "5/29/2019 8:46:47 PM"

[datetime]::ParseExact($Date,'MM dd yyyy HH:mm:ss', $null)
</code>```

Instead of getting a datetime object, I just get this error:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."

Any help will be greatly appreciated.

答:
Try one of these.

```<code>($stringToDatetime1 = '5/29/2019 8:46:47 PM' | Get-Date)
Wednesday, May 29, 2019 8:46:47 PM

($stringToDatetime2 = [DateTime]::ParseExact('5/29/2019 8:46:47 PM','M/d/yyyy h:mm:ss tt',$null))
Wednesday, May 29, 2019 8:46:47 PM

($stringToDatetime3 = [Datetime]'5/29/2019 8:46:47 PM')
Wednesday, May 29, 2019 8:46:47 PM
</code>```

BTW, this error is fully documented here:

PowerShell [DateTime] throws the error “String was not recognized as a valid DateTime.”

Body:
I am trying to convert a string like this '5/29/2019 8:46:47 PM' to a datetime for use as a PowerShell object but I am getting an error

I am trying to use the [datetime]::ParseExact method

$Date = "5/29/2019 8:46:47 PM"

[datetime]::ParseExact($Date,'MM dd yyyy HH:mm:ss', $null)

Instead of getting a datetime object, I just get this error:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."

Any help will be greatly appreciated.

Body:
Try one of these.

($stringToDatetime1 = '5/29/2019 8:46:47 PM' | Get-Date)
Wednesday, May 29, 2019 8:46:47 PM

($stringToDatetime2 = [DateTime]::ParseExact('5/29/2019 8:46:47 PM','M/d/yyyy h:mm:ss tt',$null))
Wednesday, May 29, 2019 8:46:47 PM

($stringToDatetime3 = [Datetime]'5/29/2019 8:46:47 PM')
Wednesday, May 29, 2019 8:46:47 PM

BTW, this error is fully documented here:

PowerShell [DateTime] throws the error “String was not recognized as a valid DateTime.”


问:
RealmSwift crashes with error "Invalid property name" after update
I just updated a project to Swift 5.0 and updated Realm and RealmSwift from 2.8.3 to 3.14.2.

The project ran fine before, but now it is crashing on the following simple example:

Definition:

```<code>class Subscription : Object {

    dynamic var expiryDate = Date()
    dynamic var productId = Product.SubscriptionID
}
</code>```

Implementation:

```<code>let query = NSPredicate(format:"productId == %@", productId)
let subs = Array(realm.objects(Subscription.self).filter(query))
</code>```

with the error

```<code>Terminating app due to uncaught exception 'Invalid property name', reason: 'Property 'productId' not found in object of type 'Subscription''
</code>```

Has anything changed with RealmSwift that would cause these errors?

答:
If you follow all the examples in the Realm documentation you'll see that all fields are declared as both @objc and dynamic. If you therefore change your definitions as below the problem should resolve:-

```<code>class Subscription : Object {

  @objc dynamic var expiryDate = Date()
  @objc dynamic var productId = Product.SubscriptionID
}
</code>```

Body:
I just updated a project to Swift 5.0 and updated Realm and RealmSwift from 2.8.3 to 3.14.2.

The project ran fine before, but now it is crashing on the following simple example:

Definition:

class Subscription : Object {

    dynamic var expiryDate = Date()
    dynamic var productId = Product.SubscriptionID
}

Implementation:

let query = NSPredicate(format:"productId == %@", productId)
let subs = Array(realm.objects(Subscription.self).filter(query))

with the error

Terminating app due to uncaught exception 'Invalid property name', reason: 'Property 'productId' not found in object of type 'Subscription''

Has anything changed with RealmSwift that would cause these errors?

Body:
If you follow all the examples in the Realm documentation you'll see that all fields are declared as both @objc and dynamic. If you therefore change your definitions as below the problem should resolve:-

class Subscription : Object {

  @objc dynamic var expiryDate = Date()
  @objc dynamic var productId = Product.SubscriptionID
}


问:
chrome extension onInstalled event
I have a question about chrome extension install/update event. If I add the onInstalled event listener in a top level code in the background script, is there a time frame in which my event listener will catch that event?

I'm asking this, because my demos showed that if I have some logic that executes before I hook onInstalled listener, it looks like it will never be executed, like that event happens in the meantime.

Can someone explain to me with more details how this event works, in the context of other logic in the background script, or point me to some documentation, since I haven't been able to find anything useful.

Thanks!

Update @Noam Hacker : Due to a company policy I can't post any real code here, but I have some pseudo code that illustrates my problem :

```<code>/**
 * setup in which I miss onInstalled event
 */
function firstLogicThatRunsOnBackgroundLoad() {
    // perform some logic

    // perform some asynchronous operations via generators and promises
    // which can take a while

    chrome.runtime.onInstalled.addListener(function (details) {
            if (details.reason == "install") {
                // this logic never gets executed
            } else if(details.reason == "update") {
                // perform some logic
            }
        });
}

/**
 * setup in which I catch onInstalled event
 */
function firstLogicThatRunsOnBackgroundLoad() {
    chrome.runtime.onInstalled.addListener(function (details) {
            if (details.reason == "install") {
                // this logic executes
            } else if(details.reason == "update") {
                // perform some logic
            }
        });

    // perform some logic

    // perform some asynchronous operations via generators and promises
    // which can take a while
}
</code>```

答:
Given that the document says

“Listeners must be registered synchronously from the start of the page.”

and

“Do not register listeners asynchronously, as they will not be properly triggered.”

, it seems they guarantee every synchronously-attached listener not to miss any, no matter how long it takes to evaluate your code. And this would be done by Chrome firing events after evaluating your entire code.

My hypothesis is that onInstalled actually works like onInitialized. No test data, though.

Title: chrome extension onInstalled event

Body:
I have a question about chrome extension install/update event. If I add the onInstalled event listener in a top level code in the background script, is there a time frame in which my event listener will catch that event?

I'm asking this, because my demos showed that if I have some logic that executes before I hook onInstalled listener, it looks like it will never be executed, like that event happens in the meantime.

Can someone explain to me with more details how this event works, in the context of other logic in the background script, or point me to some documentation, since I haven't been able to find anything useful.

Thanks!

Update @Noam Hacker : Due to a company policy I can't post any real code here, but I have some pseudo code that illustrates my problem :

/**
 * setup in which I miss onInstalled event
 */
function firstLogicThatRunsOnBackgroundLoad() {
    // perform some logic

    // perform some asynchronous operations via generators and promises
    // which can take a while

    chrome.runtime.onInstalled.addListener(function (details) {
            if (details.reason == "install") {
                // this logic never gets executed
            } else if(details.reason == "update") {
                // perform some logic
            }
        });
}

/**
 * setup in which I catch onInstalled event
 */
function firstLogicThatRunsOnBackgroundLoad() {
    chrome.runtime.onInstalled.addListener(function (details) {
            if (details.reason == "install") {
                // this logic executes
            } else if(details.reason == "update") {
                // perform some logic
            }
        });

    // perform some logic

    // perform some asynchronous operations via generators and promises
    // which can take a while
}


问:
Add option for custom font size in iOS app
I am developing an app in this app there are many text files.
User clicks on a button and a files is loaded on new screen.

This file contains only text but few lines with font size 15 and other lines with font size 10. User can change font size from settings for that file.

What is right way to load the file so user increase or decrease font size?

I think attributed text is not right choice for this.

答:
In this use-case NSAttributedString is my best friend, and I would go with him.

Having said that, you do not have to keep large text in code files, keep the files

In app bundle, you can load file from App Bundle using

```<code>if let path = Bundle.main.path(forResource: "file1", ofType: "txt"), let text = try? String(contentsOfFile: path) {
    ...
}
</code>```

In a remote location, you can load String from remote URL using

```<code>if let url = URL(string: "https://www.example.org"), let text = try? String(contentsOf: url) {
    ...
}
</code>```

Add option for custom font size

You can add HTML tags in your text and use CSS styles, here is an example

```<code>let headerFont = UIFont(name: "ArialRoundedMTBold", size: 30)!
let headerStyle = ".heading{font-family:\(headerFont.fontName);font-size:\(Int(headerFont.pointSize));color:#000}"

let commonFont = UIFont(name: "ArialMT", size: 22)!
let commonStyle = "*{font-family:\(commonFont.fontName);font-size:\(Int(commonFont.pointSize));color:#666}"

let htmlData = Data("<style>\(commonStyle)\(headerStyle)</style>\(text)".utf8)
let attributedString = try? NSAttributedString(data: htmlData, options: [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)
</code>```

Body:
In this use-case NSAttributedString is my best friend, and I would go with him.

Having said that, you do not have to keep large text in code files, keep the files

In app bundle, you can load file from App Bundle using

if let path = Bundle.main.path(forResource: "file1", ofType: "txt"), let text = try? String(contentsOfFile: path) {
    ...
}

In a remote location, you can load String from remote URL using

if let url = URL(string: "https://www.example.org"), let text = try? String(contentsOf: url) {
    ...
}

Add option for custom font size

You can add HTML tags in your text and use CSS styles, here is an example

let headerFont = UIFont(name: "ArialRoundedMTBold", size: 30)!
let headerStyle = ".heading{font-family:\(headerFont.fontName);font-size:\(Int(headerFont.pointSize));color:#000}"

let commonFont = UIFont(name: "ArialMT", size: 22)!
let commonStyle = "*{font-family:\(commonFont.fontName);font-size:\(Int(commonFont.pointSize));color:#666}"

let htmlData = Data("<style>\(commonStyle)\(headerStyle)</style>\(text)".utf8)
let attributedString = try? NSAttributedString(data: htmlData, options: [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)


问:
Can't get Extra from specific activity
I have a very weird problem.
I know how to pass data from an intent to another using PutExtra/getExtras.
When i wanted to get the data passed between the two intents ,it gets NullPointerException.
I have tried to achieve that too by passing a bundle, the same problem happened.
So i tried to pass it to another activity , and it is passed!!
Why the first activity couldn't retrieve the data passed ?!</p>

答:
Suppose you have three activity A B C
In order to get intent from A to B use put Extra(content) and to get the same data from A to C use putExtras(get intent) in B and in C use getExtra(content). I was also having the same null point exception untill I searched and tried everything and got this solution</p>

Title: Can't get Extra from specific activity