问:
Troubles with listview in fragment
I am trying to make a list view with both images and text inside a fragment but i just cant get it to work.I get some kind of an error that tells me that i attempted to invoke the set Adapter method on a null object.What am i doing wrong

```<code>public class SecondFragment extends Fragment {
String[] listviewTitle = new String[]{"Drew Parker","Maggie Smith","Michael John","Luisa Miller","Loredana Marie","Cristopher Smidth","Michelle Acapella","John Fitzgerald"

};
int[] listviewImage = new int[]{
        R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile,

};
String[] listviewShortDescription = new String[]{
        "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description",
        "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description",
};

public SecondFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    List<HashMap<String, String>> aList = new ArrayList<>();
    for (int i = 0; i < 8; i++) {
        HashMap<String, String> hm = new HashMap<>();
        hm.put("listview_title", listviewTitle[i]);
        hm.put("listview_discription", listviewShortDescription[i]);
        hm.put("listview_image", Integer.toString(listviewImage[i]));
        aList.add(hm);
    }
    String[] from = {"listview_image", "listview_title", "listview_discription"};
    int[] to = {R.id.listview_image, R.id.listview_item_title, R.id.listview_item_short_description};

    SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.tab2fragment, from, to);
    ListView listView=(ListView)getActivity().findViewById(R.id.list_view);
    listView.setAdapter(simpleAdapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view=inflater.inflate(R.layout.listview_withimages_andnames,container,false);

    return view;
}
</code>```

}

答:
Remove the widgets initialization from onCreate and place it inside the onCreateView as below.

```<code> @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.listview_withimages_andnames,container,false);

    SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.tab2fragment, from, to);

    ListView listView=(ListView) view.findViewById(R.id.list_view);
    listView.setAdapter(simpleAdapter);

return view;   }
</code>```

and also replace

getActivity().findViewById(R.id.list_view)

by

view.findViewById(R.id.list_view)

Because you should get your recycler view from the fragment's layout which is being initialized in the onCreateView, not from the activity

Title: Troubles with listview in fragment

Body:
I am trying to make a list view with both images and text inside a fragment but i just cant get it to work.I get some kind of an error that tells me that i attempted to invoke the set Adapter method on a null object.What am i doing wrong

public class SecondFragment extends Fragment {
String[] listviewTitle = new String[]{"Drew Parker","Maggie Smith","Michael John","Luisa Miller","Loredana Marie","Cristopher Smidth","Michelle Acapella","John Fitzgerald"

};
int[] listviewImage = new int[]{
        R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile,

};
String[] listviewShortDescription = new String[]{
        "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description",
        "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description",
};

public SecondFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    List<HashMap<String, String>> aList = new ArrayList<>();
    for (int i = 0; i < 8; i++) {
        HashMap<String, String> hm = new HashMap<>();
        hm.put("listview_title", listviewTitle[i]);
        hm.put("listview_discription", listviewShortDescription[i]);
        hm.put("listview_image", Integer.toString(listviewImage[i]));
        aList.add(hm);
    }
    String[] from = {"listview_image", "listview_title", "listview_discription"};
    int[] to = {R.id.listview_image, R.id.listview_item_title, R.id.listview_item_short_description};

    SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.tab2fragment, from, to);
    ListView listView=(ListView)getActivity().findViewById(R.id.list_view);
    listView.setAdapter(simpleAdapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view=inflater.inflate(R.layout.listview_withimages_andnames,container,false);

    return view;
}

}

Body:
Remove the widgets initialization from onCreate and place it inside the onCreateView as below.

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.listview_withimages_andnames,container,false);

    SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.tab2fragment, from, to);

    ListView listView=(ListView) view.findViewById(R.id.list_view);
    listView.setAdapter(simpleAdapter);

return view;   }

and also replace

getActivity().findViewById(R.id.list_view)

by

view.findViewById(R.id.list_view)

Because you should get your recycler view from the fragment's layout which is being initialized in the onCreateView, not from the activity


来源: stackexchange

问:
Does String.to_atom("some-known-string") create a new atom in the atom-table each time?
Does String.to_atom("some-known-string") create a new atom in the atom-table each time?

If NO, then what is the point of String.to_existing_atom/1?

If YES, then why? since String.to_atom("some-known-string") will always give the same result ... and the atom-table is never garbage collected

答:
In elixir atoms are immutable.

```<code>field(q, ^(String.to_existing_atom k))
</code>```

In this example we are using existing_atom because we are fetching data form DB and existing make sure the field is valid. It is useful and in such scenarios.

ContentLicense: CC BY-SA 3.0

Body:
In elixir atoms are immutable.

field(q, ^(String.to_existing_atom k))

In this example we are using existing_atom because we are fetching data form DB and existing make sure the field is valid. It is useful and in such scenarios.


问:
Passing ggplot2's aes_string() a string via lapply doesn't work
I've written a function that requires one argument and is supposed to output a plot. The argument it takes is the variable to be plotted on the y axis as a character. Here is some example data:

```<code>df_year <- data.frame(year = c(2000, 2001), V1 = c(1.7,2.6))
df_year_speaker <- data.frame(year = c(2000, 2000, 2001, 2001),
                              speaker = c("Smith", "House", "Smith", "House"),
                              V1 = c(1.5,2,2.3,3),
                              partyaffil = c("rep", "dem", "rep", "dem"))
</code>```

And here my plot function:

```<code>require(ggplot2)
plot_fct <- function(means_year = df_year,
                     means_year_speaker = df_year_speaker,
                     x="year",
                     y="V1"){
  ggplot()+
    scale_fill_manual(values = c("#778aff","#ff6f54"))+ #blue,red
    geom_line(data = means_year, aes_string(x, y),
                color = "#212121")+
    geom_point(data = means_year_speaker,  aes_string(x, y))+
    geom_label(data = means_year_speaker, aes_string(x, y,label="speaker",
                                                       fill = "partyaffil"),
                                                       color = "#343434")
}
</code>```

When I run my function directly, it works just fine:

```<code>plot_fct(y = "V1")
</code>```

But when I call it via lapply I get an error:

```<code>> lapply(list(A = "V1"), FUN = plot_fct)
  Error: ggplot2 doesn't know how to deal with data of class character
</code>```

Running traceback revealed that the error is in fortify.default(data).
Any ideas on what's wrong or how I can pass strings to my function via lapply?

答:
The problem is that it is not clear which parameter of the function has to be set to the single values of the list.

If you change the signature of the function by removing the default parameter of y to

```<code>plot_fct <- function(y, means_year = df_year,
                 means_year_speaker = df_year_speaker,
                 x="year")
</code>```

it should work as you intended.

Body:
I've written a function that requires one argument and is supposed to output a plot. The argument it takes is the variable to be plotted on the y axis as a character. Here is some example data:

df_year <- data.frame(year = c(2000, 2001), V1 = c(1.7,2.6))
df_year_speaker <- data.frame(year = c(2000, 2000, 2001, 2001),
                              speaker = c("Smith", "House", "Smith", "House"),
                              V1 = c(1.5,2,2.3,3),
                              partyaffil = c("rep", "dem", "rep", "dem"))

And here my plot function:

require(ggplot2)
plot_fct <- function(means_year = df_year,
                     means_year_speaker = df_year_speaker,
                     x="year",
                     y="V1"){
  ggplot()+
    scale_fill_manual(values = c("#778aff","#ff6f54"))+ #blue,red
    geom_line(data = means_year, aes_string(x, y),
                color = "#212121")+
    geom_point(data = means_year_speaker,  aes_string(x, y))+
    geom_label(data = means_year_speaker, aes_string(x, y,label="speaker",
                                                       fill = "partyaffil"),
                                                       color = "#343434")
}

When I run my function directly, it works just fine:

plot_fct(y = "V1")

But when I call it via lapply I get an error:

> lapply(list(A = "V1"), FUN = plot_fct)
  Error: ggplot2 doesn't know how to deal with data of class character

Running traceback revealed that the error is in fortify.default(data).
Any ideas on what's wrong or how I can pass strings to my function via lapply?

Body:
The problem is that it is not clear which parameter of the function has to be set to the single values of the list.

If you change the signature of the function by removing the default parameter of y to

plot_fct <- function(y, means_year = df_year,
                 means_year_speaker = df_year_speaker,
                 x="year")

it should work as you intended.


