问:
How to Change Navigation Bar Style in IOS Xamarin.Forms
I have referred the below link to hide the navigation bar back button title globally and its working fine, But when I add any text to toolbar, the toolbar text also hidden. Can anyone give suggestion to fix this issue.

How to Hide Navigation bar back button title globally in xamarin.ios

Here is my toolbar code:

```<code>ToolbarItem tbi = new ToolbarItem() { Text = "Text", Order = ToolbarItemOrder.Primary };
ToolbarItems.Add(tbi);
</code>```

答:
The easiest way to change or remove the back button text on Xamarin.Forms is with this code:

```<code>NavigationPage.SetBackButtonTitle(this, "");
</code>```

Note you need to do this in the page before the page the back button appears on i.e. the calling page.

I tried this and your toolbar code worked correctly.

EDIT

You can also create a base page containing the hide toolbar button code and inherit all pages from that.

Here is the base page:

```<code>public class BasePage : ContentPage
{
    public BasePage ()
    {
        NavigationPage.SetBackButtonTitle(this, "");
    }
}
</code>```

Then the inherited page looks like this

```<code>public partial class MainPage : BasePage
{
    public MainPage()
    {
        InitializeComponent();
    }
}
</code>```

and if it is a XAML page ensure you change the page type

```<code><pages:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:pages="clr-namespace:ScratchPad.Pages;assembly=ScratchPad"
             x:Class="ScratchPad.Pages.MainPage"
             Title="List Test">
    <StackLayout>
        <Button Text="Page Two" Command="{Binding PageTwoCommand}"/>
        <ListView ItemsSource="{Binding Items}"
                  SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
        </ListView>

    </StackLayout>

</pages:BasePage>
</code>```

Body:
I have referred the below link to hide the navigation bar back button title globally and its working fine, But when I add any text to toolbar, the toolbar text also hidden. Can anyone give suggestion to fix this issue.

How to Hide Navigation bar back button title globally in xamarin.ios

Here is my toolbar code:

ToolbarItem tbi = new ToolbarItem() { Text = "Text", Order = ToolbarItemOrder.Primary };
ToolbarItems.Add(tbi);

Body:
The easiest way to change or remove the back button text on Xamarin.Forms is with this code:

NavigationPage.SetBackButtonTitle(this, "");

Note you need to do this in the page before the page the back button appears on i.e. the calling page.

I tried this and your toolbar code worked correctly.

EDIT

You can also create a base page containing the hide toolbar button code and inherit all pages from that.

Here is the base page:

public class BasePage : ContentPage
{
    public BasePage ()
    {
        NavigationPage.SetBackButtonTitle(this, "");
    }
}

Then the inherited page looks like this

public partial class MainPage : BasePage
{
    public MainPage()
    {
        InitializeComponent();
    }
}

and if it is a XAML page ensure you change the page type

<pages:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:pages="clr-namespace:ScratchPad.Pages;assembly=ScratchPad"
             x:Class="ScratchPad.Pages.MainPage"
             Title="List Test">
    <StackLayout>
        <Button Text="Page Two" Command="{Binding PageTwoCommand}"/>
        <ListView ItemsSource="{Binding Items}"
                  SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
        </ListView>

    </StackLayout>

</pages:BasePage>


来源: stackexchange

问:
Flat File Photo Rating Script Questions
I have a very limited server environment. I can't even use JSON. I have created a page with about 25 photos on it. When you roll over the photo a 5 star rating div appears, you can click on the stars you think the photo should be rated at.

I have looked online at some tutorials and what not and got a JSON version going, then put it on the server and blah... nothing. No JSON. Should have checked that huH? Well, I know I can write to text files, so I am going that route.  I followed this tut: http://net.tutsplus.com/tutorials/html-css-techniques/building-a-5-star-rating-system-with-jquery-ajax-and-php/ to get it running on my images. Works just like it want it to... however, not on the server without JSON.

SO! What I want to know is, how can I make this write to a flat file? I can use the .POST{} jquery function and call a php script, but I am lost at how to post the data to the file.

Thanks for any thoughts, ideas, or the like. :)

答:
I've used json on PHP4 boxes. Simply use:

http://pear.php.net/package/Services_JSON/

Then, in your code do something along the lines of:

```<code>if (!function_exists('json_encode')) {
    require_once('services_json.php');
    $_JSON = new Services_JSON();

    function json_encode($value, $options = 0)
    {
        global $_JSON;
        return $_JSON->encode($value);
    }

    function json_decode($str, $assoc = false, $depth = 512)
    {
        global $_JSON;
        return $_JSON->decode($str);
    }
}
</code>```

This has allowed me to use json_encode/decode functions without worrying about PHP version.

ContentLicense: CC BY-SA 2.5

Title: Flat File Photo Rating Script Questions

Body:
I've used json on PHP4 boxes. Simply use:

http://pear.php.net/package/Services_JSON/

Then, in your code do something along the lines of:

if (!function_exists('json_encode')) {
    require_once('services_json.php');
    $_JSON = new Services_JSON();

    function json_encode($value, $options = 0)
    {
        global $_JSON;
        return $_JSON->encode($value);
    }

    function json_decode($str, $assoc = false, $depth = 512)
    {
        global $_JSON;
        return $_JSON->decode($str);
    }
}

This has allowed me to use json_encode/decode functions without worrying about PHP version.


问:
How to architecture a web-socket server with client subscription of specific responses in Phoenix?
I'm developing a web-socket server that I need to send real-time messages using Phoenix Framework to my clients.

The basic idea of my web-socket server is that a client can subscribe for some type of information and expect to receive only it, other clients would never receive it unless they subscribe to it too, the same information is broadcasted to every (and only) client subscribed to it in real-time.

Also, these information are separated in categories and sub categories, going down to 4 levels of categories.

So, for example, let's say I have 2 types of category information CatA, and CatB, each category can have sub categories, so CatA can have CatA.SubCatA and CatA.SubCatB sub categories, each sub categories can also have other subcategories and so on.

These information are generated by services, one for each root category (they handle all the information for the subcategories too), so we have CatAService and CatBService. These services needs to run as the server starts, always generating new information and broadcasting it to anyone that is subscribed to it.

Now, I have clients that will try to subscribe to these information, my solution for now is to have a channel for each information type available, so a client can join a channel to receive information of the channel's type.

For that I have something like that in the js code:

```<code>let channel = socket.channel("CatA:SubCatA:SubSubCatA", {})
channel.join()
channel.on("new_info", (payload) => { ... }
</code>```

In this case, I would have a channel that all clients interested in SubSubCatA from SubCatA from CatA can join and a service for CatA that would generate and broadcast the information for all it's sub categories and so on.

I'm not sure if I was able to explain exactly what I want, but if something is not clear, please tell me what so I can better explain it, also, I made this (very bad) image as an example of how all the communication would happen https://ibb.co/fANKPb .

Also, note that I could only have one channel for each category and broadcast all the subcategories information for everyone that joined that category channel, but I'm very concerned about performance and network bandwidth, So my objective is to only send the information to only the clients that requested it.

Doing some tests here, it seems that If the client joins the channel as shown in the js code above, I can do this:

```<code>MyServerWeb.Endpoint.broadcast "CatA:SubCatA:SubSubCatA", "new_info", message
</code>```

and that client (and all the other clients listening to that channel, but only then) will receive that message.

So, my question is divided in two parts, one is more generic and is what are the correct ways to achieve what I described above.

The second is if the solution I already came up is a good way to solve this since I'm not sure if the length of the string "CatA:SubCatA:SubSubCatA" creates an overhead when the server parses it or if there is some other limitation that I'm not aware.

Thanks!

答:
You have to make separate channels for each class of clients and depending upon the ids which you are getting, you can broadcast the messages after checking about the clients joining the channel

```<code> def join("groups:" <> group_slug, _params, socket) do
%{team_id: team_id, current_user: user} = socket.assigns

case Repo.get_by(Group, slug: group_slug, team_id: team_id) do
  nil ->
    {:error, %{message: "group not found"}}
  group ->
    case GroupAuthorization.can_view?(group.id, user.id) do
      true ->
        messages = MessageQueries.group_latest_messages(group.id, user)
        json = MessageView.render("index.json", %{messages: messages})
        send self(), :after_join
        {:ok, %{messages: json}, assign(socket, :group, group)}
      false ->
        {:error, %{message: "unauthorized"}}
    end
end
</code>```

end

This is an example of sending messages only to the users in groups which are subscribed and joined to the group. Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I'm developing a web-socket server that I need to send real-time messages using Phoenix Framework to my clients.