问:
How can I pass a double array to a form and use it in multiple subs?
I already searched a lot but could not find a solution. I have a Form and in that Form I call another Form (let's say Form2). In Form 2 I can enter values in some textboxes and then I am passing these values as a double array back to Form 1:

```<code>Public Class Form1
  Dim a As Double
  Dim userDefined(3) As Double
  Dim Form_2 As Form2
  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    Form_2= New Form2
    Form_2.ShowDialog()
    a = userDefined(0)

  End Sub

  Public WriteOnly Property setUserValues As Array
    Set(value As Array)

        userDefined = value

    End Set
  End Property
End Class

Public Class Form2
  Dim userDefined(0 To 3) As Double

Private Sub Btn_transmitValues_Click(sender As System.Object, e As System.EventArgs) Handles Btn_transmitValues.Click

    userDefined(0) = Txt_1.Text
    userDefined(1) = Txt_2.Text
    userDefined(2) = Txt_3.Text
    userDefined(3) = Txt_4.Text

    Form1.setUserValues = userDefined

    Me.Dispose()

End Sub

End Class
</code>```

Now I want to use the values from the passed double array of Form2 in Form1 in the Button1_Click Sub. But when I define my array in Form1 as

```<code>Dim userDefined(3) As Double
</code>```

then a (also in Form1) is always 0. When I define my array in Form 1 as

```<code>Dim userDefined() As Double
</code>```

then I get the error "Object reference not set to an instance of an object" but when I hover over a the right value is passed. What can I do to get the right value for a? Thanks in advance.

答:
A nice easy way is to add a proprty in Form_2 such as

```<code>Public Property userDefined() as Double
</code>```

Then in Form one, where you have

```<code>Form_2= New Form2
Form_2.ShowDialog()
</code>```

add this inbetwen the two lines -

```<code>Form_2.userDefined= userDefined
</code>```

You may need to add code into the Form_2.Shown event to update any controls if the array affects any controls as soon as the form is shown, but that's about it.

Body:
I already searched a lot but could not find a solution. I have a Form and in that Form I call another Form (let's say Form2). In Form 2 I can enter values in some textboxes and then I am passing these values as a double array back to Form 1:

Public Class Form1
  Dim a As Double
  Dim userDefined(3) As Double
  Dim Form_2 As Form2
  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    Form_2= New Form2
    Form_2.ShowDialog()
    a = userDefined(0)

  End Sub

  Public WriteOnly Property setUserValues As Array
    Set(value As Array)

        userDefined = value

    End Set
  End Property
End Class

Public Class Form2
  Dim userDefined(0 To 3) As Double

Private Sub Btn_transmitValues_Click(sender As System.Object, e As System.EventArgs) Handles Btn_transmitValues.Click

    userDefined(0) = Txt_1.Text
    userDefined(1) = Txt_2.Text
    userDefined(2) = Txt_3.Text
    userDefined(3) = Txt_4.Text

    Form1.setUserValues = userDefined

    Me.Dispose()

End Sub

End Class

Now I want to use the values from the passed double array of Form2 in Form1 in the Button1_Click Sub. But when I define my array in Form1 as

Dim userDefined(3) As Double

then a (also in Form1) is always 0. When I define my array in Form 1 as

Dim userDefined() As Double

then I get the error "Object reference not set to an instance of an object" but when I hover over a the right value is passed. What can I do to get the right value for a? Thanks in advance.

Body:
A nice easy way is to add a proprty in Form_2 such as

Public Property userDefined() as Double

Then in Form one, where you have

Form_2= New Form2
Form_2.ShowDialog()

add this inbetwen the two lines -

Form_2.userDefined= userDefined

You may need to add code into the Form_2.Shown event to update any controls if the array affects any controls as soon as the form is shown, but that's about it.


问:
Make NetBeans(ant) generate multiple jar files for one project
i have a project in netbeans that include two main classes, one starts a client and other starts a server.

I need to create two jar file to wrap into two exe file, one for client and one for server, how can i do this?

Thanks.

NB: im using ant.

答:
You have two options:

First, you can overwrite the NetBeans ant target in the project's build.xml in order to create your two jar files.

How you can do this, is explained in the online help of NetBeans. The chapter is named "Customizing the IDE-Generated Ant Script

But I would recommend to create different projects for each "executable".

Most probably server and client are using some common code, so you'll wind up with three different projects in NetBeans:

MyApp Common - contains all classes that are used by server and client

MyApp Server - contains everything that you need for the server, includes the project "MyApp Common" as a library

MyApp Client - contains everything that you need for the client, includes the project "MyApp Common" as a library.

Then when you build the client or server project, each will generate a separate jar file.

ContentLicense: CC BY-SA 2.5


答:
Note that when you call plot_fct(y = "V1") you are passing V1 to the y= parameter in particular. When using lapply, by default it will go to the first parameter, and y is not the first parameter. YOu can do

```<code>lapply(list(A = "V1"), FUN = function(y) plot_fct(y=y))
</code>```

Title: Passing ggplot2's aes_string() a string via lapply doesn't work

Body:
Note that when you call plot_fct(y = "V1") you are passing V1 to the y= parameter in particular. When using lapply, by default it will go to the first parameter, and y is not the first parameter. YOu can do

lapply(list(A = "V1"), FUN = function(y) plot_fct(y=y))


问:
Directing robot framework results using Eclipse
I'm currently using the Eclipse RED plugin for my robot framework automation efforts. How do I direct the test results to a particular folder within my project? When using the terminal, I can direct to the "Results" folder using the following:

```<code>robot -d Results Tests\MyApp\AppDriverScript.robot
</code>```

However, I'm not sure how to direct the log & report files when using the Eclipse IDE using the Run command (Ctrl+F11).

答:
In the RED user guide there is a section about launching locally.

In the application you want to go to Run > Run Configurations > Robot where you add a new Run configuration. Pick the Project, and the proceed to add the Robot Test Suite File and (Optionally) select the keywords to run.

The argument you want to add is indeed -d Results in the Additional Robot Framework Arguments box. Only this needs to be added, the rest is taken care of by RED.

Body:
I'm currently using the Eclipse RED plugin for my robot framework automation efforts. How do I direct the test results to a particular folder within my project? When using the terminal, I can direct to the "Results" folder using the following:

robot -d Results Tests\MyApp\AppDriverScript.robot

However, I'm not sure how to direct the log & report files when using the Eclipse IDE using the Run command (Ctrl+F11).


问:
Spring cacheable - filter out empty collections using SpEL
I wanted to know is there a way to use SpEL in order to filter out values like empty collections.

My cache currently filters out null values:

```<code>  @Cacheable(value = "groupIdToGroupNames",unless = "#result == null")
   public Map<Long, Collection<String>> findAllBySearchCustomerKey(final long groupId) {
    return idToNameClient.findAllGroupMembersById(groupId);
   }
</code>```

I'm trying to find a way to filter out the groups that are of size 0 but not null.
Is there a way of doing that by using params for @Cacheable?

Any help would be much appreciated.

答:
Just to show an example (Artem Bilan answer is the valid one). My function can return Optional.ofEmpty or Optional of my object</p>

```<code>@Cacheable(value = "myCache", unless = "#result == null", key = "@myDao.cacheKey(#id, #languageCode)")
public Optional<MyDTO> getMyStuff(int id, String languageCode) {
... }
</code>```

Body:
I wanted to know is there a way to use SpEL in order to filter out values like empty collections.

My cache currently filters out null values:

  @Cacheable(value = "groupIdToGroupNames",unless = "#result == null")
   public Map<Long, Collection<String>> findAllBySearchCustomerKey(final long groupId) {
    return idToNameClient.findAllGroupMembersById(groupId);
   }

I'm trying to find a way to filter out the groups that are of size 0 but not null.
Is there a way of doing that by using params for @Cacheable?

Any help would be much appreciated.

Body:
Just to show an example (Artem Bilan answer is the valid one). My function can return Optional.ofEmpty or Optional of my object

@Cacheable(value = "myCache", unless = "#result == null", key = "@myDao.cacheKey(#id, #languageCode)")
public Optional<MyDTO> getMyStuff(int id, String languageCode) {
... }


问:
Return a promise without waiting for a dependant promise in function in nodejs
I am using node 8.x. Hence, I have access to all latest features i.e. async/ await etc.

The scenario is similar to following
(Not correct syntax, just for explanation):

```<code>createUser()
{
    let userAddress = createAddress(); // Aync, returns a promise
    User.create(name: 'foo', address: userAddress); // User creation is dependant on address. Also, User.create returns a promise.
}
</code>```

Basically, User object creation is dependant on the creation of address object. I want the createUser function to execute asynchronously i.e. to return a promise as soon as possible without waiting for address object to be created.

The purpose of this question is not to get things done but to understand what is the best way to solve this kind of issues in async programming.

Few ways that I can think of:
1: Create a new promise object and return right away when entered in createUser function. Resolve it when the user object is created.
2: Make createUser an async function and then return user Promise. Facing issues with this method:

```<code>async function createUser()
{
    address = await createAddress();
    return User.create(name: 'foo', address: userAddress);
}
</code>```

The problem is function waits for the address before returning the control which I don't want. (Or it does not make any diff as the function is async. Performance is a big criterion in my case)

How to deal with this kind of promise dependancy where you want to return promise of parent object but you parent object is dependant on child object's promise.

Thank you.

答:
Make createUser an async function and then return user Promise. The problem is function waits for the address before returning the control which I don't want.

No, it doesn't. An async function does immediately return a promise to its caller. It waits only when executing the code in its body (and resolves the promise when you return). Your code works, this is exactly what you should be doing.

Body:
I am using node 8.x. Hence, I have access to all latest features i.e. async/ await etc.

The scenario is similar to following
(Not correct syntax, just for explanation):

createUser()
{
    let userAddress = createAddress(); // Aync, returns a promise
    User.create(name: 'foo', address: userAddress); // User creation is dependant on address. Also, User.create returns a promise.
}

Basically, User object creation is dependant on the creation of address object. I want the createUser function to execute asynchronously i.e. to return a promise as soon as possible without waiting for address object to be created.

The purpose of this question is not to get things done but to understand what is the best way to solve this kind of issues in async programming.

Few ways that I can think of:
1: Create a new promise object and return right away when entered in createUser function. Resolve it when the user object is created.
2: Make createUser an async function and then return user Promise. Facing issues with this method:

async function createUser()
{
    address = await createAddress();
    return User.create(name: 'foo', address: userAddress);
}

The problem is function waits for the address before returning the control which I don't want. (Or it does not make any diff as the function is async. Performance is a big criterion in my case)

How to deal with this kind of promise dependancy where you want to return promise of parent object but you parent object is dependant on child object's promise.

Thank you.


问:
Output an index number and remove the path from file
I wrote this code, it works but there are 2 features I'd like to implement and I can't find out how.

First:
How to add an index number before each song so it looks like this:

Song1

Song2

Song3

Second:
The output to file includes the path to the file. How do I remove it?

```<code>namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] files = Directory.GetFiles("E:\\Music", "*", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                string FileName = Path.GetFileName(file);
                Console.WriteLine(FileName);
                System.IO.File.WriteAllLines("E:\\songs.txt", (files));
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

        }
    }
}
</code>```

答:
So, in order to only write the name of the songs and not the whole path, you'll have to use Path.GetFileNameWithoutExtensions.

To write the index before every song, you'll have to switch to a for loop (to work with the index).

Another problem is that you're writing to songs.txt for every song, which is bad. Here's a code to help you out:

```<code>string[] files = Directory.GetFiles(@"C:\Users\Admin\Music\Playlists", "*", SearchOption.AllDirectories);
StringBuilder sb = new StringBuilder();

for (int i = 0; i < files.Length; i++)
{
    sb.AppendLine($"{i + 1}. {Path.GetFileNameWithoutExtension(files[i])}");
    // Each line will be something like: Number. NameOfTheSong
}

// Only save to the file when everything is done
File.WriteAllText("E:\\songs.txt", sb.ToString());
Console.WriteLine("Press any key to exit");
Console.ReadLine();
</code>```

Body:
I wrote this code, it works but there are 2 features I'd like to implement and I can't find out how.

First:
How to add an index number before each song so it looks like this:

Song1

Song2

Song3

Second:
The output to file includes the path to the file. How do I remove it?

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] files = Directory.GetFiles("E:\\Music", "*", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                string FileName = Path.GetFileName(file);
                Console.WriteLine(FileName);
                System.IO.File.WriteAllLines("E:\\songs.txt", (files));
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

        }
    }
}

Body:
So, in order to only write the name of the songs and not the whole path, you'll have to use Path.GetFileNameWithoutExtensions.

To write the index before every song, you'll have to switch to a for loop (to work with the index).

Another problem is that you're writing to songs.txt for every song, which is bad. Here's a code to help you out:

string[] files = Directory.GetFiles(@"C:\Users\Admin\Music\Playlists", "*", SearchOption.AllDirectories);
StringBuilder sb = new StringBuilder();

for (int i = 0; i < files.Length; i++)
{
    sb.AppendLine($"{i + 1}. {Path.GetFileNameWithoutExtension(files[i])}");
    // Each line will be something like: Number. NameOfTheSong
}

// Only save to the file when everything is done
File.WriteAllText("E:\\songs.txt", sb.ToString());
Console.WriteLine("Press any key to exit");
Console.ReadLine();


问:
see all history of git
Let's say, my current git log is

commit3

commit2

commit1

I reset the head to commit2.

Now I want to go back to commit3, but I forget the sha-1 of commit3, so I want to look at the log , but "git log" will only show commit2, commit1, my question is how to reset to commit3 or let the log show also commit3 now?

Thanks

答: Use git reflog to find the old reference and pass it to git log directly. Note that the reflog is purged periodically, and old commits will be eventually deleted unless they're part of a branch - if you want to undo a commit but leave it in history, use git revert to undo them without removing them from history.

Title: see all history of git


问:
Set python variables to operators?

Python, Operators set to variables?

I am making a calculator and I want the user to be able to enter words like add to +.
 Is there any way to set python variables to operands. e.g.

```<code>operands = {
    "add": +
}
</code>```

etc.

Is there any way to do this  without modules. But if not possible is there a module?

答:
You can use two-argument functions, such as lambdas.

```<code>ops = {
    "add": lambda a, b: a + b,
    "sub": lambda a, b: a - b,
    "mul": lambda a, b: a * b,
    "div": lambda a, b: a + b,
    "pow": lambda a, b: a ** b
    # and so on
}

x = 42
y = 13
op = "add"

print(ops[op](x, y))     # 55
</code>```

The module operator includes predefined functions like this for all of Python's built-in operators.

Title: Set python variables to operators?

Body:
Python, Operators set to variables?

I am making a calculator and I want the user to be able to enter words like add to +.
 Is there any way to set python variables to operands. e.g.

operands = {
    "add": +
}

etc.

Is there any way to do this  without modules. But if not possible is there a module?

Body:
You can use two-argument functions, such as lambdas.

ops = {
    "add": lambda a, b: a + b,
    "sub": lambda a, b: a - b,
    "mul": lambda a, b: a * b,
    "div": lambda a, b: a + b,
    "pow": lambda a, b: a ** b
    # and so on
}

x = 42
y = 13
op = "add"

print(ops[op](x, y))     # 55

The module operator includes predefined functions like this for all of Python's built-in operators.


问:
Reduce the execution time of for loops in pandas
I am stuck with for loops execution in pandas.

Below is the code snippet,

```<code>for ix, pt in result.iterrows():
    for index,row in frame_SuggestedDose.iterrows():
        isTrue = False
        if (pt[0]==row[0] and pt[4]==row[10]):
            # print("found")
            pt[8] = row[2]
            isTrue = True
        if(isTrue or pt[4]>datetime.now().date()):
            break
        result.loc[ix] = pt
</code>```

In above code, 0,10,2,4 are the index of columns in data frames.

I want to copy value from frame_SuggestedDose to result if result patient id is same as frame_SuggestedDose patient id and dates are same

Head of result frame:

```<code>patientId   Date    IntervalDate    IntervalName    start_dt    Dose    FastingBloodGlucose IntervalSuggestedReason IntervalStatus  BGL SuggestedDose
006b5d  2017-09-08 20:30:00 2017-09-08 20:30:00 Int1    2017-09-08  NaN NaN suggested_dose_reason_new_care_plan NaN NaN 14.0
</code>```

for frame_SuggestedDose frame

```<code>    patientId   category    value   units   effective   status  fasting hypo    suggestedDose   suggestedReason effective_dt    effective_tm    dailyDoseTime   dose_dt dose_tm
   006b5d51 DOSE_SUGGESTION 14.0    units   2017-09-08 20:30:00 active  0.0 0.0 0.0 suggested_dose_reason_new_care_plan 2017-09-08  20:30:00    1970-01-01 20:30:00 1970-01-01  20:30:00
</code>```

It is taking around 2 hours to execute.

How can the execution time be reduced?

I am using Jupyter Notebook

答:
try the following code</p>

```<code>result = result.drop("value",axis=1)
result = pd.merge(result,
                  frame_SuggestedDose[["patientId","effective_dt","value"]],
                  left_on=["patientId","Date"],
                  right_on=["patientId","effective_dt"],
                  how="left")
</code>```

Body:
I am stuck with for loops execution in pandas.

Below is the code snippet,

for ix, pt in result.iterrows():
    for index,row in frame_SuggestedDose.iterrows():
        isTrue = False
        if (pt[0]==row[0] and pt[4]==row[10]):
            # print("found")
            pt[8] = row[2]
            isTrue = True
        if(isTrue or pt[4]>datetime.now().date()):
            break
        result.loc[ix] = pt

In above code, 0,10,2,4 are the index of columns in data frames.

I want to copy value from frame_SuggestedDose to result if result patient id is same as frame_SuggestedDose patient id and dates are same

Head of result frame:

patientId   Date    IntervalDate    IntervalName    start_dt    Dose    FastingBloodGlucose IntervalSuggestedReason IntervalStatus  BGL SuggestedDose
006b5d  2017-09-08 20:30:00 2017-09-08 20:30:00 Int1    2017-09-08  NaN NaN suggested_dose_reason_new_care_plan NaN NaN 14.0

for frame_SuggestedDose frame

    patientId   category    value   units   effective   status  fasting hypo    suggestedDose   suggestedReason effective_dt    effective_tm    dailyDoseTime   dose_dt dose_tm
   006b5d51 DOSE_SUGGESTION 14.0    units   2017-09-08 20:30:00 active  0.0 0.0 0.0 suggested_dose_reason_new_care_plan 2017-09-08  20:30:00    1970-01-01 20:30:00 1970-01-01  20:30:00

It is taking around 2 hours to execute.

How can the execution time be reduced?

I am using Jupyter Notebook

Body:
try the following code

result = result.drop("value",axis=1)
result = pd.merge(result,
                  frame_SuggestedDose[["patientId","effective_dt","value"]],
                  left_on=["patientId","Date"],
                  right_on=["patientId","effective_dt"],
                  how="left")


问:
Autorelease then retain for setters
According to the Google Objective-C Style Guide, we should autorelease then retain as so:

```<code>- (void)setFoo:(GMFoo *)aFoo {
  [foo_ autorelease];  // Won't dealloc if |foo_| == |aFoo|
  foo_ = [aFoo retain];
}
</code>```

In this case, foo_ will not be deallocated if being set to the same instance, making for a more defensive setter.

My question is, is this how @property & @synthesize work?

答:
release due to an autorelease isn't called until the end of the current runloop so foo_ wont dealloc because retain is called first followed by release at the end of the current runloop. However, this isn't how the code generated in @synthesize works. It works more like

```<code>- (void)setFoo:(GMFoo *)aFoo {
   if (aFoo != foo_) {
      [aFoo retain];
      [foo_ release];
      foo_ = aFoo;
   }
}
</code>```

This method saves cpu cycles when no change is necessary and takes out the small overhead of using the autorelease pool.

Title: Autorelease then retain for setters

Body:
According to the Google Objective-C Style Guide, we should autorelease then retain as so:

- (void)setFoo:(GMFoo *)aFoo {
  [foo_ autorelease];  // Won't dealloc if |foo_| == |aFoo|
  foo_ = [aFoo retain];
}

In this case, foo_ will not be deallocated if being set to the same instance, making for a more defensive setter.

My question is, is this how @property & @synthesize work?

Body:
release due to an autorelease isn't called until the end of the current runloop so foo_ wont dealloc because retain is called first followed by release at the end of the current runloop. However, this isn't how the code generated in @synthesize works. It works more like

- (void)setFoo:(GMFoo *)aFoo {
   if (aFoo != foo_) {
      [aFoo retain];
      [foo_ release];
      foo_ = aFoo;
   }
}

This method saves cpu cycles when no change is necessary and takes out the small overhead of using the autorelease pool.


问:
Calling Promise with Axios in Vue 2
How to implement Promise in this Axios POST request for Vue-Snotify?
This is my Axios post request:

```<code>const url = 'https://foobar.api/photos';
axios.post(url, {photo: "data:image/jpeg;base64," + photo})
    .then(function (response) {
        console.info('Done');
    })
    .catch(function (error) {
        console.error(error);
    });
</code>```

This package Vue-Snotify I want to add as a notifier what will show a notify box with a loader showing the progress. This is what it should look like regarding the docs:

```<code>this.$snotify.async('Called with promise', 'Success async', () => new Promise((resolve, reject) => {
  setTimeout(() => resolve({
    title: 'Success!!!',
    body: 'We got an example success!',
    config: {
      closeOnClick: true
    }
  }), 2000);
}));
</code>```

But how to achieve this? I'm no pro in Vue and can't figure out how to combine those two.

答:
You can return axios to accomplish this but if you catch the error Snotify will show a success message. Try this:

```<code>this.$snotify.async('Called with promise', 'Success async', () => {
    const url = 'https://foobar.api/photos';
    return axios.post(url, {photo: "data:image/jpeg;base64," + photo})
        .then(function (response) {
            console.info('Done');
        })
        .catch(function (error) {
            // handle error first

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

EDIT: If you want to control the messages to this instead:

```<code> this.$snotify.async('Called with promise', 'Success async', () => {
   return new Promise((resolve, reject) => {
     const url = 'https://foobar.api/photos';
     return axios.post(url, {photo: "data:image/jpeg;base64," + photo})
     .then(function (response) {
       resolve({
         title: 'Success!!!',
         body: 'We got an example success!',
         config: {
           closeOnClick: true
         }
       })
     })
     .catch(function (error) {
       reject({
         title: 'Error!!!',
         body: 'We got an example error!',
         config: {
           closeOnClick: true
         }
       })
     });
   });
 });
</code>```

Fiddle:
https://jsfiddle.net/qo6fdv1n/2/

Title: Calling Promise with Axios in Vue 2

Body:
How to implement Promise in this Axios POST request for Vue-Snotify?
This is my Axios post request:

const url = 'https://foobar.api/photos';
axios.post(url, {photo: "data:image/jpeg;base64," + photo})
    .then(function (response) {
        console.info('Done');
    })
    .catch(function (error) {
        console.error(error);
    });

This package Vue-Snotify I want to add as a notifier what will show a notify box with a loader showing the progress. This is what it should look like regarding the docs:

this.$snotify.async('Called with promise', 'Success async', () => new Promise((resolve, reject) => {
  setTimeout(() => resolve({
    title: 'Success!!!',
    body: 'We got an example success!',
    config: {
      closeOnClick: true
    }
  }), 2000);
}));

But how to achieve this? I'm no pro in Vue and can't figure out how to combine those two.

Body:
You can return axios to accomplish this but if you catch the error Snotify will show a success message. Try this:

this.$snotify.async('Called with promise', 'Success async', () => {
    const url = 'https://foobar.api/photos';
    return axios.post(url, {photo: "data:image/jpeg;base64," + photo})
        .then(function (response) {
            console.info('Done');
        })
        .catch(function (error) {
            // handle error first

            throw error;
        });
}));

EDIT: If you want to control the messages to this instead:

 this.$snotify.async('Called with promise', 'Success async', () => {
   return new Promise((resolve, reject) => {
     const url = 'https://foobar.api/photos';
     return axios.post(url, {photo: "data:image/jpeg;base64," + photo})
     .then(function (response) {
       resolve({
         title: 'Success!!!',
         body: 'We got an example success!',
         config: {
           closeOnClick: true
         }
       })
     })
     .catch(function (error) {
       reject({
         title: 'Error!!!',
         body: 'We got an example error!',
         config: {
           closeOnClick: true
         }
       })
     });
   });
 });

Fiddle:
https://jsfiddle.net/qo6fdv1n/2/


问:
ActiveRecord queries: Accessing outer field in subquery
I'm confused at how to do an active record join. I have three models, User, Task, and Response. A user submits responses to tasks. I'm using the has_many, through: pattern in ActiveRecord.

```<code>class Task < ApplicationRecord
  has_many :users, through: :responses
  has_many :responses
  validates :response_limit, presence: true

class User < ApplicationRecord
  has_many :responses
  has_many :tasks, through: :responses

class Response < ApplicationRecord
  belongs_to :task, optional: false
  belongs_to :user, optional: false
</code>```

In plain English, I'd like to create a query that given a query, returns all tasks that:

Has a Response count less than the :response_limit field in Task

The User has not responded to already.

I'm able to satisfy #2 with this nested query, which I got from an earlier question.

```<code>Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id]))
</code>```

However, I'm having difficulty satisfying the first. I took at stab at it and got this:

```<code>Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id])).where('response_limit > (?)', Response.where(task_id:task.id).count)
</code>```

My issue is that I'm not sure how to get the task_id from the outer query into the Response subquery.

答:
For this, you can try utilizing SQL GROUP BY and HAVING clauses that will help you count the responses and filter them based on a condition </p>

```<code>Task.select("tasks.*, COUNT(responses.id) AS response_count")
    .joins(:responses)
    .group("tasks.id")
    .where.not(id: Response.select(:task_id).where(user_id: params[:user_id]))
    .having("COUNT(responses.id) < tasks.response_limit")