The basic idea of my web-socket server is that a client can subscribe for some type of information and expect to receive only it, other clients would never receive it unless they subscribe to it too, the same information is broadcasted to every (and only) client subscribed to it in real-time.

Also, these information are separated in categories and sub categories, going down to 4 levels of categories.

So, for example, let's say I have 2 types of category information CatA, and CatB, each category can have sub categories, so CatA can have CatA.SubCatA and CatA.SubCatB sub categories, each sub categories can also have other subcategories and so on.

These information are generated by services, one for each root category (they handle all the information for the subcategories too), so we have CatAService and CatBService. These services needs to run as the server starts, always generating new information and broadcasting it to anyone that is subscribed to it.

Now, I have clients that will try to subscribe to these information, my solution for now is to have a channel for each information type available, so a client can join a channel to receive information of the channel's type.

For that I have something like that in the js code:

let channel = socket.channel("CatA:SubCatA:SubSubCatA", {})
channel.join()
channel.on("new_info", (payload) => { ... }

In this case, I would have a channel that all clients interested in SubSubCatA from SubCatA from CatA can join and a service for CatA that would generate and broadcast the information for all it's sub categories and so on.

I'm not sure if I was able to explain exactly what I want, but if something is not clear, please tell me what so I can better explain it, also, I made this (very bad) image as an example of how all the communication would happen https://ibb.co/fANKPb .

Also, note that I could only have one channel for each category and broadcast all the subcategories information for everyone that joined that category channel, but I'm very concerned about performance and network bandwidth, So my objective is to only send the information to only the clients that requested it.

Doing some tests here, it seems that If the client joins the channel as shown in the js code above, I can do this:

MyServerWeb.Endpoint.broadcast "CatA:SubCatA:SubSubCatA", "new_info", message

and that client (and all the other clients listening to that channel, but only then) will receive that message.

So, my question is divided in two parts, one is more generic and is what are the correct ways to achieve what I described above.

The second is if the solution I already came up is a good way to solve this since I'm not sure if the length of the string "CatA:SubCatA:SubSubCatA" creates an overhead when the server parses it or if there is some other limitation that I'm not aware.

Thanks!

Body:
You have to make separate channels for each class of clients and depending upon the ids which you are getting, you can broadcast the messages after checking about the clients joining the channel

 def join("groups:" <> group_slug, _params, socket) do
%{team_id: team_id, current_user: user} = socket.assigns

case Repo.get_by(Group, slug: group_slug, team_id: team_id) do
  nil ->
    {:error, %{message: "group not found"}}
  group ->
    case GroupAuthorization.can_view?(group.id, user.id) do
      true ->
        messages = MessageQueries.group_latest_messages(group.id, user)
        json = MessageView.render("index.json", %{messages: messages})
        send self(), :after_join
        {:ok, %{messages: json}, assign(socket, :group, group)}
      false ->
        {:error, %{message: "unauthorized"}}
    end
end

end

This is an example of sending messages only to the users in groups which are subscribed and joined to the group. Hope this helps.


问:
Windows update apparently deleted Android SDK files from Visual Studio
I just restarted my Windows 10 machine to install some updates, and afterward I started getting this error in Visual Studio:

```<code>Error       Xamarin.Android for Visual Studio requires Android SDK.
Please install it or set Android SDK path on Tools->Options->Xamarin->Android Settings menu.            0
</code>```

Which I thought was weird, since I'd never run into any issues with my Android SDK before. So I went to Tools->Android to open the SDK manager, but all the options were grayed out and not selectable. Here's a screenshot:

So I did a little research, and this post told me to manually start my SDK manager with the .exe file. So I searched my files for the SDK manager, but when I clicked to open it, I got this error message:

```<code>The item that this shortcut refers to has been changed or moved.
Would you like to remove this shortcut?
</code>```

And I got the same error for the Uninstall Android SDK Tools and AVD Manager shortcuts. So it seems that all my Android SDK files were for some reason deleted during my Windows updates.

Then I noticed that under Visual Studio Tools->Options->Xamarin->Android, the "Android SDK Location" was empty. Screenshot:

So then I downloaded Android Studio from the official site, found the location to the .exe file, and then copy-and-pasted the path into the "Android SDK Location" field, and clicked "OK". But the field wasn't saved. No matter what I do, when I open Options, the "Android SDK Location" field is always empty.

I have no idea how to proceed. Anyone have any ideas?

UPDATE

I ran Visual Studio Installer, clicked Modify, and under "Individual Components", it tells me that I already have the latest Android SDK setup (API level 25) installed. Do I need to install something other than that? Screenshot:

答:
Better to Update Visual studio from Visual studio Installer

When you Load Visual Studio Installer, select repair option...

it will fix all issues...

Body:
I just restarted my Windows 10 machine to install some updates, and afterward I started getting this error in Visual Studio:

Error       Xamarin.Android for Visual Studio requires Android SDK.
Please install it or set Android SDK path on Tools->Options->Xamarin->Android Settings menu.            0

Which I thought was weird, since I'd never run into any issues with my Android SDK before. So I went to Tools->Android to open the SDK manager, but all the options were grayed out and not selectable. Here's a screenshot:

So I did a little research, and this post told me to manually start my SDK manager with the .exe file. So I searched my files for the SDK manager, but when I clicked to open it, I got this error message:

The item that this shortcut refers to has been changed or moved.
Would you like to remove this shortcut?

And I got the same error for the Uninstall Android SDK Tools and AVD Manager shortcuts. So it seems that all my Android SDK files were for some reason deleted during my Windows updates.

Then I noticed that under Visual Studio Tools->Options->Xamarin->Android, the "Android SDK Location" was empty. Screenshot:

So then I downloaded Android Studio from the official site, found the location to the .exe file, and then copy-and-pasted the path into the "Android SDK Location" field, and clicked "OK". But the field wasn't saved. No matter what I do, when I open Options, the "Android SDK Location" field is always empty.

I have no idea how to proceed. Anyone have any ideas?

UPDATE

I ran Visual Studio Installer, clicked Modify, and under "Individual Components", it tells me that I already have the latest Android SDK setup (API level 25) installed. Do I need to install something other than that? Screenshot:


问:
Showing only specific fields of javascript object in the array doesn't work
I'm trying to show specific series of specific fields and value inside of the object but it's not working.

```<code>var objArray = [
    {id:1, photo:true, bol: true }, {id:2, photo: true, bol:true}
];

result = objArray.map((item) => return {id: item.id, photo: item.photo
}) // this doesn't work.. why??
</code>```

Expectd Output

```<code>[
    {id:1, photo:true}, {id:2, photo: true}
]
</code>```

答:
You need to make two changes

Remove return statement - arrow functions will implicitly return the expression's evaluated result.

Wrap {} with () so that {} doesn't get treated as a code block, but as an expression.

i.e.

```<code>objArray.map((item) => ({id: item.id, photo: item.photo  }));
</code>```

Demo

var objArray = [{
  id: 1,
  photo: true,
  bol: true
}, {
  id: 2,
  photo: true,
  bol: true
}];

var result = objArray.map((item) => ({
  id: item.id,
  photo: item.photo
}));

console.log(result);```

Body:
I'm trying to show specific series of specific fields and value inside of the object but it's not working.

var objArray = [
    {id:1, photo:true, bol: true }, {id:2, photo: true, bol:true}
];

result = objArray.map((item) => return {id: item.id, photo: item.photo
}) // this doesn't work.. why??

Expectd Output

[
    {id:1, photo:true}, {id:2, photo: true}
]

Body:
You need to make two changes

Remove return statement - arrow functions will implicitly return the expression's evaluated result.

Wrap {} with () so that {} doesn't get treated as a code block, but as an expression.

i.e.

objArray.map((item) => ({id: item.id, photo: item.photo  }));

Demo

var objArray = [{
  id: 1,
  photo: true,
  bol: true
}, {
  id: 2,
  photo: true,
  bol: true
}];

var result = objArray.map((item) => ({
  id: item.id,
  photo: item.photo
}));

console.log(result);


问:
Find mode without built in functions or dictionaries
So I have a list of values, and I have an idea of how to get the mode. But I'm unsure of how exactly to execute it. I know I will need the max value of the list using max() and also for x in list,and perhaps creating two lists, one for unique values and the other for how many times they appear, but besides that. I'm completely lost.
My list is:

```<code> [0,68, 92, 68, 49, 43, 68]
</code>```

Expected output:

```<code>68
</code>```

Sorry if this is vague! This is not a duplicate. I don't want to use a counter function or dictionary. Only lists/ loops.

答:
The mode of a set of data values is the value that appears most often. You can easily get this using python's Counter module's most_common method. It takes n that defines how many results you want, 1 is the most common 2 would be the two most common.

```<code>from collections import Counter
data = Counter( [0,68, 92, 68, 49, 43, 68])
print data.most_common(1)
> [(68, 3)]
</code>```

most_common: Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:

Body:
So I have a list of values, and I have an idea of how to get the mode. But I'm unsure of how exactly to execute it. I know I will need the max value of the list using max() and also for x in list,and perhaps creating two lists, one for unique values and the other for how many times they appear, but besides that. I'm completely lost.
My list is:

 [0,68, 92, 68, 49, 43, 68]

Expected output:

68

Sorry if this is vague! This is not a duplicate. I don't want to use a counter function or dictionary. Only lists/ loops.

Body:
The mode of a set of data values is the value that appears most often. You can easily get this using python's Counter module's most_common method. It takes n that defines how many results you want, 1 is the most common 2 would be the two most common.

from collections import Counter
data = Counter( [0,68, 92, 68, 49, 43, 68])
print data.most_common(1)
> [(68, 3)]

most_common: Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:


问:
int.Parse is not working with string value (System.FormatException: Input string was not in a correct format )
If a user inputs anything but a number I get Unhandled Exception:

System.FormatException: Input string was not in a correct format.

Can someone explain what I am doing wrong?

Here's my code C# .NET:

```<code>private static int WeightIFeMale()
{
    Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
    int femaleWeight = int.Parse(Console.ReadLine());

    if
        (0 >= femaleWeight && 80 <= femaleWeight)
    {
        Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
    }
    else if
        (81 >= femaleWeight && 110 <= femaleWeight)
    {
        Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

    }
    else if
        (111 >= femaleWeight && 140 <= femaleWeight)
    {
        Console.WriteLine("Holy shit, I have some protein bar coupons you can have!", Environment.NewLine);

    }
    else if
        (141 >= femaleWeight && 160 <= femaleWeight)
    {
        Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

    }
    else if
        (161 >= femaleWeight && 200 <= femaleWeight)
    {
        Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

    }
    else if
        (201 >= femaleWeight && 240 <= femaleWeight)
    {
        Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

    }
    else if
        (241 >= femaleWeight && 999 <= femaleWeight)
    {
        Console.WriteLine("My condolences!", Environment.NewLine);
    }
    else if
        (femaleWeight >= 1000)
    {
        Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
    }
    else
    {
        Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
        WeightIFeMale();
    }

    return femaleWeight;
}
</code>```

答:
```<code>This is how it worked for me:

private static int WeightIFeMale()
    {
            Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
    }
 int femaleWeight;

            if (!int.TryParse(Console.ReadLine(), out femaleWeight)) //I deleted the else statement.
    {
    Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
        Console.Write(Environment.NewLine);
        WeightIFeMale();
    }
    else if
        (femaleWeight >= 0   && femaleWeight <= 80)
    {
        Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
    }
    else if
        (femaleWeight >= 81 && femaleWeight <= 110)
    {
        Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

    }
    else if
        (femaleWeight >= 111 && femaleWeight <= 140)
    {
        Console.WriteLine("Holy ***, I have some protein bar coupons you can have!", Environment.NewLine);

    }
    else if
        (femaleWeight >= 141 && femaleWeight <= 160)
    {
        Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

    }
    else if
        (femaleWeight >= 161 && femaleWeight <= 200)
    {
        Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

    }
    else if
        (femaleWeight >= 201 && femaleWeight <= 240)
    {
        Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

    }
    else if
        (femaleWeight >= 241 && femaleWeight <= 999)
    {
        Console.WriteLine("My condolences!", Environment.NewLine);
    }
    else if
        (femaleWeight >= 1000)
    {
        Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
    }
</code>```

Body:
If a user inputs anything but a number I get Unhandled Exception:

System.FormatException: Input string was not in a correct format.

Can someone explain what I am doing wrong?

Here's my code C# .NET:

private static int WeightIFeMale()
{
    Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
    int femaleWeight = int.Parse(Console.ReadLine());

    if
        (0 >= femaleWeight && 80 <= femaleWeight)
    {
        Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
    }
    else if
        (81 >= femaleWeight && 110 <= femaleWeight)
    {
        Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

    }
    else if
        (111 >= femaleWeight && 140 <= femaleWeight)
    {
        Console.WriteLine("Holy shit, I have some protein bar coupons you can have!", Environment.NewLine);

    }
    else if
        (141 >= femaleWeight && 160 <= femaleWeight)
    {
        Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

    }
    else if
        (161 >= femaleWeight && 200 <= femaleWeight)
    {
        Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

    }
    else if
        (201 >= femaleWeight && 240 <= femaleWeight)
    {
        Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

    }
    else if
        (241 >= femaleWeight && 999 <= femaleWeight)
    {
        Console.WriteLine("My condolences!", Environment.NewLine);
    }
    else if
        (femaleWeight >= 1000)
    {
        Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
    }
    else
    {
        Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
        WeightIFeMale();
    }

    return femaleWeight;
}


问:
Generate all strings under length N in C
I tried coding this myself and horribly failed. This is basically what I want:

```<code>a
b
...
z
aa
ba
...
za
ab
bb
...
zz
aaa
baa
...
zzz
</code>```

In the end it should have generated every string that is shorter then N characters with charset a-z. So I'm not looking for permutations (of which 1001 implementations can be found on the internet), but for combinations with replacement (at least that's how it's called in Python). Order is not important, speed is.

答:
Something like this (pseudocode):</p>

```<code>void CompWithRep(string line,int N) {
  char c;
  if (N==0) return;
  for (c = 'a' ; c <= 'z' ; c++ )
  {
    printf(line + c);
    CompWithRep(line + c,N-1);
  }
}
</code>```

Body:
I tried coding this myself and horribly failed. This is basically what I want:

a
b
...
z
aa
ba
...
za
ab
bb
...
zz
aaa
baa
...
zzz

In the end it should have generated every string that is shorter then N characters with charset a-z. So I'm not looking for permutations (of which 1001 implementations can be found on the internet), but for combinations with replacement (at least that's how it's called in Python). Order is not important, speed is.

Body:
Something like this (pseudocode):

void CompWithRep(string line,int N) {
  char c;
  if (N==0) return;
  for (c = 'a' ; c <= 'z' ; c++ )
  {
    printf(line + c);
    CompWithRep(line + c,N-1);
  }
}


问:
How to remove some character from string using PHP
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

```<code>$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);
</code>```

Expected Output

```<code>$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);
</code>```

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

答:
You can use a regular expression to remove unwanted words by looping through it.

```<code>foreach($datArr as &$i)
{
     $i['date']=preg_replace('[AM|PM]',"",$i['date']);
}
print_r ($datArr);
</code>```

 Output

```<code>Array
(
[0] => Array
    (
        [name] => Ram
        [id] => 1
        [date] => 12/04/2017 05:31:57
    )

[1] => Array
    (
        [name] => Rahim
        [id] => 5
        [date] => 12/03/2017 12:31:57
    )

[2] => Array
    (
        [name] => Raj
        [id] => 4
        [date] => 12/04/2017 05:31:57
    )

)
</code>```

Body:
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);

Expected Output

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

Body:
You can use a regular expression to remove unwanted words by looping through it.

foreach($datArr as &$i)
{
     $i['date']=preg_replace('[AM|PM]',"",$i['date']);
}
print_r ($datArr);

 Output

Array
(
[0] => Array
    (
        [name] => Ram
        [id] => 1
        [date] => 12/04/2017 05:31:57
    )

[1] => Array
    (
        [name] => Rahim
        [id] => 5
        [date] => 12/03/2017 12:31:57
    )

[2] => Array
    (
        [name] => Raj
        [id] => 4
        [date] => 12/04/2017 05:31:57
    )

)


问:
LinkedIn 'Jobs You May Be Interested In' Plugin adjust width and hight
I am trying to add width on this this LinkedIn Plugin https://developer.linkedin.com/plugins/jymbii because the plugin is too small, I tried adding data-width=600 on the code but it is not working. Is there any way we can add width on this?

答:
You may just have forgotten the "" around 600

so the full thing would be:

```<code><script src="//platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/JYMBII" data-format="inline" data-width="600"></script>
</code>```

Body:
You may just have forgotten the "" around 600

so the full thing would be:

<script src="//platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/JYMBII" data-format="inline" data-width="600"></script>


问:
What is the best way to conditionally apply a class?
Lets say you have an array that is rendered in a ul with an li for each element and a property on the controller called selectedIndex. What would be the best way to add a class to the li with the index selectedIndex in AngularJS?

I am currently duplicating (by hand) the li code and adding the class to one of the li tags and using ng-show and ng-hide to show only one li per index.

答:
You can use this npm package. It handles everything and has options for static and conditional classes based on a variable or a function.</p>

```<code>// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />
</code>```

Body:
You can use this npm package. It handles everything and has options for static and conditional classes based on a variable or a function.

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />


问:
Callback Method if user declines Push Notification Prompt?
My problem is I want to show a loading screen for the initial Push Notification Prompt "The app wants to send you push notifications."

So if the user hits yes I can proceed and start the app in the then invoked delegate methods:

```<code>- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
  [self hideLoadingScreen];
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
  [self hideLoadingScreen];
}
</code>```

However if the user hits no, none of these methods get called, which makes sense. My question is, is there a different delegate method that gets fired if he declines?

My problem is if no is selected, the loading screens never disappear. So I somehow need to know when the user is done with the selection.

答:
You can detect if user has cancelled the notification prompt in didRegisterUserNotificationSettings method that fires after calling registerForRemoteNotificationTypes by checking the notificationSettings.types.

If you have requested a number of settings but notificationSettings.types == UIUserNotificationTypeNone means, that user has cancelled the prompt.

But don't forget that registerForRemoteNotificationTypes method is now deprecated!

Body:
My problem is I want to show a loading screen for the initial Push Notification Prompt "The app wants to send you push notifications."

So if the user hits yes I can proceed and start the app in the then invoked delegate methods:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
  [self hideLoadingScreen];
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
  [self hideLoadingScreen];
}

However if the user hits no, none of these methods get called, which makes sense. My question is, is there a different delegate method that gets fired if he declines?

My problem is if no is selected, the loading screens never disappear. So I somehow need to know when the user is done with the selection.


问:
Java Riak Connection Problems
trying to connect my Java Eclipse to a Riak server on Linux Ubuntu.
Followed up some guides but still don't working.
Using:
- Riak-Client-2.0.2
- Eclipse Oxygen.1a Release (4.7.1a)
- Ubuntu 16.04.3
- openjdk version "1.8.0_151"

Have had some problems before with slf4j so i added a external jar:
slf4j-jdk14-1.7.25-sources to solve it.

My code:

```<code>import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.api.commands.kv.FetchValue;
import com.basho.riak.client.api.commands.kv.StoreValue;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;

import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;

public class ProdukteEinlesen {
    public static void main(String [] args) throws UnknownHostException, ExecutionException, InterruptedException {

        RiakClient client = RiakClient.newClient(8098, "127.0.0.1");
        Location location = new Location(new Namespace("TestBucket"),"TestKey");

        FetchValue fv = new FetchValue.Builder(location).build();
        FetchValue.Response response = client.execute(fv);

        // Fetch object as String
        String value = response.getValue(String.class);
        System.out.println(value);

        client.shutdown();
    }
}
</code>```

Now i am getting this:

```<code> Dez 04, 2017 5:58:23 PM com.basho.riak.client.core.RiakNode start
INFORMATION: RiakNode started; 127.0.0.1:8098
Dez 04, 2017 5:58:23 PM com.basho.riak.client.core.RiakCluster start
INFORMATION: RiakCluster is starting.
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-2083854054 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:674162571 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:1161062152 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-1411904647 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-1369356068 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:957736106 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-1598195494 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-1723639977 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-1232050671 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$3 operationComplete
SCHWERWIEGEND: Channel closed while operation in progress; id:-459317961 127.0.0.1:8098
Dez 04, 2017 6:08:17 PM com.basho.riak.client.core.RiakNode healthCheckFailed
SCHWERWIEGEND: RiakNode failed healthcheck operation; health checking; 127.0.0.1:8098 java.io.IOException: Channel closed while performing health check op.
Dez 04, 2017 6:08:17 PM com.basho.riak.client.core.DefaultNodeManager nodeStateChanged
INFORMATION: NodeManager moved node to unhealthy list; 127.0.0.1:8098
Dez 04, 2017 6:08:17 PM com.basho.riak.client.core.RiakNode$3 operationComplete
SCHWERWIEGEND: Channel closed while operation in progress; id:-1254319488 127.0.0.1:8098
Exception in thread "main" java.util.concurrent.ExecutionException: com.basho.riak.client.core.NoNodesAvailableException
    at com.basho.riak.client.core.FutureOperation.get(FutureOperation.java:260)
    at com.basho.riak.client.api.commands.CoreFutureAdapter.get(CoreFutureAdapter.java:52)
    at com.basho.riak.client.api.RiakCommand.execute(RiakCommand.java:89)
    at com.basho.riak.client.api.RiakClient.execute(RiakClient.java:293)
    at ProdukteEinlesen.main(ProdukteEinlesen.java:18)