</code>```

Body:
I'm confused at how to do an active record join. I have three models, User, Task, and Response. A user submits responses to tasks. I'm using the has_many, through: pattern in ActiveRecord.

class Task < ApplicationRecord
  has_many :users, through: :responses
  has_many :responses
  validates :response_limit, presence: true

class User < ApplicationRecord
  has_many :responses
  has_many :tasks, through: :responses

class Response < ApplicationRecord
  belongs_to :task, optional: false
  belongs_to :user, optional: false

In plain English, I'd like to create a query that given a query, returns all tasks that:

Has a Response count less than the :response_limit field in Task

The User has not responded to already.

I'm able to satisfy #2 with this nested query, which I got from an earlier question.

Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id]))

However, I'm having difficulty satisfying the first. I took at stab at it and got this:

Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id])).where('response_limit > (?)', Response.where(task_id:task.id).count)

My issue is that I'm not sure how to get the task_id from the outer query into the Response subquery.

Body:
For this, you can try utilizing SQL GROUP BY and HAVING clauses that will help you count the responses and filter them based on a condition

Task.select("tasks.*, COUNT(responses.id) AS response_count")
    .joins(:responses)
    .group("tasks.id")
    .where.not(id: Response.select(:task_id).where(user_id: params[:user_id]))
    .having("COUNT(responses.id) < tasks.response_limit")


问:
Cannot create virtualenv without using sudo
I am having problems regarding creating virtual environment for installing some python packages. The following thing is happening in my terminal. 'venv-py2' is the directory in which i am creating the virtual environment.
This directory is inside the current directory i am in my terminal i.e. 'B.E.N.J.I.'. Here are the two screenshots.

The thing is it works fine if i use the sudo command. Is there any other way to do it without using sudo?.

答:
It's not a python or virtualenv issue, it is about user permissions to write files under /media.

You are creating virtualenv under /media, it is the place where mounting external removable on the filesystem. You must have enough permission to create files under that folder. Either use sudo or switch to root user by sudo su -

Taking /media folder on my laptop as an example:

```<code>drwxr-xr-x   3 root root  4096 Aug  1 04:17 media
</code>```

Both owner and group are root, which means only user root and users in group root can write files under it

Body:
It's not a python or virtualenv issue, it is about user permissions to write files under /media.

You are creating virtualenv under /media, it is the place where mounting external removable on the filesystem. You must have enough permission to create files under that folder. Either use sudo or switch to root user by sudo su -

Taking /media folder on my laptop as an example:

drwxr-xr-x   3 root root  4096 Aug  1 04:17 media

Both owner and group are root, which means only user root and users in group root can write files under it


问:
Showing more text with jquery
I am looking for a way to show more or less text. I want to show 600 characters by default and if show more is clicked it will show 600 more characters and then if clicked again shows 600 more until there are no more characters. I also would like a show less button to collapse the text back to its default 600 characters. I have pages with 5000+ words and this would make reading much easier and make it look nicer. Right now I am using this to show the first 600 chars and when show more is clicked it expands all the way.

```<code>$(document).ready(function() {
var showChar = 600;
var ellipsestext = "...";
var moretext = "View more";
var lesstext = "View less";
$('.more').each(function() {
    var content = $(this).html();

    if(content.length > showChar) {

        var c = content.substr(0, showChar);
        var h = content.substr(showChar-1, content.length - showChar);

        var html = c + '<span class="moreelipses">'+ellipsestext+'</span> <span class="morecontent"><span>' + h + '  </span><a rel="nofollow" href="" class="morelink">'+moretext+'</a></span>';

        $(this).html(html);
    }

});

$(".morelink").click(function(){
    if($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
});
});
</code>```

Could somebody please edit this code to work like this or help me to achieve this any other way? I would really like to make my pages more presentable and readable and this would definitely do the trick. Thanks.

答:
check out the following links -

http://plugins.learningjquery.com/expander/index.html#getting-started

http://viralpatel.net/blogs/2010/12/dynamically-shortened-text-show-more-link-jquery.html

http://shakenandstirredweb.com/240/jquery-moreless-text

Title: Showing more text with jquery

Body:
I am looking for a way to show more or less text. I want to show 600 characters by default and if show more is clicked it will show 600 more characters and then if clicked again shows 600 more until there are no more characters. I also would like a show less button to collapse the text back to its default 600 characters. I have pages with 5000+ words and this would make reading much easier and make it look nicer. Right now I am using this to show the first 600 chars and when show more is clicked it expands all the way.

$(document).ready(function() {
var showChar = 600;
var ellipsestext = "...";
var moretext = "View more";
var lesstext = "View less";
$('.more').each(function() {
    var content = $(this).html();

    if(content.length > showChar) {

        var c = content.substr(0, showChar);
        var h = content.substr(showChar-1, content.length - showChar);

        var html = c + ''+ellipsestext+' ' + h + '  '+moretext+'';

        $(this).html(html);
    }

});

$(".morelink").click(function(){
    if($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
});
});

Could somebody please edit this code to work like this or help me to achieve this any other way? I would really like to make my pages more presentable and readable and this would definitely do the trick. Thanks.


问:
how to search string inside another string in system verilog?
If I want to know if string a is included string qwerty, is there an easy way to do this in system verilog? Like below code in C?

```<code>a.strstr("qwerty");
</code>```

答:
Based on the answer by awill I coded these two functions:</p>

```<code>function int contains(string a, string b);
  // checks if string A contains string B
  int len_a;
  int len_b;
  len_a = a.len();
  len_b = b.len();
  $display("a (%s) len %d -- b (%s) len %d", a, len_a, b, len_b);
  for( int i=0; i<len_a; i++) begin
    if(a.substr(i,i+len_b-1) == b)
         return 1;
  end
  return 0;
endfunction

function int startswith(string a, string b);
  // checks if string A starts-with string B
  int len_b;
  len_b = b.len();
  if(a.substr(0, len_b-1) == b)
    return 1;
  return 0;
endfunction
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I want to know if string a is included string qwerty, is there an easy way to do this in system verilog? Like below code in C?

a.strstr("qwerty");

Body:
Based on the answer by awill I coded these two functions:

function int contains(string a, string b);
  // checks if string A contains string B
  int len_a;
  int len_b;
  len_a = a.len();
  len_b = b.len();
  $display("a (%s) len %d -- b (%s) len %d", a, len_a, b, len_b);
  for( int i=0; i<len_a; i++) begin
    if(a.substr(i,i+len_b-1) == b)
         return 1;
  end
  return 0;
endfunction

function int startswith(string a, string b);
  // checks if string A starts-with string B
  int len_b;
  len_b = b.len();
  if(a.substr(0, len_b-1) == b)
    return 1;
  return 0;
endfunction


问:
How to convert an object to a string for a list search?
I am trying to search a list that contains only objects for a string input entered by the user. If an object in the list has a name that corresponds to the string input, the code should print the relevant info of the object and return it.

However, output is "0" even if I enter an item I know is on the list. I need python to recognize the objects in the list as a string so that it knows when the input is equal to one of the objects.

This is my code:

```<code>flavor_input = str.upper(input('What is the flavor of the cake you are looking for? '))
for var in cakeList:
     if str(var) == flavor_input:
         print('The flavor has been found')
         print(var)
         return var
    if var not in cakeList:
         print('The cake is not on the list!')
         return 0
</code>```

答:
You are checking the first item in the list and then iterate over the list inside the for loop. Your logic is faulty.

```<code>cakeList = ['SPAM', 'HAM']
flavor_input = str.upper(input('What is the flavor of the cake you are looking for? '))
for var in cakeList:
    if str(var) == flavor_input:
        print('The flavor has been found')
        print(var)
        break
else:
    print('The cake is not on the list!')
</code>```

Or more simply:

```<code>if flavor_input in map(str,cakeList):
    print('The flavor has been found')
else:
    print('The cake is not on the list!')
</code>```

Body:
I am trying to search a list that contains only objects for a string input entered by the user. If an object in the list has a name that corresponds to the string input, the code should print the relevant info of the object and return it.

However, output is "0" even if I enter an item I know is on the list. I need python to recognize the objects in the list as a string so that it knows when the input is equal to one of the objects.

This is my code:

flavor_input = str.upper(input('What is the flavor of the cake you are looking for? '))
for var in cakeList:
     if str(var) == flavor_input:
         print('The flavor has been found')
         print(var)
         return var
    if var not in cakeList:
         print('The cake is not on the list!')
         return 0

Body:
You are checking the first item in the list and then iterate over the list inside the for loop. Your logic is faulty.

cakeList = ['SPAM', 'HAM']
flavor_input = str.upper(input('What is the flavor of the cake you are looking for? '))
for var in cakeList:
    if str(var) == flavor_input:
        print('The flavor has been found')
        print(var)
        break
else:
    print('The cake is not on the list!')

Or more simply:

if flavor_input in map(str,cakeList):
    print('The flavor has been found')
else:
    print('The cake is not on the list!')


问:
Modeling velocity and height of rocket c++
Hi We are supposed to model the height and velocity of a rocket in c++ for our final project. Having user input the total flight time and delta time for the points during flight that they wish to measure. The following is the code I have written for this project. The velocity is supposed to start positive and after 60 seconds at which point there is no fuel left and thus no thrust the velocity should start becoming negative. However both my height and velocity are coming out as negative from the start and reaching negative infinite by the end.

```<code>#include <iostream>
using namespace std;
int main()
{
    float *v;
    float *h;
    float a;

    double mass=0.0, thrust, time, dt;
    double g = 32.2;
    double K = 0.008;

    cout << "enter time";
    cin >> time;
    cout << "enter dt";
    cin >> dt;

    a = (time/dt);
    v = new float[a];
    h = new float[a];

    v[0] = 0;
    h[0] = 0;
    float tt = 0;

    // for loop to calculate velocity and time
    for(int i = 0; i <= (time/dt) ; i++)
    {
        tt = dt + tt;

        if( tt <= 60)
        {
            mass = (3000-(40*tt)/g);
            thrust = 7000;
        }
        if ( tt > 60)
        {
            mass = 3000/g;
            thrust = 0;
        }

        // these are the formulas for velocity and height position our prof gave us
        v[i+1] = v[i] - (K/mass)*v[i]*v[i-1] * dt + (thrust/mass - g)*dt;
        h[i+1] = v[i+1] * dt + h[i];
    }

    // for loop to output
    for(int i = 0; i <= (time/dt); i++)
    {
        cout << i << " - " << "Velocity:" << v[i+1] << " Position:" << h[i+1] <<endl;
    }
    return 0;
}
</code>```

sample output:

```<code>enter time120
enter dt.01
0 - Velocity:-0.298667 Position:-0.00298667
1 - Velocity:-0.597333 Position:-0.00896
2 - Velocity:-0.895999 Position:-0.01792
3 - Velocity:-1.19467 Position:-0.0298666
4 - Velocity:-1.49333 Position:-0.0448
5 - Velocity:-1.792 Position:-0.0627199
6 - Velocity:-2.09066 Position:-0.0836266
7 - Velocity:-2.38933 Position:-0.10752

<...i left out a lot of numbers in the middle to not make this post too long...>

11994 - Velocity:-inf Position:-inf
11995 - Velocity:-inf Position:-inf
11996 - Velocity:-inf Position:-inf
11997 - Velocity:-inf Position:-inf
11998 - Velocity:-inf Position:-inf
11999 - Velocity:-inf Position:-inf
12000 - Velocity:-inf Position:-inf
Program ended with exit code: 0
</code>```

I have compared with my friends who are getting good results and we can not determine a difference between their code and mine. I have the rest of my program complete and working fine I just cannot figure out why my calculations are wrong

答: You are using v[i-1] but i starts out at 0, therefore this calculation is going to use whatever happens to be at v[-1]. I suggest you initialize i to 1 (and then check all the uses of i to ensure that the correct array elements will be used).</p>

Body:
Hi We are supposed to model the height and velocity of a rocket in c++ for our final project. Having user input the total flight time and delta time for the points during flight that they wish to measure. The following is the code I have written for this project. The velocity is supposed to start positive and after 60 seconds at which point there is no fuel left and thus no thrust the velocity should start becoming negative. However both my height and velocity are coming out as negative from the start and reaching negative infinite by the end.

#include <iostream>
using namespace std;
int main()
{
    float *v;
    float *h;
    float a;

    double mass=0.0, thrust, time, dt;
    double g = 32.2;
    double K = 0.008;

    cout << "enter time";
    cin >> time;
    cout << "enter dt";
    cin >> dt;

    a = (time/dt);
    v = new float[a];
    h = new float[a];

    v[0] = 0;
    h[0] = 0;
    float tt = 0;

    // for loop to calculate velocity and time
    for(int i = 0; i <= (time/dt) ; i++)
    {
        tt = dt + tt;

        if( tt <= 60)
        {
            mass = (3000-(40*tt)/g);
            thrust = 7000;
        }
        if ( tt > 60)
        {
            mass = 3000/g;
            thrust = 0;
        }

        // these are the formulas for velocity and height position our prof gave us
        v[i+1] = v[i] - (K/mass)*v[i]*v[i-1] * dt + (thrust/mass - g)*dt;
        h[i+1] = v[i+1] * dt + h[i];
    }

    // for loop to output
    for(int i = 0; i <= (time/dt); i++)
    {
        cout << i << " - " << "Velocity:" << v[i+1] << " Position:" << h[i+1] <<endl;
    }
    return 0;
}

sample output:

enter time120
enter dt.01
0 - Velocity:-0.298667 Position:-0.00298667
1 - Velocity:-0.597333 Position:-0.00896
2 - Velocity:-0.895999 Position:-0.01792
3 - Velocity:-1.19467 Position:-0.0298666
4 - Velocity:-1.49333 Position:-0.0448
5 - Velocity:-1.792 Position:-0.0627199
6 - Velocity:-2.09066 Position:-0.0836266
7 - Velocity:-2.38933 Position:-0.10752

<...i left out a lot of numbers in the middle to not make this post too long...>

11994 - Velocity:-inf Position:-inf
11995 - Velocity:-inf Position:-inf
11996 - Velocity:-inf Position:-inf
11997 - Velocity:-inf Position:-inf
11998 - Velocity:-inf Position:-inf
11999 - Velocity:-inf Position:-inf
12000 - Velocity:-inf Position:-inf
Program ended with exit code: 0

I have compared with my friends who are getting good results and we can not determine a difference between their code and mine. I have the rest of my program complete and working fine I just cannot figure out why my calculations are wrong


问:
User one @Pipe for two treatment
I would like to create a simple table with  the name of my items, a column that would take the "key" config and finally on the same line the values associated with "key" and .

But I use a @Pipe to filter my keys by removing the duplicates but I do not see how to bind the values associated with the keys.

Here is my code hoping that my explanation is correct

config.json :

[ { "id": "dev",
    "values": [ {
      "name": "password",
      "value": "root-default://dev" },

      { "name": "env",
        "value": "env-default://dev" },

       { "name": "user",
         "value": "toto-default://dev" },

       { "name": "element",
          "value": "element-default://dev" }
        ] },

      { "id": "test",
        "values": [ {
        "name": "password",
        "value": "root-default://test" },

       { "name": "env",
         "value": "env-default://test" },

       { "name": "user",
         "value": "toto-default://test" },

       { "name": "element",
         "value": "element-default://test" }
        ] },

       { "id": "toto",
        "values": [ {
          "name": "password",
          "value": "root-default://toto" },

          { "name": "env",
            "value": "env-default://toto" },

          { "name": "user",
            "value": "toto-default://toto" },

          { "name": "element",
            "value": "element-default://toto" }
           ] }
 ]```
</div>
</div>
</p>

<p>My Html :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ng-container *ngIf="service && config">
  <table style="color: white; background-color: red;">
    <tr>
      <th></th>
      <th *ngFor="let item of service.configs">{{item.name}}</th>
    </tr>

    <ng-container *ngFor="let key of (config | keys); let i = index">
        <tr>
          <td>{{key}}</td>
        </tr>
    </ng-container>
  </table>
</ng-container></code>```

My @Pipe:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
    transform(value: any) {
        let listConf = [];
        let result = [];
        if(! value){
            return result;
        }

        for (let obj in value){
            let item = value[obj];
            if (result.indexOf(item.values) < 0) {
                listConf.push(item.values);
            }
        }

        for (let values in listConf) {
            let value = listConf[values];

            for (let items in value) {
                let item = value[items];
                if (result.indexOf(item.name) < 0) {
                    result.push(item.name);
                }
            }
        }

        return result;
    }
}```
</div>
</div>
</p>

<p>For the display of the <code><th></code> I use another object "service" which lists the names of the config</p>

<p>Service.json</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
  "configs": [
      {"name": "dev"},
      {"name": "test"},
      {"name": "toto"}
  ]
}</code>```