Caused by: com.basho.riak.client.core.NoNodesAvailableException
    at com.basho.riak.client.core.RiakCluster.retryOperation(RiakCluster.java:468)
    at com.basho.riak.client.core.RiakCluster.access$1000(RiakCluster.java:47)
    at com.basho.riak.client.core.RiakCluster$RetryTask.run(RiakCluster.java:553)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

My Riak DB is working fine tasted it already via command.

答:
You seem to be using an incorrect port number for Riak connections. The correct port for the Protocol Buffers API is 8087 (assuming you haven't changed the defaults). Port 8098 is for HTTP, you must have tested the server with cURL or another HTTP client. The Java code should be as follows:

```<code>RiakClient client = RiakClient.newClient(8087, "127.0.0.1");
</code>```

Riak Protocol Buffers API

RiakClient Javadoc

Title: Java Riak Connection Problems

Body:
trying to connect my Java Eclipse to a Riak server on Linux Ubuntu.
Followed up some guides but still don't working.
Using:
- Riak-Client-2.0.2
- Eclipse Oxygen.1a Release (4.7.1a)
- Ubuntu 16.04.3
- openjdk version "1.8.0_151"

Have had some problems before with slf4j so i added a external jar:
slf4j-jdk14-1.7.25-sources to solve it.

My code:

import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.api.commands.kv.FetchValue;
import com.basho.riak.client.api.commands.kv.StoreValue;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;

import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;

public class ProdukteEinlesen {
    public static void main(String [] args) throws UnknownHostException, ExecutionException, InterruptedException {

        RiakClient client = RiakClient.newClient(8098, "127.0.0.1");
        Location location = new Location(new Namespace("TestBucket"),"TestKey");

        FetchValue fv = new FetchValue.Builder(location).build();
        FetchValue.Response response = client.execute(fv);

        // Fetch object as String
        String value = response.getValue(String.class);
        System.out.println(value);

        client.shutdown();
    }
}

Now i am getting this:

 Dez 04, 2017 5:58:23 PM com.basho.riak.client.core.RiakNode start
INFORMATION: RiakNode started; 127.0.0.1:8098
Dez 04, 2017 5:58:23 PM com.basho.riak.client.core.RiakCluster start
INFORMATION: RiakCluster is starting.
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-2083854054 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:674162571 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:1161062152 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-1411904647 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-1369356068 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:957736106 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-1598195494 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-1723639977 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$2 operationComplete
SCHWERWIEGEND: inAvailable channel closed; id:-1232050671 127.0.0.1:8098
Dez 04, 2017 6:03:20 PM com.basho.riak.client.core.RiakNode$3 operationComplete
SCHWERWIEGEND: Channel closed while operation in progress; id:-459317961 127.0.0.1:8098
Dez 04, 2017 6:08:17 PM com.basho.riak.client.core.RiakNode healthCheckFailed
SCHWERWIEGEND: RiakNode failed healthcheck operation; health checking; 127.0.0.1:8098 java.io.IOException: Channel closed while performing health check op.
Dez 04, 2017 6:08:17 PM com.basho.riak.client.core.DefaultNodeManager nodeStateChanged
INFORMATION: NodeManager moved node to unhealthy list; 127.0.0.1:8098
Dez 04, 2017 6:08:17 PM com.basho.riak.client.core.RiakNode$3 operationComplete
SCHWERWIEGEND: Channel closed while operation in progress; id:-1254319488 127.0.0.1:8098
Exception in thread "main" java.util.concurrent.ExecutionException: com.basho.riak.client.core.NoNodesAvailableException
    at com.basho.riak.client.core.FutureOperation.get(FutureOperation.java:260)
    at com.basho.riak.client.api.commands.CoreFutureAdapter.get(CoreFutureAdapter.java:52)
    at com.basho.riak.client.api.RiakCommand.execute(RiakCommand.java:89)
    at com.basho.riak.client.api.RiakClient.execute(RiakClient.java:293)
    at ProdukteEinlesen.main(ProdukteEinlesen.java:18)
Caused by: com.basho.riak.client.core.NoNodesAvailableException
    at com.basho.riak.client.core.RiakCluster.retryOperation(RiakCluster.java:468)
    at com.basho.riak.client.core.RiakCluster.access$1000(RiakCluster.java:47)
    at com.basho.riak.client.core.RiakCluster$RetryTask.run(RiakCluster.java:553)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

My Riak DB is working fine tasted it already via command.

Body:
You seem to be using an incorrect port number for Riak connections. The correct port for the Protocol Buffers API is 8087 (assuming you haven't changed the defaults). Port 8098 is for HTTP, you must have tested the server with cURL or another HTTP client. The Java code should be as follows:

RiakClient client = RiakClient.newClient(8087, "127.0.0.1");

Riak Protocol Buffers API

RiakClient Javadoc


问:
Loop synchronization deadlock
I've got the following classes in Java

```<code>public class Counter {
    private int value;

    public Counter(int value) {
        this.value = value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public void decrement() {
        this.value--;
    }
    public int getValue() {
        return this.value;
    }
}

public class Cell extends Thread {

    private Object sync;
    private Counter counter;

    public Cell(Object sync, Counter counter) {
        this.sync = sync;
        this.counter = counter;
    }

    public void run() {
        for (int r=0; r<Simulation.ROUND_NUM; r++) {

            // do something

            synchronized(counter) {
                counter.decrement();
                counter.notifyAll();
            }
            synchronized(sync) {
                try {
                    sync.wait();
                }
                catch (Exception ex) {}
            }

        }
    }
}

public class Simulation extends Thread {

    public static final int THREAD_NUM = 5;
    public static final int ROUND_NUM = 5;

    public Object sync = new Object();
    private Counter counter = new Counter(THREAD_NUM);

    public void run() {

        for (int i=0; i<THREAD_NUM; i++) {
            Cell c = new Cell(sync,counter);
            c.start();
        }

        for (int i=0; i<ROUND_NUM; i++) {
            synchronized(counter) {
                while(counter.getValue() != 0) {
                    try {
                        counter.wait();
                    }
                    catch (Exception ex) {}
                }
                counter.setValue(THREAD_NUM);
            }

            synchronized(sync) {
                sync.notifyAll();
            }
        }
    }
}
</code>```

The aim is to prevent from executing the next iteration of loop in each Cell Thread, until every Cell Thread will be done on each iteration. My solution sometimes leads to deadlock. I can't understand why. Please help

答:
In your code, there seems to be no guarantee that when sync.notifyAll() gets executed, all the Cell threads got to sync.wait(). This refers to the last Cell thread (the fifth in your example) that needs to grab the lock for sync in order to wait on it. But the Simulation thread is also trying the same thing without making sure that everyone is waiting. That race condition makes Simulation sometimes grab the lock before the last Cell is able to do the same and wait.

Since that last Cell is not waiting, it doesn't get notified so the whole thing gets stuck.
You can test this by adding a System.out.println() as the first line in each synchronized (sync) block and writing "waiting for sync" and "notifying sync" accordingly. You'll see that only 4 threads are waiting for sync when you notify it.

To make sure everyone is waiting when the Simulator notifies, have the two synchronized blocks in Cell#run() nested:

```<code>public class Counter {
    private int value;

    public Counter(int value) {
        this.value = value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public void decrement() {
        this.value--;
    }

    public int getValue() {
        return this.value;
    }

    public static void main(String[] args) {
        new Simulation().start();
    }
}

class Cell extends Thread {

    private Object sync;
    private Counter counter;

    public Cell(Object sync, Counter counter) {
        this.sync = sync;
        this.counter = counter;
    }

    public void run() {
        for (int r = 0; r < Simulation.ROUND_NUM; r++) {

            // do something

            synchronized (sync) {
                synchronized (counter) {
                    counter.decrement();
                    counter.notifyAll();
                }
                try {
                    sync.wait();
                } catch (Exception ignored) {}
            }

        }
    }
}

class Simulation extends Thread {

    public static final int THREAD_NUM = 900;
    public static final int ROUND_NUM = 30;

    public Object sync = new Object();
    private Counter counter = new Counter(THREAD_NUM);

    public void run() {

        for (int i = 0; i < THREAD_NUM; i++) {
            Cell c = new Cell(sync, counter);
            c.start();
        }

        for (int i = 0; i < ROUND_NUM; i++) {
            synchronized (counter) {
                while (counter.getValue() != 0) {
                    try {
                        counter.wait();
                    } catch (Exception ex) {
                    }
                }
                counter.setValue(THREAD_NUM);
            }

            synchronized (sync) {
                sync.notifyAll();
            }
        }
    }
}
</code>```

Title: Loop synchronization deadlock

Body:
I've got the following classes in Java

public class Counter {
    private int value;

    public Counter(int value) {
        this.value = value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public void decrement() {
        this.value--;
    }
    public int getValue() {
        return this.value;
    }
}

public class Cell extends Thread {

    private Object sync;
    private Counter counter;

    public Cell(Object sync, Counter counter) {
        this.sync = sync;
        this.counter = counter;
    }

    public void run() {
        for (int r=0; r<Simulation.ROUND_NUM; r++) {

            // do something

            synchronized(counter) {
                counter.decrement();
                counter.notifyAll();
            }
            synchronized(sync) {
                try {
                    sync.wait();
                }
                catch (Exception ex) {}
            }

        }
    }
}

public class Simulation extends Thread {

    public static final int THREAD_NUM = 5;
    public static final int ROUND_NUM = 5;

    public Object sync = new Object();
    private Counter counter = new Counter(THREAD_NUM);

    public void run() {

        for (int i=0; i<THREAD_NUM; i++) {
            Cell c = new Cell(sync,counter);
            c.start();
        }

        for (int i=0; i<ROUND_NUM; i++) {
            synchronized(counter) {
                while(counter.getValue() != 0) {
                    try {
                        counter.wait();
                    }
                    catch (Exception ex) {}
                }
                counter.setValue(THREAD_NUM);
            }

            synchronized(sync) {
                sync.notifyAll();
            }
        }
    }
}

The aim is to prevent from executing the next iteration of loop in each Cell Thread, until every Cell Thread will be done on each iteration. My solution sometimes leads to deadlock. I can't understand why. Please help

Body:
In your code, there seems to be no guarantee that when sync.notifyAll() gets executed, all the Cell threads got to sync.wait(). This refers to the last Cell thread (the fifth in your example) that needs to grab the lock for sync in order to wait on it. But the Simulation thread is also trying the same thing without making sure that everyone is waiting. That race condition makes Simulation sometimes grab the lock before the last Cell is able to do the same and wait.

Since that last Cell is not waiting, it doesn't get notified so the whole thing gets stuck.
You can test this by adding a System.out.println() as the first line in each synchronized (sync) block and writing "waiting for sync" and "notifying sync" accordingly. You'll see that only 4 threads are waiting for sync when you notify it.

To make sure everyone is waiting when the Simulator notifies, have the two synchronized blocks in Cell#run() nested:

public class Counter {
    private int value;

    public Counter(int value) {
        this.value = value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public void decrement() {
        this.value--;
    }

    public int getValue() {
        return this.value;
    }

    public static void main(String[] args) {
        new Simulation().start();
    }
}

class Cell extends Thread {

    private Object sync;
    private Counter counter;

    public Cell(Object sync, Counter counter) {
        this.sync = sync;
        this.counter = counter;
    }

    public void run() {
        for (int r = 0; r < Simulation.ROUND_NUM; r++) {

            // do something

            synchronized (sync) {
                synchronized (counter) {
                    counter.decrement();
                    counter.notifyAll();
                }
                try {
                    sync.wait();
                } catch (Exception ignored) {}
            }

        }
    }
}

class Simulation extends Thread {

    public static final int THREAD_NUM = 900;
    public static final int ROUND_NUM = 30;

    public Object sync = new Object();
    private Counter counter = new Counter(THREAD_NUM);

    public void run() {

        for (int i = 0; i < THREAD_NUM; i++) {
            Cell c = new Cell(sync, counter);
            c.start();
        }

        for (int i = 0; i < ROUND_NUM; i++) {
            synchronized (counter) {
                while (counter.getValue() != 0) {
                    try {
                        counter.wait();
                    } catch (Exception ex) {
                    }
                }
                counter.setValue(THREAD_NUM);
            }

            synchronized (sync) {
                sync.notifyAll();
            }
        }
    }
}


问:
How to use the Abp.ZeroCore.EntityFramework with a ASP.NET Core solution

I am trying to use the package Abp.ZeroCore.EntityFramework in a vanilla ASP.NET Boilerplate template project, targeting ASP.NET Core 2 with full .NET Framework.
The template includes Entity Framework Core, but I want to use Entity Framework 6 because it's much more reliable and has features Entity Framework Core is missing.

In order to get it to build, I created a classic .NET class library with the Abp.ZeroCore.EntityFramework package, replicating the original .EntityFrameworkCore project included in the project template, but with code specific to EntityFramework 6, and configured all other projects to use this new module instead of the EF Core project.

Project builds successfully without any warnings, but when I try to create a migration I get a model validation error detailed below:

```<code>PM> Add-Migration InitialMigration
System.InvalidOperationException: The index with name 'IX_UserId_State_CreationTime' on table 'dbo.AbpUserNotifications' has the same column order of '1' specified for columns 'TenantId' and 'UserId'. Make sure a different order value is used for the IndexAttribute on each column of a multi-column index.
   at System.Data.Entity.Infrastructure.ConsolidatedIndex.Add(String columnName, IndexAttribute index)
   at System.Data.Entity.Infrastructure.ConsolidatedIndex.BuildIndexes(String tableName, IEnumerable`1 columns)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<FindTargetIndexes>b__278(EntitySet es)
   at System.Linq.Enumerable.<SelectManyIterator>d__22`3.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.Design.MigrationScaffolder.Scaffold(String migrationName, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Scaffold(MigrationScaffolder scaffolder)
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.RunCore()
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
The index with name 'IX_UserId_State_CreationTime' on table 'dbo.AbpUserNotifications' has the same column order of '1' specified for columns 'TenantId' and 'UserId'. Make sure a different order value is used for the IndexAttribute on each column of a multi-column index.
</code>```

So it looks like that some of the included models in Abp.ZeroCore package are not compatible with the Abp.ZeroCore.EntityFramework package.

Is this a know issue or there is a workaround for this error?
Including a vanilla ASP.NET Boilerplate template using ASP.NET Core and Entity Framework 6 would be really useful.

答:
I found the bug caused by faulty/duplicate CreateIndex entries:

modelBuilder.Entity<UserNotificationInfo>()
    .Property(e => e.UserId)
    .CreateIndex("IX_UserId_State_CreationTime", 1);
```

<pre class="lang-cs prettyprint-override"><code>modelBuilder.Entity<UserNotificationInfo>()
    .Property(e => e.TenantId)
    .CreateIndex("IX_UserId_State_CreationTime", 1);
</code>```

The fix will be included in the next minor version. You can upgrade to ABP v3.3 when it is released.

Body:
I am trying to use the package Abp.ZeroCore.EntityFramework in a vanilla ASP.NET Boilerplate template project, targeting ASP.NET Core 2 with full .NET Framework.
The template includes Entity Framework Core, but I want to use Entity Framework 6 because it's much more reliable and has features Entity Framework Core is missing.

In order to get it to build, I created a classic .NET class library with the Abp.ZeroCore.EntityFramework package, replicating the original .EntityFrameworkCore project included in the project template, but with code specific to EntityFramework 6, and configured all other projects to use this new module instead of the EF Core project.

Project builds successfully without any warnings, but when I try to create a migration I get a model validation error detailed below:

PM> Add-Migration InitialMigration
System.InvalidOperationException: The index with name 'IX_UserId_State_CreationTime' on table 'dbo.AbpUserNotifications' has the same column order of '1' specified for columns 'TenantId' and 'UserId'. Make sure a different order value is used for the IndexAttribute on each column of a multi-column index.
   at System.Data.Entity.Infrastructure.ConsolidatedIndex.Add(String columnName, IndexAttribute index)
   at System.Data.Entity.Infrastructure.ConsolidatedIndex.BuildIndexes(String tableName, IEnumerable`1 columns)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<FindTargetIndexes>b__278(EntitySet es)
   at System.Linq.Enumerable.<SelectManyIterator>d__22`3.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.Design.MigrationScaffolder.Scaffold(String migrationName, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Scaffold(MigrationScaffolder scaffolder)
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.RunCore()
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
The index with name 'IX_UserId_State_CreationTime' on table 'dbo.AbpUserNotifications' has the same column order of '1' specified for columns 'TenantId' and 'UserId'. Make sure a different order value is used for the IndexAttribute on each column of a multi-column index.

So it looks like that some of the included models in Abp.ZeroCore package are not compatible with the Abp.ZeroCore.EntityFramework package.

Is this a know issue or there is a workaround for this error?
Including a vanilla ASP.NET Boilerplate template using ASP.NET Core and Entity Framework 6 would be really useful.

Body:
I found the bug caused by faulty/duplicate CreateIndex entries:

modelBuilder.Entity<UserNotificationInfo>()
    .Property(e => e.UserId)
    .CreateIndex("IX_UserId_State_CreationTime", 1);

modelBuilder.Entity<UserNotificationInfo>()
    .Property(e => e.TenantId)
    .CreateIndex("IX_UserId_State_CreationTime", 1);

The fix will be included in the next minor version. You can upgrade to ABP v3.3 when it is released.


问:
Excel Macro Autofilter and Delete Rows
I am trying to get the coding below working but getting errors.

Coding selects another worksheet, then autofilter a column and delete row.

Line having trouble is .AutoFilter 1, "NoNo"

Run-time error '1004': AutoFilter method of Range clas failed.

Can I please get some assistance.

```<code>Private Sub Project()
Worksheets("YesYes").Select
With ActiveSheet
.AutoFilterMode = False
 With Range("y1", Range("y" & Rows.Count).End(xlUp))
    .AutoFilter 1, "*NoNo*"
    On Error Resume Next
    .Offset(1).SpecialCells(12).EntireRow.Delete
End With
.AutoFilterMode = False
End With
End Sub
</code>```

答:
99% of the times using Select or Activate is not necessary.

Instead use fully qualified objects, in your case use:

```<code>With Worksheets("YesYes")
</code>```

And nested below use:

```<code>With .Range("y1", .Range("y" & .Rows.Count).End(xlUp))
</code>```

And then add the rest of your code.

Title: Excel Macro Autofilter and Delete Rows

Body:
I am trying to get the coding below working but getting errors.

Coding selects another worksheet, then autofilter a column and delete row.

Line having trouble is .AutoFilter 1, "NoNo"

Run-time error '1004': AutoFilter method of Range clas failed.

Can I please get some assistance.

Private Sub Project()
Worksheets("YesYes").Select
With ActiveSheet
.AutoFilterMode = False
 With Range("y1", Range("y" & Rows.Count).End(xlUp))
    .AutoFilter 1, "*NoNo*"
    On Error Resume Next
    .Offset(1).SpecialCells(12).EntireRow.Delete
End With
.AutoFilterMode = False
End With
End Sub

Body:
99% of the times using Select or Activate is not necessary.

Instead use fully qualified objects, in your case use:

With Worksheets("YesYes")

And nested below use:

With .Range("y1", .Range("y" & .Rows.Count).End(xlUp))

And then add the rest of your code.


问:
Unable to get upload project from bitbucket
I am new in bitbucket.I want to upload project from Linux to bitbucket.successfully I have created a bitbucket account and did the following

1)create a repository name 'testadmin'
2)Using command line cd /var/www/myname/myprojectname

```<code>git init
git remote add origin https://username@bitbucket.org/user/testadmin.git
git pull origin master
</code>```

then I get

```<code>Password for 'https://user@bitbucket.org':
From https://bitbucket.org/user/testadmin
 * branch            master     -> FETCH_HEAD
Merge made by the 'recursive' strategy.
 README.md | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
</code>```

But I didn't get my project from bitbucket.Please help me

答:
ok, then
I would advice you to keep your project folder in www directly. Like if your project folder name is project_1 then it should be at var/www/html/project_1

then open terminal and reach to the folder project_1
cd /var/www/html/project_1 and then as you have already initiated git and added remote origin so you just need to push your code to repo.
To do so, follow these steps:

1) You need to add all the files to a commit bucket to upload on repo. For that,

```<code>git add -A (it will add all the files of the folder project_1)
</code>```

2) Commit files with a message to track your uploaded work

```<code>git commit -m "First time uploading project 1"  // The commit message will be for your reference.
</code>```

3) Push the commited code now:

```<code>`git push origin master`  // this command will push the code to master branch which is the default branch in a repo. You can create any branches on Bitbucket and add their name after origin to push to that particular branch.
</code>```

After these 3 commands, check your repo. You should see your project up there.

Comment if you need further help.

Body:
I am new in bitbucket.I want to upload project from Linux to bitbucket.successfully I have created a bitbucket account and did the following

1)create a repository name 'testadmin'
2)Using command line cd /var/www/myname/myprojectname

git init
git remote add origin https://username@bitbucket.org/user/testadmin.git
git pull origin master

then I get

Password for 'https://user@bitbucket.org':
From https://bitbucket.org/user/testadmin
 * branch            master     -> FETCH_HEAD
Merge made by the 'recursive' strategy.
 README.md | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)

But I didn't get my project from bitbucket.Please help me

Body:
ok, then
I would advice you to keep your project folder in www directly. Like if your project folder name is project_1 then it should be at var/www/html/project_1

then open terminal and reach to the folder project_1
cd /var/www/html/project_1 and then as you have already initiated git and added remote origin so you just need to push your code to repo.
To do so, follow these steps:

1) You need to add all the files to a commit bucket to upload on repo. For that,

git add -A (it will add all the files of the folder project_1)

2) Commit files with a message to track your uploaded work