My question is: how to have an array of key and an array of values in the same @Pipe

My result with this code :

Result table

答:
You can achieve this by completing the way you display your data in your view.

For example:

           <ng-container *ngFor="let item of config">

                  {{item.id}}

           </ng-container>

        <ng-container *ngFor="let key of (config | keys); let i = index">

               {{key}}
               {{config[0].values[i].value}}
               {{config[1].values[i].value}}
               {{config[2].values[i].value}}

         </ng-container>

```

With this i get this result:

Edit: this solution works only if you respect the order of the column at generation as i hardcoded the index of columns in the second ngFor

Title: User one @Pipe for two treatment

Body:
I would like to create a simple table with  the name of my items, a column that would take the "key" config and finally on the same line the values associated with "key" and .

But I use a @Pipe to filter my keys by removing the duplicates but I do not see how to bind the values associated with the keys.

Here is my code hoping that my explanation is correct

config.json :

[ { "id": "dev",
    "values": [ {
      "name": "password",
      "value": "root-default://dev" },

      { "name": "env",
        "value": "env-default://dev" },

       { "name": "user",
         "value": "toto-default://dev" },

       { "name": "element",
          "value": "element-default://dev" }
        ] },

      { "id": "test",
        "values": [ {
        "name": "password",
        "value": "root-default://test" },

       { "name": "env",
         "value": "env-default://test" },

       { "name": "user",
         "value": "toto-default://test" },

       { "name": "element",
         "value": "element-default://test" }
        ] },

       { "id": "toto",
        "values": [ {
          "name": "password",
          "value": "root-default://toto" },

          { "name": "env",
            "value": "env-default://toto" },

          { "name": "user",
            "value": "toto-default://toto" },

          { "name": "element",
            "value": "element-default://toto" }
           ] }
 ]

My Html :

<ng-container *ngIf="service && config">

      {{item.name}}

    <ng-container *ngFor="let key of (config | keys); let i = index">

          {{key}}

    </ng-container>

</ng-container>

My @Pipe:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
    transform(value: any) {
        let listConf = [];
        let result = [];
        if(! value){
            return result;
        }

        for (let obj in value){
            let item = value[obj];
            if (result.indexOf(item.values) < 0) {
                listConf.push(item.values);
            }
        }

        for (let values in listConf) {
            let value = listConf[values];

            for (let items in value) {
                let item = value[items];
                if (result.indexOf(item.name) < 0) {
                    result.push(item.name);
                }
            }
        }

        return result;
    }
}

For the display of the  I use another object "service" which lists the names of the config

Service.json

{
  "configs": [
      {"name": "dev"},
      {"name": "test"},
      {"name": "toto"}
  ]
}

My question is: how to have an array of key and an array of values in the same @Pipe

My result with this code :

Result table

Body:
You can achieve this by completing the way you display your data in your view.

For example:

<table>
        <tr>
           <th></th>
           <ng-container *ngFor="let item of config">
              <th>
                  {{item.id}}
              </th>
           </ng-container>
        </tr>
        <ng-container *ngFor="let key of (config | keys); let i = index">
            <tr>
               <td>{{key}}</td>
               <td>{{config[0].values[i].value}}</td>
               <td>{{config[1].values[i].value}}</td>
               <td>{{config[2].values[i].value}}</td>
            </tr>
         </ng-container>
   </table>

With this i get this result:

Edit: this solution works only if you respect the order of the column at generation as i hardcoded the index of columns in the second ngFor


问:
C# asp.net cannot open user default database .ldf may be incorrect
I am having an odd problem with my SQL Server express 2005 DB.  It is running on a 2003 server.  With VS2005 I can access the db without any problem.  But when I try and run the application I get:

```<code> Cannot open user default database. Login failed.  Login failed for user 'NT AUTHORITY\NETWORK SERVICE'......... .ldf may be incorrect.
</code>```

I have ensured that NETWORK SERVICE has full access to the website folder and all it sub folders.

I have noticed that when I look at the properties of App_Data it has a gray tick on the read only.  The .MDF file is not read only but I can not remove this gray tick.  I have tried just clicking it till its gone and applying changes, I have tried ATTRIB . -r but nothing seems to change it.

I am very confused.

Jon

答:
The difference isn't related to ACLs on the folder but to that fact that the security context is mapped to a user in the DB.  Your DB will have a mapping for your user account probably to dbo.

If the Network Service account is going to use the DB you need to create a user in the db to map to Machine account.

OwnerDisplayName: Jon

Body:
I am having an odd problem with my SQL Server express 2005 DB.  It is running on a 2003 server.  With VS2005 I can access the db without any problem.  But when I try and run the application I get:

 Cannot open user default database. Login failed.  Login failed for user 'NT AUTHORITY\NETWORK SERVICE'......... .ldf may be incorrect.

I have ensured that NETWORK SERVICE has full access to the website folder and all it sub folders.

I have noticed that when I look at the properties of App_Data it has a gray tick on the read only.  The .MDF file is not read only but I can not remove this gray tick.  I have tried just clicking it till its gone and applying changes, I have tried ATTRIB . -r but nothing seems to change it.

I am very confused.

Jon

LastEditorDisplayName: gbn

OwnerDisplayName: AnthonyWJones


问:
How Can I Make WordPress's <?php the_title_attribute(); ?> Render %20 for Spaces?
I'm trying to render a WordPress theme that is 100% HTML5 compliant, and have managed my way through all but one snag.

At the end of certain posts I show a "Tweet" link, which uses the following source code in the Theme template:

```<code><a href="http://twitter.com/share?text=<?php the_title_attribute(); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>
</code>```

HTML5 forbids having spaces in URLs. They must be rendered as %20. However, <?php the_title_attribute; ?> renders an XHTML safe version of the Post Title with spaces maintained.

An example URL (rendered using the template source code above):

```<code>a href="http://twitter.com/share?text=Twitter, Reblog, and Email Comments&via=ianhines&url=http://ihin.es/eCoYN9" title="Share This Article on Twitter">Tweet</a>
</code>```

Is there any way I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?

答:
Well, just wrap the the_title_attribute() with urlencode():

```<code>/share?text=<?php echo urlencode(the_title_attribute()); ?>&via=
</code>```

Edit: Ok, due to that comment, you'd need to do something like this:

```<code><?php
ob_start();
the_title_attribute();
$title = ob_get_clean();
?>
/share?text=<?php echo urlencode($title); ?>&via=
</code>```

Edit2: Looking at the docs for the_title_attribute:

```<code>/share?text=<?php echo urlencode(the_title_attribute('echo=0')); ?>&via=
</code>```

Body:
I'm trying to render a WordPress theme that is 100% HTML5 compliant, and have managed my way through all but one snag.

At the end of certain posts I show a "Tweet" link, which uses the following source code in the Theme template:

<a href="http://twitter.com/share?text=<?php the_title_attribute(); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet

HTML5 forbids having spaces in URLs. They must be rendered as %20. However, <?php the_title_attribute; ?> renders an XHTML safe version of the Post Title with spaces maintained.

An example URL (rendered using the template source code above):

a href="http://twitter.com/share?text=Twitter, Reblog, and Email Comments&via=ianhines&url=http://ihin.es/eCoYN9" title="Share This Article on Twitter">Tweet

Is there any way I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?

Body:
Well, just wrap the the_title_attribute() with urlencode():

/share?text=<?php echo urlencode(the_title_attribute()); ?>&amp;via=

Edit: Ok, due to that comment, you'd need to do something like this:

<?php
ob_start();
the_title_attribute();
$title = ob_get_clean();
?>
/share?text=<?php echo urlencode($title); ?>&amp;via=

Edit2: Looking at the docs for the_title_attribute:

/share?text=<?php echo urlencode(the_title_attribute('echo=0')); ?>&amp;via=


问:
How do I use arrow functions filtering a property by a list
I have an array of objects and I am trying to remove several elements by a list of ids in another array.

Say I have

```<code>transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];

ids = [12, 98];
</code>```

Then I want to end up with

```<code>transactions = [{id:18, name:'trs18'}, {id:45, name:'trs145'}];
</code>```

I am trying to remove the elements from the transactions array that have the id specified in the ids array.

I am thinking of creating a sub array doing a filter and replacing the original array with this new sub array which does not contains the elements included in the ids array.

Something like

```<code>var subArray = transactions.filter(trans => trans.id != ids)
transactions = subArray;
</code>```

But I am new to arrow functions and I don't know how to accomplish this. In the documentation I only see that they use == as the comparison operator. But I am looking for something that compares against a list of elements.

答:
You could check the id with Array#every.

var transactions = [{ id: 12, name: 'trs1' }, { id: 18, name: 'trs18' }, { id: 45, name: 'trs145' }, { id: 98, name: 'trs19' }],
    ids = [12, 98],
    subArray = transactions.filter(trans => ids.every(id => trans.id !== id));

console.log(subArray);```

Body:
I have an array of objects and I am trying to remove several elements by a list of ids in another array.

Say I have

transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];

ids = [12, 98];

Then I want to end up with

transactions = [{id:18, name:'trs18'}, {id:45, name:'trs145'}];

I am trying to remove the elements from the transactions array that have the id specified in the ids array.

I am thinking of creating a sub array doing a filter and replacing the original array with this new sub array which does not contains the elements included in the ids array.

Something like

var subArray = transactions.filter(trans => trans.id != ids)
transactions = subArray;

But I am new to arrow functions and I don't know how to accomplish this. In the documentation I only see that they use == as the comparison operator. But I am looking for something that compares against a list of elements.


问:
Browser displaying blank page when I run my code
This is probably a very silly question but when I try to run my code in Notepad++ on either browser such as Chrome and IE. It's not showing. I have carefully looked at the code to see if i'm missing anything but I can't seem to figure out what.

I recently asked a question about help on my code and it got fixed, it was working when I ran the "Run code snippet" thingy but when I copied the code to my Notepad++, it's not working. This is my code...

```<code><!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="gamescript.js">
</head>

<body>
<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<!---- Question 1 ---->
<p id ="choice1">Behind Door 1 is an empty room. Whilst searching the room for clues, you see a hidden passageway. Do you wish to enter the passageway or continue searching?</p>

<div id="question2">
<input id="myInput2" type="text">

<button onclick="myFunction2()">Enter</button>
</div>

<!---- Boss ---->
<div id="question3">
<h1>Fight the Monster!</h1>

<p id="mspace"></p>

<div id="game">

  <button id="fight">Fight</button>
  <button id="run">Run</button>

</div>
</div>

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

.

```<code>document.getElementById("choice1").style.visibility = "hidden";
document.getElementById("question2").style.visibility = "hidden";
document.getElementById("question3").style.visibility = "hidden";

function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1" || door == "door 1"){
        document.getElementById("door").innerHTML = "You have entered " + door;
        document.getElementById("choice1").style.visibility = "visible";