git commit -m "First time uploading project 1"  // The commit message will be for your reference.

3) Push the commited code now:

`git push origin master`  // this command will push the code to master branch which is the default branch in a repo. You can create any branches on Bitbucket and add their name after origin to push to that particular branch.

After these 3 commands, check your repo. You should see your project up there.

Comment if you need further help.


问:
Cannot fetch data from MySQL
this is my validation page

```<code> <html>
    <body>
    <?php
    function error_found(){
      header("Location: login.php");
    }
    set_error_handler('error_found');
    ?>
    <?php
    $con=mysqli_connect('localhost','root','','mydb');
    session_start();
    if(isset($_POST['loginbtn'])){
    $email=$_POST['email'];
    $password=$_POST['pwd'];
    $result=mysqli_query($con,'select * from myguests where email="'.$email.'" and password="'.$password.'"');
    if(mysqli_num_rows($result)==1)
    {
        $_SESSION['email']= $email;
        header("Location: welcome.php");
    }
    else
        echo"INVALID ACCOUNT";

    }

    ?>

    </body>
    </html>
</code>```

this is my user profile page

```<code><html>
    <body>

    <?php
     require_once 'valid.php';
        session_start();
    echo"welcome  " .$_SESSION['email'];
    $res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email=".$_SESSION['email']);
     $userRow=mysqli_fetch_array($res);
     echo $userRow;
    ?>
    <br><a href="logout.php">logout</a>
    </body>
    </html>

>
</code>```