document.getElementById("question2").style.visibility = "visible";
    }else if (door == "Door 2" || door == "door 2"){
        document.getElementById("door").innerHTML = "You have entered " + door;
        document.getElementById("choice1").style.visibility = "visible";
document.getElementById("question2").style.visibility = "visible";
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

function myFunction2(){
    var choice1 = document.getElementById("myInput2").value;
    if (choice1 == "enter passageway" || choice1 == "passageway"){
        document.getElementById("choice1").innerHTML = "You entered the " + choice1;
        document.getElementById("question3").style.visibility = "visible";
     }else if (choice1 == "continue searching"){
        document.getElementById("choice1").innerHTML = "You " + choice1;
        document.getElementById("question3").style.visibility = "visible";
    }else{
        document.getElementById("choice1").innerHTML = "You must choose an option!"
    }
}

// JS for BOSS level
// starting variable for the boss
var stamina = 10;

// starting message
var msg = "A huge, threatening monster wants to fight you! What do you do?";
// run a function that is below
document.getElementById("mspace").innerHTML = msg;

// click a button to execute a function
// NOTE: no parentheses after the function name in these cases
window.onload = function(){
    document.getElementById("fight").onclick = fightResponse;
    document.getElementById("run").onclick = runResponse;
}

function runResponse() {
  if (stamina > 8) {
    msg = "The monster swings his long arm and -- GAME OVER!";
    hideButtons();
  } else if (stamina > 3) {
    msg = "Well, that's one way to end a fight ...";
    hideButtons();
  } else {
    msg = "Keep fighting! The monster is almost dead!";
  }
  writeMessage();
}

function fightResponse() {
  if (stamina > 8) {
    msg = "The monster is strong! It resists your attack!";
  } else if (stamina > 5) {
    msg = "With a loud screech, the monster stands firm.";
  } else if (stamina > 3) {
    msg = "Your attack seems to be having an effect! The monster stumbles!";
  } else if (stamina > 0) {
    msg = "This monster is about to fall! It staggers and reels!";
  } else {
    msg = "With a final swing! The monster has been defeated! You have triumphed!";
    hideButtons();
  }
  // create new random number from 0 to 5
  var damage = Math.floor(Math.random() * 6);
  // subtract it from stamina
  stamina -= damage;
  writeMessage();
}

function hideButtons() {
  // changes the class on the div - see the CSS pane
  document.getElementById("game").className = "hideThis";
}

function writeMessage() {
  document.getElementById("mspace").innerHTML = msg;
}
</code>```

I tried using the F12 developer tool but no errors are showing. I don't know why it's not working on Notepad++. All help is always appreciated and thank you very much!

答:
I think you need to add a </script> so this

```<code><script type="text/javascript" src="gamescript.js" >
</code>```

becomes this:

```<code><script type="text/javascript" src="gamescript.js" ></script>
</code>```

Body:
This is probably a very silly question but when I try to run my code in Notepad++ on either browser such as Chrome and IE. It's not showing. I have carefully looked at the code to see if i'm missing anything but I can't seem to figure out what.

I recently asked a question about help on my code and it got fixed, it was working when I ran the "Run code snippet" thingy but when I copied the code to my Notepad++, it's not working. This is my code...

<!DOCTYPE HTML>

Body:
I think you need to add a </script> so this

<script type="text/javascript" src="gamescript.js" >

becomes this:

<script type="text/javascript" src="gamescript.js" ></script>


问:
Install a feature according to a user input
I have 2 features.

Network Device.

USB Device.

And i need them to install, one at a time. Customize dialog allows to install both features at one time, which i wanted to avoid, so I removed the "Customize" Dialog (I am using "WixUI_Mondo") and I added a custom dialog with 2 radio buttons.

```<code><Control Id ="ConnectionType" Type="RadioButtonGroup" Property="CONPROPERTY" X="20" Y="60" Width="330" Height="100" Text="test">
  <RadioButtonGroup Property="CONPROPERTY">
    <RadioButton Text="!(loc.ChooseConnectionTypeDevice)" Value="network" Height="18" Width="370" X="0" Y="20" />
    <RadioButton Text="!(loc.ChooseConnectionTypeUSB)" Value="usb" Height="18" Width="370" X="0" Y="40" />
  </RadioButtonGroup>
</Control>
</code>```

Now I want to install above features according to the selection of the radio buttons.

I tried adding a condition to my features. but it seems it is not working. I guess this is not working at run time.

```<code><Feature Id='NetworkDevice' Level="1">

<ComponentRef Id='cmpConfig' />
<ComponentRef Id='cmpCatalog' />

<Condition Level="0"><![CDATA[CONPROPERTY<>"network"]]></Condition>
</Feature>

<Feature Id='UsbDevice' Level="1">
<ComponentRef Id='cmpConfig' />
<ComponentRef Id='cmpCatalog' />
<ComponentRef Id='cmpUsbInstallation' />

<Condition Level='0'><![CDATA[CONPROPERTY<>"usb"]]></Condition>
</Feature>
</code>```

How could i achieve this scenario. can any one show me a path?

答:
This won't work the way you expect. The 'Condition' references in the code end up authoring MSI Condition Table entires. These are evaluated before your UI ever pops up. What you want is 'Publish' ControlEvents that will turn the features on/off when the user clicks the "Next" button. Something like this:</p>

```<code><Publish Dialog="YourDialog" Control="Next" Event="AddLocal" Value="NetworkDevice" Order="1">![CDATA[CONPROPERTY=network]]</Publish>
<Publish Dialog="YourDialog" Control="Next" Event="Remove" Value="NetworkDevice" Order="2">![CDATA[CONPROPERTY<>network]]</Publish>
<Publish Dialog="YourDialog" Control="Next" Event="AddLocal" Value="UsbDevice" Order="3">![CDATA[CONPROPERTY=usb]]</Publish>
<Publish Dialog="YourDialog" Control="Next" Event="Remove" Value="UsbDevice" Order="4">![CDATA[CONPROPERTY<>usb]]</Publish>
</code>```

Body:
I have 2 features.

Network Device.

USB Device.

And i need them to install, one at a time. Customize dialog allows to install both features at one time, which i wanted to avoid, so I removed the "Customize" Dialog (I am using "WixUI_Mondo") and I added a custom dialog with 2 radio buttons.

<Control Id ="ConnectionType" Type="RadioButtonGroup" Property="CONPROPERTY" X="20" Y="60" Width="330" Height="100" Text="test">
  <RadioButtonGroup Property="CONPROPERTY">
    <RadioButton Text="!(loc.ChooseConnectionTypeDevice)" Value="network" Height="18" Width="370" X="0" Y="20" />
    <RadioButton Text="!(loc.ChooseConnectionTypeUSB)" Value="usb" Height="18" Width="370" X="0" Y="40" />
  </RadioButtonGroup>
</Control>

Now I want to install above features according to the selection of the radio buttons.

I tried adding a condition to my features. but it seems it is not working. I guess this is not working at run time.

<Feature Id='NetworkDevice' Level="1">

<ComponentRef Id='cmpConfig' />
<ComponentRef Id='cmpCatalog' />

<Condition Level="0"><![CDATA[CONPROPERTY<>"network"]]></Condition>
</Feature>

<Feature Id='UsbDevice' Level="1">
<ComponentRef Id='cmpConfig' />
<ComponentRef Id='cmpCatalog' />
<ComponentRef Id='cmpUsbInstallation' />

<Condition Level='0'><![CDATA[CONPROPERTY<>"usb"]]></Condition>
</Feature>

How could i achieve this scenario. can any one show me a path?

Body:
This won't work the way you expect. The 'Condition' references in the code end up authoring MSI Condition Table entires. These are evaluated before your UI ever pops up. What you want is 'Publish' ControlEvents that will turn the features on/off when the user clicks the "Next" button. Something like this:

<Publish Dialog="YourDialog" Control="Next" Event="AddLocal" Value="NetworkDevice" Order="1">![CDATA[CONPROPERTY=network]]</Publish>
<Publish Dialog="YourDialog" Control="Next" Event="Remove" Value="NetworkDevice" Order="2">![CDATA[CONPROPERTY<>network]]</Publish>
<Publish Dialog="YourDialog" Control="Next" Event="AddLocal" Value="UsbDevice" Order="3">![CDATA[CONPROPERTY=usb]]</Publish>
<Publish Dialog="YourDialog" Control="Next" Event="Remove" Value="UsbDevice" Order="4">![CDATA[CONPROPERTY<>usb]]</Publish>


问:
Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found
I've seen other questions related to this issue but none of them actually helps with my issue.

I have these two properties defined in my test class.

```<code>  @Autowired
  private MessagingProperties messagingProperties;

  @Autowired
  private MessagingPropertiesRefactor messagingPropertiesRefactor;
</code>```

I am trying to create a new version of MessagingProperties.java. I basically copied this class and create a new file MessagingPropertiesRefactor.java (same package/dir) and pasted the same code. I changed the class definition, etc., but for the most part are the same.

I get an IntelliJ design time compiler error stating that "Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found."

I then searched for every single Usage of the original class to double check if it has been declared somewhere but I have found nothing.

I am "new" to Java (and Spring). Has anyone run into the same issue before?

答: Ensure that MessagingPropertiesRefactor has all annotations applied to the class that MessagingProperties has. If it has, than look for the bean definition of MessagingProperties  in xml configurations for your project and make a copy.

Body:
I've seen other questions related to this issue but none of them actually helps with my issue.

I have these two properties defined in my test class.

  @Autowired
  private MessagingProperties messagingProperties;

  @Autowired
  private MessagingPropertiesRefactor messagingPropertiesRefactor;

I am trying to create a new version of MessagingProperties.java. I basically copied this class and create a new file MessagingPropertiesRefactor.java (same package/dir) and pasted the same code. I changed the class definition, etc., but for the most part are the same.

I get an IntelliJ design time compiler error stating that "Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found."

I then searched for every single Usage of the original class to double check if it has been declared somewhere but I have found nothing.

I am "new" to Java (and Spring). Has anyone run into the same issue before?


问:
Difference between ++ and +=1 in javascript
Could somebody explain why the following functions give different results.  The first does not seem to work, but the second does. I'm puzzled because I thought +=1 and ++ did the same thing.

(I'm not intending to actually use this code, it's just to demonstrate the difference).

```<code>/*function 1*/
function incrementIfZero1(base,element) {

    if (element == 0) {
        return base++;
    }
    else
    {
        return base;
    }
};

/*function 2*/
function incrementIfZero2(base,element) {

    if (element == 0) {
        return base+=1;
    }
    else
    {
        return base;
    }
};

incrementIfZero1(1,0) /* -> 1*/
incrementIfZero2(1,0) /* -> 2*/
</code>```

Any help is very much appreciated.

Thanks,

Robin

[Edit:]

Thank you for your replies, it makes sense now.  I had also tried the following statement, which resulted in the same thing as function 1:

```<code>return (base++)
</code>```

I'm now surprised that this doesn't give the same result as function 2 - I would have expected the brackets to 'force' it to be evaluated before returning.  Any idea why this is not the case?

答:
Warning! There's a difference when two different types, a string and a number, are mutated using ++ and +=:

When count is a string, count += 1 seems to do type conversion and converts the 2nd number to a string, whereas count++ takes the string count argument, converts to a number, and increments by 1.

```<code>let count = process.argv[2]

while (count < 5) {
  console.log('Inside of the loop. Count is', count)
  count += 1 // NOT likely what you want! Now, try it with count++
}

console.log('Outside of loop. Count is', count)
</code>```

Another example:

```<code>> let num = '2'
undefined
> num++
2
> num
3

// VS using +=

> let num2 = '2'
undefined
> num2 += 1
'21'
> num2
'21'
</code>```

Body:
Could somebody explain why the following functions give different results.  The first does not seem to work, but the second does. I'm puzzled because I thought +=1 and ++ did the same thing.

(I'm not intending to actually use this code, it's just to demonstrate the difference).

/*function 1*/
function incrementIfZero1(base,element) {

    if (element == 0) {
        return base++;
    }
    else
    {
        return base;
    }
};

/*function 2*/
function incrementIfZero2(base,element) {

    if (element == 0) {
        return base+=1;
    }
    else
    {
        return base;
    }
};

incrementIfZero1(1,0) /* -> 1*/
incrementIfZero2(1,0) /* -> 2*/

Any help is very much appreciated.

Thanks,

Robin

[Edit:]

Thank you for your replies, it makes sense now.  I had also tried the following statement, which resulted in the same thing as function 1:

return (base++)

I'm now surprised that this doesn't give the same result as function 2 - I would have expected the brackets to 'force' it to be evaluated before returning.  Any idea why this is not the case?

Body:
Warning! There's a difference when two different types, a string and a number, are mutated using ++ and +=:

When count is a string, count += 1 seems to do type conversion and converts the 2nd number to a string, whereas count++ takes the string count argument, converts to a number, and increments by 1.

let count = process.argv[2]

while (count < 5) {
  console.log('Inside of the loop. Count is', count)
  count += 1 // NOT likely what you want! Now, try it with count++
}

console.log('Outside of loop. Count is', count)

Another example:

> let num = '2'
undefined
> num++
2
> num
3

// VS using +=

> let num2 = '2'
undefined
> num2 += 1
'21'
> num2
'21'


问:
Where does IntelliJ IDEA store shelf changes on the local drive?
I want to write a small backup script that would take my shelf changes in IntelliJ from my local drive and put them on a network drive. But I can't locate the path to where these are stored on my local drive.

Any ideas?

答:
Instead of giving the fish, here is how to fish:

Find an action item:
⌘ +Shift+A (on a Mac) or Ctrl +Shift+A (on Windows/Linux)

Type "change shelve"

Check the location where it is being stored


问:
Re-sign xcarchive file
A client wants to re-sign the IPA file with their own certificate and since that's pretty easy using this, what I actually need is to re-sign the entire xcarchive so the dSYM's UUID matches the IPA's UUID. Otherwise crash symbolication won't work.
Is it possible to re-sign a xcarchive file?</p>

答:
Update: Xcode 9+, the title of the question is essentially how to re-sign an xarchive file, please note that xarchive is a higher level where ipa file is embedded, the way to deal with this file is to extract them "show packages" then you'll see the actual app on "products/applications/name.app" then, copy the name.app (asssuming this is your app) to another folder, re-sign them using this method , the article is old but works on xcode 9.

Once you've re-signed it you can put it back on the extracted xarchive file earlier, then if you double click it will open on xcode archive and now you can distribute them under your signature.

Also if you run into problems with provisions, just make sure that push notification is enabled /disabled on the app, then change your entitlements.plist. Hope this helps anyone still looking for this kind of issue.

Title: Re-sign xcarchive file


答:
I am not 100% convinced about the forumla, I dont understand why it contains a v[i] and a v[i-1] term. Anyhow, even if correct, in the first iteration (i==0) you are accesing out of bounds of the velocity array: v[i-1]. That is undefined behaviour.

To fix this, either review the formula, does it really contain a v[i-1] term? ..or start the iteration at i=1 (and initialize v[0] and v[1]).

Title: Modeling velocity and height of rocket c++


问:
Ajax not posting Select Option
I'm trying to get the value of the option in my template below called exampleid.  I've followed several examples I found online, but nothing seems to work.  My template below has the ajax and jquery to get the value but when I try to print it returns None.  I've exhausted my resources and my professor doesn't seem to know, he's "looking into it".

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title ="accesslevelid" class="form-control" id="accesslevelid" onchange="accesslevelid" title="">
            <option value="7"> Option 1</option>
            <option value="5"> Option 2</option>
            <option value = "3"> Option 3</option>

</select>
<script>
$(document).ready(function () {
    $('#accesslevelid').on('change', function () {
        var accesslevelid = $(this).val();
        $.ajax({ url: "{% url 'submitted' %}",
                headers: { 'X-CSRFToken': '{{ csrf_token }}' },
                data: {
                  accesslevelid: accesslevelid,
                },
                type: 'POST',
                success: function (result) {
                  alert(result);
                },
              });
      });
  });
</script>
</code>```

my view attempting to retrieve the value of the post.

```<code>exampleidpost = request.POST.get('accesslevelid', False)
print (exampleidpost)
</code>```

My desired result is for the POST to return a 7,5, or 3.

答:
You should add csrf token to you ajax request,
Try this way.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title="accesslevelid" class="form-control" id="accesslevelid" >
    <option value="1"> Option1</option>
    <option value="2"> Option2</option>
    <option value="3"> Option3</option>
</select>

<script>
$(document).ready(function () {
    $('#accesslevelid').on('change', function () {
        var accesslevelid= $(this).val();
        $.ajax({
             url: "{% url 'submitted' %}",
             headers: {'X-CSRFToken': '{{ csrf_token }}'},
             data: {
                 accesslevelid: accesslevelid
             },
             type: 'POST',
             success: function (result) {
               alert(result);
             },
        });
    });
});
</script>
</code>```

And you no longer need a form.

Title: Ajax not posting Select Option

Body:
I'm trying to get the value of the option in my template below called exampleid.  I've followed several examples I found online, but nothing seems to work.  My template below has the ajax and jquery to get the value but when I try to print it returns None.  I've exhausted my resources and my professor doesn't seem to know, he's "looking into it".

<select title ="accesslevelid" class="form-control" id="accesslevelid" onchange="accesslevelid" title="">
            <option value="7"> Option 1</option>
            <option value="5"> Option 2</option>
            <option value = "3"> Option 3</option>

</select>

my view attempting to retrieve the value of the post.

exampleidpost = request.POST.get('accesslevelid', False)
print (exampleidpost)

My desired result is for the POST to return a 7,5, or 3.

Body:
You should add csrf token to you ajax request,
Try this way.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title="accesslevelid" class="form-control" id="accesslevelid" >
    <option value="1"> Option1</option>
    <option value="2"> Option2</option>
    <option value="3"> Option3</option>
</select>

<script>
$(document).ready(function () {
    $('#accesslevelid').on('change', function () {
        var accesslevelid= $(this).val();
        $.ajax({
             url: "{% url 'submitted' %}",
             headers: {'X-CSRFToken': '{{ csrf_token }}'},
             data: {
                 accesslevelid: accesslevelid
             },
             type: 'POST',
             success: function (result) {
               alert(result);
             },
        });
    });
});
</script>

And you no longer need a form.