I am not able to fetch the data from the database it shows me the error.I think I made mistake in declaring a session variable to the SQL query

答:
You have an error on your sql.

$res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email=".$_SESSION['email']);

It should be:

$res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email='".$_SESSION['email']."');

Title: Cannot fetch data from MySQL

Body:
this is my validation page

    <?php
    function error_found(){
      header("Location: login.php");
    }
    set_error_handler('error_found');
    ?>
    <?php
    $con=mysqli_connect('localhost','root','','mydb');
    session_start();
    if(isset($_POST['loginbtn'])){
    $email=$_POST['email'];
    $password=$_POST['pwd'];
    $result=mysqli_query($con,'select * from myguests where email="'.$email.'" and password="'.$password.'"');
    if(mysqli_num_rows($result)==1)
    {
        $_SESSION['email']= $email;
        header("Location: welcome.php");
    }
    else
        echo"INVALID ACCOUNT";

    }

    ?>

this is my user profile page

    <?php
     require_once 'valid.php';
        session_start();
    echo"welcome  " .$_SESSION['email'];
    $res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email=".$_SESSION['email']);
     $userRow=mysqli_fetch_array($res);
     echo $userRow;
    ?>

logout

>

I am not able to fetch the data from the database it shows me the error.I think I made mistake in declaring a session variable to the SQL query


问:
3rd party dependency tracking tool
I need to program a C# software that tracks all dependencies inside a .Net solution by parsing C# code. Dependencies such as database/tables/queries-vs-commands touched, web services and project dependencies, included projects/dll´s/nugets. This information is used to have an overview what dependencies are active/redundant within a solution. The program should later on also be able to parse PowerShell scripts and even Ruby to check for dependent resources.

My question is if there exists a 3rd party tool that does part or all of this?

答:
You can try the tool NDepend that parses dependencies between assemblies, namespaces, classes methods and fields of your Visual Studio Solution.

It comes with a dependency graph, a dependency matrix and a code query language that can be used to query dependencies.

However it doesn't parse yet Database dependencies.

Title: 3rd party dependency tracking tool


问:
Best practice for displaying multiple bitmaps in a scrollable list
What I am trying to do:

I render single pdf pages to bitmaps using Android PdfRenderer class.
(Rendering so fare is not the issue)

No I want to display the on the screen the entire first page and half of the second page.

My question?
What is the best approach to do that?
- Should I use a RecyclerView with several ImageViews
- Should I use two ImageViews with scrolling
- Performance matters, so should be efficient

I am glad for any comments or ideas.

答:
Not sure about the rendering part, but I did work with displaying multiple images.
You can use URIs or path of a bitmap to pass it to the adapter class.

```<code> public class MainActivity extends Activity
   {
   ArrayList<String> list; //get the path of a bitmap
    Bitmap bitmap;
     RecyclerView horizontal_rv;
    RecyclerViewAdapter recycleViewAdapter;
    recyvlerview= (RecyclerView);
    LinearLayoutManager horizontal_lm;

    findViewById(R.id.horizontal_recycler_view);//initializing the recyclerview

    horizontal_lm = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false); // calling the layout manager

    horizontal_rv.setLayoutManager(horizontal_lm); //setting the layout
      manager

  horizontal_rv= new RecyclerViewAdapter(list); // initializing the adapter, passing the list

   horizontal_rv.setAdapter(recycleViewAdapter);
       }
       // get image from the gallery
       @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == ImagePicker.IMAGE_PICKER_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
        List<String> mPaths = (List<String>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_PATH);
        for(String path:mPaths)
        {
            horizontalList.add(path);
            Log.e("horizontallist size", String.valueOf(horizontalList.size()));
        }
        Log.e("tag", String.valueOf(mPaths.size()));
        recycleViewAdapter.notifyDataSetChanged();
    }
}
</code>```

In the adapter class

```<code>   public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements Serializable{

private List<String> horizontalList;
public class MyViewHolder extends RecyclerView.ViewHolder {
    public ImageView image_result;

    public MyViewHolder(View view) {
        super(view);
        image_result = (ImageView) view.findViewById(R.id.image_result);
    }
}

public RecyclerViewAdapter(ArrayList<String> horizontalList) {
    this.horizontalList = horizontalList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.recyclerview_item_row, parent,false);

    return new MyViewHolder(itemView);

}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
   holder.image_result.setImageURI(Uri.parse(horizontalList.get(position)));  // setting image in the recycler view
    holder.image_result.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           // do anything with the image that is clicked
        }
    });
}

@Override
public int getItemCount() {
    return horizontalList.size();
}
public void removeAt(int position) {
    horizontalList.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, horizontalList.size());
}
</code>```

}

Body:
Not sure about the rendering part, but I did work with displaying multiple images.
You can use URIs or path of a bitmap to pass it to the adapter class.

 public class MainActivity extends Activity
   {
   ArrayList<String> list; //get the path of a bitmap
    Bitmap bitmap;
     RecyclerView horizontal_rv;
    RecyclerViewAdapter recycleViewAdapter;
    recyvlerview= (RecyclerView);
    LinearLayoutManager horizontal_lm;

    findViewById(R.id.horizontal_recycler_view);//initializing the recyclerview

    horizontal_lm = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false); // calling the layout manager

    horizontal_rv.setLayoutManager(horizontal_lm); //setting the layout
      manager

  horizontal_rv= new RecyclerViewAdapter(list); // initializing the adapter, passing the list

   horizontal_rv.setAdapter(recycleViewAdapter);
       }
       // get image from the gallery
       @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == ImagePicker.IMAGE_PICKER_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
        List<String> mPaths = (List<String>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_PATH);
        for(String path:mPaths)
        {
            horizontalList.add(path);
            Log.e("horizontallist size", String.valueOf(horizontalList.size()));
        }
        Log.e("tag", String.valueOf(mPaths.size()));
        recycleViewAdapter.notifyDataSetChanged();
    }
}

In the adapter class

   public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements Serializable{

private List<String> horizontalList;
public class MyViewHolder extends RecyclerView.ViewHolder {
    public ImageView image_result;

    public MyViewHolder(View view) {
        super(view);
        image_result = (ImageView) view.findViewById(R.id.image_result);
    }
}

public RecyclerViewAdapter(ArrayList<String> horizontalList) {
    this.horizontalList = horizontalList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.recyclerview_item_row, parent,false);

    return new MyViewHolder(itemView);

}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
   holder.image_result.setImageURI(Uri.parse(horizontalList.get(position)));  // setting image in the recycler view
    holder.image_result.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           // do anything with the image that is clicked
        }
    });
}

@Override
public int getItemCount() {
    return horizontalList.size();
}
public void removeAt(int position) {
    horizontalList.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, horizontalList.size());
}

}


问:
How to use FirebaseApp.initializeApp for FirebaseRemoteConfig
I am trying to use FirebaseApp.initializeApp, but its not working. I have the right library, but I cannot use the JSON file to initialize the app

This is my code:

Imports

```<code>import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
</code>```

Variables

```<code>private FirebaseRemoteConfig mFirebaseRemoteConfig;

private String projectID;
private String apiKey;
private String appID;
</code>```

How I initialize the app

```<code>public void Initialize() {
    FirebaseOptions mFirebaseOptions = new FirebaseOptions.Builder()
        .setApplicationId(this.appID)
        .setApiKey(this.apiKey)
        .build();
    FirebaseApp.initializeApp(this.context, mFirebaseOptions, this.projectID);
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
}
</code>```

The app crashed on startup this is the logcat error:

```<code>12-04 22:11:42.217 12566 12566 E AndroidRuntime: FATAL EXCEPTION: main
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Process: com.makeroid.sanderjochems.FirebaseRemoteConfig, PID: 12566
12-04 22:11:42.217 12566 12566 E AndroidRuntime: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzby;
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.FirebaseRemoteConfiguration.<init>(FirebaseRemoteConfiguration.java:67)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance0(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.expr.PrimProcedure.apply(PrimProcedure.java:272)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilDone(CallContext.java:234)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilValue(CallContext.java:298)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.kawa.reflect.Invoke.applyN(Invoke.java:209)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.ProcedureN.apply2(ProcedureN.java:39)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.makeroid.sanderjochems.FirebaseRemoteConfig.Screen1.$define(Screen1.yail:10182)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreateFinish(Form.java:389)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreate(Form.java:336)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Activity.performCreate(Activity.java:6942)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.-wrap14(ActivityThread.java)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:154)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:6682)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzby" on path: DexPathList[[zip file "/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/base.apk"],nativeLibraryDirectories=[/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/lib/arm64, /system/lib64, /vendor/lib64]]
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        ... 25 more
</code>```

答:
There may be multiple problems.  I'll point out what appears to be one.

The documentation for RemoteConfig.getInstance() notes that it expects the default FirebaseApp to be initialized:

FirebaseRemoteConfig uses the default FirebaseApp...

Unlike some of the other Firebase APIs, there is no way to initialize RemoteConfig using a different FirebaseApp.

That means that when you initialze FirebaseApp, projectID must be "[DEFAULT]", which is available as constant FirebaseApp.DEFAULT_APP_NAME.

```<code>FirebaseApp.initializeApp(this.context, mFirebaseOptions, this.projectID);
</code>```

Try setting projectID to "[DEFAULT]" (or the available constant) to see if the failure changes or is resolved.

Body:
I am trying to use FirebaseApp.initializeApp, but its not working. I have the right library, but I cannot use the JSON file to initialize the app

This is my code:

Imports

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;

Variables

private FirebaseRemoteConfig mFirebaseRemoteConfig;

private String projectID;
private String apiKey;
private String appID;

How I initialize the app

public void Initialize() {
    FirebaseOptions mFirebaseOptions = new FirebaseOptions.Builder()
        .setApplicationId(this.appID)
        .setApiKey(this.apiKey)
        .build();
    FirebaseApp.initializeApp(this.context, mFirebaseOptions, this.projectID);
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
}

The app crashed on startup this is the logcat error:

12-04 22:11:42.217 12566 12566 E AndroidRuntime: FATAL EXCEPTION: main
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Process: com.makeroid.sanderjochems.FirebaseRemoteConfig, PID: 12566
12-04 22:11:42.217 12566 12566 E AndroidRuntime: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzby;
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.FirebaseRemoteConfiguration.<init>(FirebaseRemoteConfiguration.java:67)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance0(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.expr.PrimProcedure.apply(PrimProcedure.java:272)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilDone(CallContext.java:234)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilValue(CallContext.java:298)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.kawa.reflect.Invoke.applyN(Invoke.java:209)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.ProcedureN.apply2(ProcedureN.java:39)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.makeroid.sanderjochems.FirebaseRemoteConfig.Screen1.$define(Screen1.yail:10182)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreateFinish(Form.java:389)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreate(Form.java:336)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Activity.performCreate(Activity.java:6942)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.-wrap14(ActivityThread.java)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:154)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:6682)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzby" on path: DexPathList[[zip file "/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/base.apk"],nativeLibraryDirectories=[/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/lib/arm64, /system/lib64, /vendor/lib64]]
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        ... 25 more

Body:
There may be multiple problems.  I'll point out what appears to be one.

The documentation for RemoteConfig.getInstance() notes that it expects the default FirebaseApp to be initialized:

FirebaseRemoteConfig uses the default FirebaseApp...

Unlike some of the other Firebase APIs, there is no way to initialize RemoteConfig using a different FirebaseApp.

That means that when you initialze FirebaseApp, projectID must be "[DEFAULT]", which is available as constant FirebaseApp.DEFAULT_APP_NAME.

FirebaseApp.initializeApp(this.context, mFirebaseOptions, this.projectID);

Try setting projectID to "[DEFAULT]" (or the available constant) to see if the failure changes or is resolved.


问:
Github Commit Failing After New Update
I've been trying to make new commits for and publish my project but I keep getting this error:

What is the solution to this issue because I can't figure out what the error means?

答:
You can see this bug followed in issue 2041.

```<code>Error: write EOF
at exports._errnoException (util.js:1022:11)
at WriteWrap.afterWrite (net.js:804:14)
</code>```

One possible cause is the path length: make sure your repo is cloned near C:\, for testing.

Title: Github Commit Failing After New Update

Body:
You can see this bug followed in issue 2041.

Error: write EOF
at exports._errnoException (util.js:1022:11)
at WriteWrap.afterWrite (net.js:804:14)

One possible cause is the path length: make sure your repo is cloned near C:\, for testing.


问:
Get email content by gmail addon
I am trying to get gmail content(body) like Wrike(https://imgur.com/a/9h1ij) but getting the above error.

"Access denied: : Not allowed for full access to mail message"

```<code>Logger.log(mail.getPlainBody());
</code>```

答:
Without seeing your code it seems to me that you need to include in your

"appsscript.json" file the correct scope.

```<code>// This scope allows you to: 'View your email messages and settings'
"oauthScopes": ["https://www.googleapis.com/auth/gmail.readonly"]

// This scope gives you full access to your Gmail - 'Read, send, delete, and manage your email'
"oauthScopes": ["https://mail.google.com/"]
</code>```

see the scope documentation here: https://developers.google.com/identity/protocols/googlescopes#gmailv1

Title: Get email content by gmail addon

Body:
I am trying to get gmail content(body) like Wrike(https://imgur.com/a/9h1ij) but getting the above error.

"Access denied: : Not allowed for full access to mail message"

Logger.log(mail.getPlainBody());

Body:
Without seeing your code it seems to me that you need to include in your

"appsscript.json" file the correct scope.

// This scope allows you to: 'View your email messages and settings'
"oauthScopes": ["https://www.googleapis.com/auth/gmail.readonly"]

// This scope gives you full access to your Gmail - 'Read, send, delete, and manage your email'
"oauthScopes": ["https://mail.google.com/"]

see the scope documentation here: https://developers.google.com/identity/protocols/googlescopes#gmailv1