问:
VBA Insert rows at certain point in data
I have this pivot table I am inserting above my data. The data can be different lengths and so the pivot table and be different lengths. So what I do is put the data a little ways down on the sheet starting at say maybe row 30. Then I insert my pivot table up top. What I do next is I then have some code to delete all of the blank rows in between my data and the pivot table.

```<code>sub foo()
    dim r As Range, rows As Long, i As Long
    Set r = ActiveSheet.Range("A1:Z50")
    rows = r.rows.Count
    For i = rows To 1 Step (-1)
        If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
    Next
End Sub
</code>```

This code will delete all of the blank rows and seems to work correctly. Since that puts everything together, what I want to do then is just put 2 blank rows in between my pivot table and my data but I don't know how to figure out where my pivot table ends or where my data begins.

So I want it to look like that ^^^^ , but right now Row 7 and 8 are not there and my data is pushed up onto my pivot table. Any help is appreciated please!

I was thinking someone like using Rows.Count + 1 or something to find where the pivot table ends. But I don't know how it would determine that since there is data in the row right after. SO maybe I need to find when there is data starting in say Column A then Insert the rows right before that. Thank you in advance for the help!

答:
Try something along those lines:</p>

```<code>Public Sub Answer()
    Dim dataTopRowIndex As Integer
    Dim ptBottomRowIndex As Integer

    With ActiveSheet 'Note: use your worksheet's CodeName here instead, e.g. With Sheet1 (Active[anything], Activate, Select, Selection: evil).
        dataTopRowIndex = .Cells(1, 1).End(xlDown).Row

        With .PivotTables("PivotTable1").TableRange1 'Replace PivotTable1 by your PT's name.
            ptBottomRowIndex = .Row + .Rows.Count - 1
        End With

        If (dataTopRowIndex - ptBottomRowIndex - 1) > 2 Then
            .Range(.Rows(ptBottomRowIndex + 1), .Rows(dataTopRowIndex - 3)).EntireRow.Delete
        End If
    End With
End Sub
</code>```

Body:
I have this pivot table I am inserting above my data. The data can be different lengths and so the pivot table and be different lengths. So what I do is put the data a little ways down on the sheet starting at say maybe row 30. Then I insert my pivot table up top. What I do next is I then have some code to delete all of the blank rows in between my data and the pivot table.

sub foo()
    dim r As Range, rows As Long, i As Long
    Set r = ActiveSheet.Range("A1:Z50")
    rows = r.rows.Count
    For i = rows To 1 Step (-1)
        If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
    Next
End Sub

This code will delete all of the blank rows and seems to work correctly. Since that puts everything together, what I want to do then is just put 2 blank rows in between my pivot table and my data but I don't know how to figure out where my pivot table ends or where my data begins.

So I want it to look like that ^^^^ , but right now Row 7 and 8 are not there and my data is pushed up onto my pivot table. Any help is appreciated please!

I was thinking someone like using Rows.Count + 1 or something to find where the pivot table ends. But I don't know how it would determine that since there is data in the row right after. SO maybe I need to find when there is data starting in say Column A then Insert the rows right before that. Thank you in advance for the help!

Body:
Try something along those lines:

Public Sub Answer()
    Dim dataTopRowIndex As Integer
    Dim ptBottomRowIndex As Integer

    With ActiveSheet 'Note: use your worksheet's CodeName here instead, e.g. With Sheet1 (Active[anything], Activate, Select, Selection: evil).
        dataTopRowIndex = .Cells(1, 1).End(xlDown).Row

        With .PivotTables("PivotTable1").TableRange1 'Replace PivotTable1 by your PT's name.
            ptBottomRowIndex = .Row + .Rows.Count - 1
        End With

        If (dataTopRowIndex - ptBottomRowIndex - 1) > 2 Then
            .Range(.Rows(ptBottomRowIndex + 1), .Rows(dataTopRowIndex - 3)).EntireRow.Delete
        End If
    End With
End Sub


来源: stackexchange

问:
C++ C2466 error
Why we can do something like

```<code>        for(int i = 0; i < destination->imageSize; i=i+3)
        {

            buffer[2] = destination->imageData[i];
            buffer[1] = destination->imageData[i+1];
            buffer[0] = destination->imageData[i+2];
            buffer+=3;
        }
</code>```

but we can not do

```<code>                               char buffer[destination->imageSize];
</code>```

And how to such thing?

Sorry - I am quite new to C++...

BTW: my point is to create a function that would return a char with an image. If I'd use mem copy how do I delete returned value?

答:
You cannot return a local array. Everything you return will need to be free'd by someone.

The size of a local array must be constant. Always. This is because there is no special logic around arrays in C++. You can use some object collection of STL.

ContentLicense: CC BY-SA 3.0

Title: C++ C2466 error

Body:
Why we can do something like

        for(int i = 0; i < destination->imageSize; i=i+3)
        {

            buffer[2] = destination->imageData[i];
            buffer[1] = destination->imageData[i+1];
            buffer[0] = destination->imageData[i+2];
            buffer+=3;
        }

but we can not do

                               char buffer[destination->imageSize];

And how to such thing?

Sorry - I am quite new to C++...

BTW: my point is to create a function that would return a char with an image. If I'd use mem copy how do I delete returned value?

ContentLicense: CC BY-SA 2.5


问:
Distibuting desktop apache piviot application from netbeans
I've developed a desktop application using Apache Pivot for the UI.

Everything runs fine when launched from Netbeans, but when I try to execute the .jar file on it's own I get the following error;

```<code>Exception in thread "main" java.lang.ExceptionInInitializerError
    at **********.Main.main(Main.java:14)
Caused by: java.lang.NumberFormatException: Value out of range. Value:"131" Radix:10
    at java.lang.Byte.parseByte(Unknown Source)
    at java.lang.Byte.parseByte(Unknown Source)
    at org.apache.pivot.util.Version.decode(Version.java:150)
    at org.apache.pivot.wtk.ApplicationContext.<clinit>(ApplicationContext.java:1697)
    ... 1 more
</code>```

It seems like there are arguments Pivot isn't expecting, but this was run with the command;

java -jar {filename}.jar

The folowing enviroment;

Windows 10

Netbeans 8.2

Java version "1.8.0_131"

JDK "1.8.0_60"

Apache Pivot 2.0.4

答: That is a known problem with the "Version" class in Pivot.  This was fixed very recently with version 2.0.5 (you are using the previous 2.0.4 version).  If you update your environment outside of NetBeans you should be good.  My suspicion is that NetBeans somehow gets the latest version but you don't have your class path pointing there outside of the IDE.</p>

Body:
I've developed a desktop application using Apache Pivot for the UI.

Everything runs fine when launched from Netbeans, but when I try to execute the .jar file on it's own I get the following error;

Exception in thread "main" java.lang.ExceptionInInitializerError
    at **********.Main.main(Main.java:14)
Caused by: java.lang.NumberFormatException: Value out of range. Value:"131" Radix:10
    at java.lang.Byte.parseByte(Unknown Source)
    at java.lang.Byte.parseByte(Unknown Source)
    at org.apache.pivot.util.Version.decode(Version.java:150)
    at org.apache.pivot.wtk.ApplicationContext.<clinit>(ApplicationContext.java:1697)
    ... 1 more

It seems like there are arguments Pivot isn't expecting, but this was run with the command;

java -jar {filename}.jar

The folowing enviroment;

Windows 10

Netbeans 8.2

Java version "1.8.0_131"

JDK "1.8.0_60"

Apache Pivot 2.0.4


问:
Outlook AddIn: showing popup while dragging mail in Outlook
I have an outlook addin which shows a popup after sending mail which asks the user whether he/she wants to save the mail.
The problem is that this popup is shown when a mail is added to the sent folder.
So when you send a mail and immediately start dragging a mail to another folder because, e.g. you want to clean up mails, then the popup shows when you're in the middle of dragging which stops the dragging and makes the popup with the question unresponsive to the mouse.

Is there any way around this?

Thanks in advance!

The event for an mail being added to sent folder is set in the Ribbon Load method:

```<code>        private void CodexRibbon_Load(object sender, RibbonUIEventArgs e)
    {
        if (!Globals.ThisAddIn.FirstLoadComplete)
        {
            Messenger.Default.Register<object>(this, ItemSend);
            Globals.ThisAddIn.FirstLoadComplete = true;
        }
    }
</code>```

The question is asked as follows:

```<code>        private void ItemSend(object item)
    {
        if (MessageBox.Show(@" Wilt u de zojuist verzonden e-mail opslaan?", @"Opslaan in Codex", MessageBoxButtons.YesNo) == DialogResult.Yes)
            ShowSaveWindow(item);
    }
</code>```

答:
I don't think there is a way to find out if the control is inside the DoDragDrop Windows API function (you can patch it and have the patched version set some kind of a global flag before entering the original function, but I don't think that will be a good idea in .Net).

Try to display the message box in the Application.ItemSendevent handler, mark the message somehow (user property?), then do the processing in Items.ItemAdd without a message box.

Body:
I have an outlook addin which shows a popup after sending mail which asks the user whether he/she wants to save the mail.
The problem is that this popup is shown when a mail is added to the sent folder.
So when you send a mail and immediately start dragging a mail to another folder because, e.g. you want to clean up mails, then the popup shows when you're in the middle of dragging which stops the dragging and makes the popup with the question unresponsive to the mouse.

Is there any way around this?

Thanks in advance!

The event for an mail being added to sent folder is set in the Ribbon Load method:

        private void CodexRibbon_Load(object sender, RibbonUIEventArgs e)
    {
        if (!Globals.ThisAddIn.FirstLoadComplete)
        {
            Messenger.Default.Register<object>(this, ItemSend);
            Globals.ThisAddIn.FirstLoadComplete = true;
        }
    }

The question is asked as follows:

        private void ItemSend(object item)
    {
        if (MessageBox.Show(@" Wilt u de zojuist verzonden e-mail opslaan?", @"Opslaan in Codex", MessageBoxButtons.YesNo) == DialogResult.Yes)
            ShowSaveWindow(item);
    }


问:
Pandas, how to count the occurance within grouped dataframe and create new column?
How do I get the count of each values within the group using pandas ?

In the below table, I have Group and the Value column, and I want to generate a new column called count, which should contain the total nunmber of occurance of that value within the group.

my df dataframe is as follows (without the count column):

```<code>-------------------------
| Group| Value | Count? |
-------------------------
|   A  |    10 |      3 |
|   A  |    20 |      2 |
|   A  |    10 |      3 |
|   A  |    10 |      3 |
|   A  |    20 |      2 |
|   A  |    30 |      1 |
-------------------------
|   B  |    20 |      3 |
|   B  |    20 |      3 |
|   B  |    20 |      3 |
|   B  |    10 |      1 |
-------------------------
|   C  |    20 |      2 |
|   C  |    20 |      2 |
|   C  |    10 |      2 |
|   C  |    10 |      2 |
-------------------------
</code>```

I can get the counts using this:

```<code>df.groupby(['group','value']).value.count()
</code>```

but this is just to view, I am having difficuly putting the results back to the dataframe as new columns.

Body:
How do I get the count of each values within the group using pandas ?

In the below table, I have Group and the Value column, and I want to generate a new column called count, which should contain the total nunmber of occurance of that value within the group.

my df dataframe is as follows (without the count column):

-------------------------
| Group| Value | Count? |
-------------------------
|   A  |    10 |      3 |
|   A  |    20 |      2 |
|   A  |    10 |      3 |
|   A  |    10 |      3 |
|   A  |    20 |      2 |
|   A  |    30 |      1 |
-------------------------
|   B  |    20 |      3 |
|   B  |    20 |      3 |
|   B  |    20 |      3 |
|   B  |    10 |      1 |
-------------------------
|   C  |    20 |      2 |
|   C  |    20 |      2 |
|   C  |    10 |      2 |
|   C  |    10 |      2 |
-------------------------

I can get the counts using this:

df.groupby(['group','value']).value.count()

but this is just to view, I am having difficuly putting the results back to the dataframe as new columns.

Body:
Try a merge:

df

   Group  Value
0      A     10
1      A     20
2      A     10
3      A     10
4      A     20
5      A     30
6      B     20
7      B     20
8      B     20
9      B     10
10     C     20
11     C     20
12     C     10
13     C     10

g = df.groupby(['Group', 'Value']).Group.count()\
                      .to_frame('Count?').reset_index()

df = df.merge(g)
df

   Group  Value  Count?
0      A     10       3
1      A     10       3
2      A     10       3
3      A     20       2
4      A     20       2
5      A     30       1
6      B     20       3
7      B     20       3
8      B     20       3
9      B     10       1
10     C     20       2
11     C     20       2
12     C     10       2
13     C     10       2


问:
How to count total items in a column, if header name is provided
Sorry! May be I couldn't give a nice question title. I have following sample data. Obviously in case of actual data it will be different and more...

Data Screenshot

Suppose, I put Pen in D17 cell then expected result will be 6 in E17 cell as in table/DataArray Pen column has 6 items. Count should be 4 if I put T-Shirt in D17 cell and so on....

Believe me, I tried combination of many formulas, search on google but no satisfied solution found. I can achieve it by VBA but I am trying to solve it by using excel formulas only.

答:
This will count non-blanks provided user knows the maximum number of rows to set the Height of the OFFSET() function:

```<code>=SUM((OFFSET(B3,1,MATCH(D16,B3:J3,0)-1,10,1)<>"")*1)
</code>```

to be executed with Ctrl+Shift+Enter. The height set in this formula is 10.

Body:
This will count non-blanks provided user knows the maximum number of rows to set the Height of the OFFSET() function:

=SUM((OFFSET(B3,1,MATCH(D16,B3:J3,0)-1,10,1)<>"")*1)

to be executed with Ctrl+Shift+Enter. The height set in this formula is 10.


问:
MySQL - On delete cascade constraint doesn't do it's job properly
I have a couple of tables:

users is full of users.

item is full of items.

item can have multiple second_items.

users are able to have second_items via table users_items.

When I delete a item all second_item and users_items should be removed too. So I setup some constraints that should delete child table records. But it leaves the record in users_items.

Here is my MySQL queries:

```<code>CREATE TABLE `item` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(63) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `item` (`id`, `name`) VALUES (1, 'test');

CREATE TABLE `second_item` (
  `id` int(10) UNSIGNED NOT NULL,
  `item_id` int(10) UNSIGNED DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `second_item` (`id`, `item_id`, `name`) VALUES
(1, 1, 'test');

CREATE TABLE `users` (
  `id` int(10) UNSIGNED NOT NULL,
  `email` varchar(200) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `email`, `password`) VALUES (1, 'test', 'test');

CREATE TABLE `users_items` (
  `id` int(10) UNSIGNED NOT NULL,
  `user_id` int(10) UNSIGNED DEFAULT NULL,
  `item_id` int(10) UNSIGNED DEFAULT NULL,
  `item_second_id` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users_items` (`id`, `user_id`, `item_id`, `item_second_id`) VALUES (1, 1, 1, 1);

ALTER TABLE `second_item`
  ADD PRIMARY KEY (`id`),
  ADD KEY `item_id` (`item_id`);

ALTER TABLE `item` ADD PRIMARY KEY (`id`);

ALTER TABLE `users` ADD PRIMARY KEY (`id`);

ALTER TABLE `users_items`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `item_id` (`item_id`),
  ADD KEY `item_second_id` (`item_second_id`);

ALTER TABLE `second_item`
  ADD CONSTRAINT `constraint1` FOREIGN KEY (`item_id`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `users_items`
  ADD CONSTRAINT `constraint2` FOREIGN KEY (`item_id`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `constraint3` FOREIGN KEY (`item_second_id`) REFERENCES `second_item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  ADD CONSTRAINT `constraint4` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
</code>```

I try to do the following delete query, but it leaves a record in users_items:

```<code>DELETE FROM `item` WHERE `item`.`id` = 1;
</code>```

This "bug" happens on:

WAMP (Server version: 5.7.16 - MySQL Community Server (GPL))

UBUNTU (5.7.20-0ubuntu0.16.04.1 - (Ubuntu))

EDITED:

The bug is caused by the order you add constraints:

```<code>ALTER TABLE `users_items`
  ADD CONSTRAINT `constraint1` FOREIGN KEY (`item_id`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `constraint2` FOREIGN KEY (`item_second_id`) REFERENCES `second_item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  ADD CONSTRAINT `constraint3` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `second_item`
  ADD CONSTRAINT `constraint4` FOREIGN KEY (`item_id`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
</code>```

This way it is fixed.

答:
I had indeed the same results as you had.
Also found the fix ;)

Change the order of your constraints in your SQL code. This will solve your problem.

I think this is a weird MySQL Bug

Body:
I have a couple of tables:

users is full of users.

item is full of items.

item can have multiple second_items.

users are able to have second_items via table users_items.

When I delete a item all second_item and users_items should be removed too. So I setup some constraints that should delete child table records. But it leaves the record in users_items.

Here is my MySQL queries:

CREATE TABLE `item` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(63) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `item` (`id`, `name`) VALUES (1, 'test');

CREATE TABLE `second_item` (
  `id` int(10) UNSIGNED NOT NULL,
  `item_id` int(10) UNSIGNED DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `second_item` (`id`, `item_id`, `name`) VALUES
(1, 1, 'test');

CREATE TABLE `users` (
  `id` int(10) UNSIGNED NOT NULL,
  `email` varchar(200) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `email`, `password`) VALUES (1, 'test', 'test');

CREATE TABLE `users_items` (
  `id` int(10) UNSIGNED NOT NULL,
  `user_id` int(10) UNSIGNED DEFAULT NULL,
  `item_id` int(10) UNSIGNED DEFAULT NULL,
  `item_second_id` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users_items` (`id`, `user_id`, `item_id`, `item_second_id`) VALUES (1, 1, 1, 1);

ALTER TABLE `second_item`
  ADD PRIMARY KEY (`id`),
  ADD KEY `item_id` (`item_id`);

ALTER TABLE `item` ADD PRIMARY KEY (`id`);

ALTER TABLE `users` ADD PRIMARY KEY (`id`);

ALTER TABLE `users_items`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `item_id` (`item_id`),
  ADD KEY `item_second_id` (`item_second_id`);

ALTER TABLE `second_item`
  ADD CONSTRAINT `constraint1` FOREIGN KEY (`item_id`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `users_items`
  ADD CONSTRAINT `constraint2` FOREIGN KEY (`item_id`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `constraint3` FOREIGN KEY (`item_second_id`) REFERENCES `second_item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  ADD CONSTRAINT `constraint4` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

I try to do the following delete query, but it leaves a record in users_items:

DELETE FROM `item` WHERE `item`.`id` = 1;

This "bug" happens on:

WAMP (Server version: 5.7.16 - MySQL Community Server (GPL))

UBUNTU (5.7.20-0ubuntu0.16.04.1 - (Ubuntu))

EDITED:

The bug is caused by the order you add constraints:

ALTER TABLE `users_items`
  ADD CONSTRAINT `constraint1` FOREIGN KEY (`item_id`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `constraint2` FOREIGN KEY (`item_second_id`) REFERENCES `second_item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  ADD CONSTRAINT `constraint3` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `second_item`
  ADD CONSTRAINT `constraint4` FOREIGN KEY (`item_id`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

This way it is fixed.


答:
I have to ask, why do you think they're at all related?  If you couldn't index an array by runtime variable, it'd be pretty useless for there to even be arrays.  Declaring a variable of a size governed by a runtime variable is entirely different and requires fundamental changes to the way the compiler manages automatic memory.

Which is why you can't do it in C++.  This may change, but for now you can't.

If you really need a variable sized array you need to allocate one dynamically.  You can do it the hard, f'd up way (char * buff = new char[size]...delete [] buff;), or you can do it the easy, safer way (std::vector<char> buff(size)).  Your choice.  You can't build it "on the stack" though.

Title: C++ C2466 error


问:
navigation bar centering an element next to floated right elements
 of my navigation bar.

I'm trying to center a link in the middle of my navbar. I've been looking around for a solution but it just breaks my navbar, i.e. moves the link by a few pixels to the right. I know if I put display: block it will center it but my items on the right get bumped off. This is what I have so far:

.navbar > a.favmovies-title {
  font-family: Impact, Haettenschweiler, "Franklin Gothic Bold", Charcoal, "Helvetica Inserat", "Bitstream Vera Sans Bold", "Arial Black", "sans serif";
  font-size: 155%;
  width: 25%;
  float: none;
  text-align: center;
  text-decoration: none;
  background-color: #FF6347;
  color: orange;
}

.navbar {
  height: 100px;
  overflow: hidden;
  background-color: #FF6347;
  padding: 1%;
  position: fixed;
  width: 100%;
}

.navbar > ul > li.right {
  float: right;
}

.navbar > ul > li > a.userlogin {
  font-size: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar">
  FavMovies
  <ul>
    <li class="right">Login<span class = "small_font_size"></span></li>
    <li class="right">Signup</li>
    <input class="right" id="Search-Bar" type="text">
    <li class="right" id="Search">search <img src="/assets/icons/searchicon.fw.png" alt="Search" id="SearchIcon"></li>
  </ul>
</div></code>```

I've been trying some display flex properties and transformations but it's not working. The aligned-content property didn't help me either. Appreciate any tips.

答:
You could center the logo normally by using text-align: center on the .navbar and make the floating ul element position: absolute to make this happen.

```<code>.navbar {
  text-align: center;
}

.navbar > ul {
  position: absolute;
  top: 0;
  right: 0;
}
</code>```

Body:
 of my navigation bar.

I'm trying to center a link in the middle of my navbar. I've been looking around for a solution but it just breaks my navbar, i.e. moves the link by a few pixels to the right. I know if I put display: block it will center it but my items on the right get bumped off. This is what I have so far:

.navbar > a.favmovies-title {
  font-family: Impact, Haettenschweiler, "Franklin Gothic Bold", Charcoal, "Helvetica Inserat", "Bitstream Vera Sans Bold", "Arial Black", "sans serif";
  font-size: 155%;
  width: 25%;
  float: none;
  text-align: center;
  text-decoration: none;
  background-color: #FF6347;
  color: orange;
}

.navbar {
  height: 100px;
  overflow: hidden;
  background-color: #FF6347;
  padding: 1%;
  position: fixed;
  width: 100%;
}

.navbar > ul > li.right {
  float: right;
}

.navbar > ul > li > a.userlogin {
  font-size: 50%;
}

  FavMovies

Login

Signup

    <input class="right" id="Search-Bar" type="text">

search

I've been trying some display flex properties and transformations but it's not working. The aligned-content property didn't help me either. Appreciate any tips.

Body:
You could center the logo normally by using text-align: center on the .navbar and make the floating ul element position: absolute to make this happen.

.navbar {
  text-align: center;
}

.navbar > ul {
  position: absolute;
  top: 0;
  right: 0;
}


答:
You could try absolutely positioning your logo in the middle of your navbar.

Try adding this to your text logo styles:

```<code>.navbar > a.favmovies-title {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
}
</code>```

Title: navigation bar centering an element next to floated right elements

Body:
You could try absolutely positioning your logo in the middle of your navbar.

Try adding this to your text logo styles:

.navbar > a.favmovies-title {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
}


问:
Google Datastore query filter for multiple values for same property
I have a query I wish to run on google Datastore that is intended to retrieve data from multiple devices. However, I couldn't find anywhere in the documentation that would allow me to get data from e.g. device-1 or device-2 or device-3, i.e. only 1 property name can be set. Is this a Datastore limitation? Or am I just missing something that I don't know about?

Based on the NodeJS client library, the query might look something like the below filter criteria:

```<code>var query = datastore.createQuery('data')
              .filter('device_id', 1)
              .filter('device_id', 2)
              .filter('device_id', 3);
</code>```

Otherwise, I might have to run separate queries for the various devices, which doesn't seem like a very elegant solution, especially if there are a lot of devices to simultaneously run queries on.

Any suggestions for the Datastore API or alternative approaches are welcome!

答:
Yes, this would be an OR operation which is one of the Restrictions on queries (emphasis mine):

The nature of the index query mechanism imposes certain restrictions
  on what a query can do. Cloud Datastore queries do not support
  substring matches, case-insensitive matches, or so-called full-text
  search. The NOT, OR, and != operators are not natively
  supported, but some client libraries may add support on top of Cloud
  Datastore. Additionally:

Body:
I have a query I wish to run on google Datastore that is intended to retrieve data from multiple devices. However, I couldn't find anywhere in the documentation that would allow me to get data from e.g. device-1 or device-2 or device-3, i.e. only 1 property name can be set. Is this a Datastore limitation? Or am I just missing something that I don't know about?

Based on the NodeJS client library, the query might look something like the below filter criteria:

var query = datastore.createQuery('data')
              .filter('device_id', 1)
              .filter('device_id', 2)
              .filter('device_id', 3);

Otherwise, I might have to run separate queries for the various devices, which doesn't seem like a very elegant solution, especially if there are a lot of devices to simultaneously run queries on.

Any suggestions for the Datastore API or alternative approaches are welcome!


问:
reading/writing xmp metadatas on pdf files through pypdf
I can read xmp metadatas through pypdf with this code:

from pypdf import PdfReader

a = PdfReader("file.pdf")
b = a.xmp_metadata
c = b.pdf_keywords
```

But is this the best way?

And if I don't use the pdf_keywords property?

Is there any way to set these metadatas with pypdf?

答: As far as I can see, this is the best way to do so - and there is no way to change the metadata with pyPDF.</p>

OwnerDisplayName: GIANCARLO

ContentLicense: CC BY-SA 4.0

Body:
I can read xmp metadatas through pypdf with this code:

from pypdf import PdfReader

a = PdfReader("file.pdf")
b = a.xmp_metadata
c = b.pdf_keywords

But is this the best way?

And if I don't use the pdf_keywords property?

Is there any way to set these metadatas with pypdf?

OwnerDisplayName: kylebrooks


问:
(Javascript - Arrays) Get most left and most right connected character
I have an array (2d-matrix) and I'd like to get the x/y values for the

most left & top connected '1'-character

most right & bottom connected '1'-character

EDIT 2.0:

I call my function with the parameters x/y, that are the coordinates of my start-'1'-character.

```<code>10001
00001
11111
01110   --> (x: 1, y: 3)
</code>```

And my function checks the column above & and the column right so if there is a character '1' it counts x or y (wherever the column has been found) plus 1.

My function starts at a specific point (e.g. y: 2, x: 0)

```<code>var array = [
 '00000',
 '01111',       --> get position of the most top & right '1'-character (x: 4, y: 1)
 '11000',
 '00000'
]
</code>```

This is the function to get the top-right end of '1'-characters:

var array = [
 '00000',
 '01111',
 '11000',
 '00000'
]

  Array.prototype.get_top_right = function(x_pos, y_pos) {
    var matrix = this, y1= y_pos;
    for (var x1 = x_pos; x1 < this[0].length; x1++) {
      try {
        if (matrix[(y1-1)][x1] == '1') y1--;
        else if (matrix[y1][(x1+1)] != '1') break;
      } catch(e) {}
    }; return [x1,y1]
 }

 var result=array.get_top_right(0,2)

 console.log(result)```
</div>
</div>
</p>

<p>Ok. The function above seems to work fine, but now I'd like to turn around the process to get the last bottom-left connected '1'-character of my array / 2D-matrix.</p>

```var array = [
  '00000',
  '01111',
  '11000', --> get position of the most bottom & left '1'-character (x: 0, y: 2)
  '00000'
]
```

<p>I have no clue how to edit the function above to get the left&bottom match as result instead of the most right&top match like you can see above. </p>

<blockquote>
  <p>Edit 1.0 My function I've coded till yet is not working but looks like this:</p>
</blockquote>

```Array.prototype.get_bottom_left = function(x_pos, y_pos) {
    var matrix = this, y2= y_pos;
    for (var x2 = x_pos; x2 > 0; x2--) {
      try {
        if (matrix[(y2+1)][x2] == '1') y2++;
        if (matrix[y2][(x2-1)] != '1') break;
      } catch(e) {}
    }; return [x2,y2]
 }
```

<blockquote>
  <p>Using this function above and the error_array below to get the bottom left connected character of the array will lead to a browser crash. Nice!</p>
</blockquote>

```  var error_array = [
    '000000',
    '000011',
    '111110',
    '111111'
  ]
```

However, I hope somebody can help me updating my function...

Thanks a million in advance,

Greetings - hans.

答:
I created two versions of get_bottom_left method:

bottom_left_up which traversing from (x, y) point to the left and to the up

bottom_left_down which traversing from (x, y) point to the right and to the down.

Here's the implementation:

```<code>Array.prototype.bottom_left_up = function(x, y) {
  if(this[y][x] === '0') {
    return;
  }
  while(y >= 0) {
    while(--x >= 0) {
      if(this[y][x] === '0') {
        return [x + 1, y];
      }
    }
    if(--y === -1 || this[y][this[y].length - 1] === '0') {
      return [0, y + 1];
    }
    x = this[y].length;
  }
};

Array.prototype.bottom_left_down = function(x, y) {
  if(this[y][x] === '0') {
    return;
  }
  while(y < this.length) {
    if(this[y].indexOf('0', x) !== -1) {
      return [x, y];
    }
    if(++y === this.length || this[y][0] === '0') {
      return [x, y - 1];
    }
    x = 0;
  }
};
</code>```

You see, there are no out-of-range protections, it could be added with no problem separately. Let's test the logic:

```<code>var array = [
 '00000',
 '01111',
 '11000',
 '00000'
];
console.log(array.bottom_left_up(2, 1)); // [1, 1]
console.log(array.bottom_left_down(2, 1)); // [0, 2]

var array2 = [
  '000000',
  '000011',
  '111110',
  '111111'
];
console.log(array2.bottom_left_up(3, 3)); // [0, 3]
console.log(array2.bottom_left_down(3, 3)); // [3, 3]
</code>```

Regarding methods protection, I would not use try-catch, I would suggest something like:

```<code>function(x, y) {
  x = parseInt(x, 10);
  y = parseInt(y, 10);
  if(!this.length || isNaN(x) || isNaN(y) || x < 0 || y < 0 || x >= this.length || y >= this[0].length) {
    return;
  }
  // ...
}
</code>```

So you will get 'undefined' in 3 cases: empty array, bad params, not found.

Body:
I have an array (2d-matrix) and I'd like to get the x/y values for the

most left & top connected '1'-character

most right & bottom connected '1'-character

EDIT 2.0:

I call my function with the parameters x/y, that are the coordinates of my start-'1'-character.

10001
00001
11111
01110   --> (x: 1, y: 3)

And my function checks the column above & and the column right so if there is a character '1' it counts x or y (wherever the column has been found) plus 1.

My function starts at a specific point (e.g. y: 2, x: 0)

var array = [
 '00000',
 '01111',       --> get position of the most top & right '1'-character (x: 4, y: 1)
 '11000',
 '00000'
]

This is the function to get the top-right end of '1'-characters:

var array = [
 '00000',
 '01111',
 '11000',
 '00000'
]

  Array.prototype.get_top_right = function(x_pos, y_pos) {
    var matrix = this, y1= y_pos;
    for (var x1 = x_pos; x1 < this[0].length; x1++) {
      try {
        if (matrix[(y1-1)][x1] == '1') y1--;
        else if (matrix[y1][(x1+1)] != '1') break;
      } catch(e) {}
    }; return [x1,y1]
 }

 var result=array.get_top_right(0,2)

 console.log(result)

Ok. The function above seems to work fine, but now I'd like to turn around the process to get the last bottom-left connected '1'-character of my array / 2D-matrix.

var array = [
  '00000',
  '01111',
  '11000', --> get position of the most bottom & left '1'-character (x: 0, y: 2)
  '00000'
]

I have no clue how to edit the function above to get the left&bottom match as result instead of the most right&top match like you can see above.

Edit 1.0 My function I've coded till yet is not working but looks like this:

Array.prototype.get_bottom_left = function(x_pos, y_pos) {
    var matrix = this, y2= y_pos;
    for (var x2 = x_pos; x2 > 0; x2--) {
      try {
        if (matrix[(y2+1)][x2] == '1') y2++;
        if (matrix[y2][(x2-1)] != '1') break;
      } catch(e) {}
    }; return [x2,y2]
 }

Using this function above and the error_array below to get the bottom left connected character of the array will lead to a browser crash. Nice!

  var error_array = [
    '000000',
    '000011',
    '111110',
    '111111'
  ]

However, I hope somebody can help me updating my function...

Thanks a million in advance,

Greetings - hans.

Body:
I created two versions of get_bottom_left method:

bottom_left_up which traversing from (x, y) point to the left and to the up

bottom_left_down which traversing from (x, y) point to the right and to the down.

Here's the implementation:

Array.prototype.bottom_left_up = function(x, y) {
  if(this[y][x] === '0') {
    return;
  }
  while(y >= 0) {
    while(--x >= 0) {
      if(this[y][x] === '0') {
        return [x + 1, y];
      }
    }
    if(--y === -1 || this[y][this[y].length - 1] === '0') {
      return [0, y + 1];
    }
    x = this[y].length;
  }
};

Array.prototype.bottom_left_down = function(x, y) {
  if(this[y][x] === '0') {
    return;
  }
  while(y < this.length) {
    if(this[y].indexOf('0', x) !== -1) {
      return [x, y];
    }
    if(++y === this.length || this[y][0] === '0') {
      return [x, y - 1];
    }
    x = 0;
  }
};

You see, there are no out-of-range protections, it could be added with no problem separately. Let's test the logic:

var array = [
 '00000',
 '01111',
 '11000',
 '00000'
];
console.log(array.bottom_left_up(2, 1)); // [1, 1]
console.log(array.bottom_left_down(2, 1)); // [0, 2]

var array2 = [
  '000000',
  '000011',
  '111110',
  '111111'
];
console.log(array2.bottom_left_up(3, 3)); // [0, 3]
console.log(array2.bottom_left_down(3, 3)); // [3, 3]

Regarding methods protection, I would not use try-catch, I would suggest something like:

function(x, y) {
  x = parseInt(x, 10);
  y = parseInt(y, 10);
  if(!this.length || isNaN(x) || isNaN(y) || x < 0 || y < 0 || x >= this.length || y >= this[0].length) {
    return;
  }
  // ...
}

So you will get 'undefined' in 3 cases: empty array, bad params, not found.


问:
javascript - what is the effect of applying prototype to functions that are not constructors?
So, I know how to apply the prototype property to modify constructors that will effectively affect instances. Theoretically, the prototype should work on a normal function as well (though not necessarily have an effect if it's not a prototype of a certain instance). So I tried the code (createNewFunction is a normal function that's not a constructor)(full code is at the end)

```<code>createNewPerson.prototype.xx = (function() { //alerts hello
            alert("hello");
        })();
</code>```

I'm wondering what this actually does as to how xx is appended to the function. Is it stored as variable xx that is equal to the anon function? Or is stored as this.xx = function? How will this compare to storing the following code:

```<code>createNewPerson.xx = (function() { //alerts hello
        alert("hello");
    })();
</code>```

This also makes me wonder as to how this this line will be stored(As in if it will be stored as var mm = 3, or it won't append at all?):

```<code>createNewPerson.mm = 3;
</code>```

Full code for reference:

function createNewPerson(name) {
  var obj = {};
  obj.name = name;
  obj.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
  return obj;
}

createNewPerson.mm = 3; //does nothing when i tested it

createNewPerson.xx = (function() { //alerts hello
  alert("hello");
})();
createNewPerson.prototype.xx = (function() { //alerts hello
  alert("hello");
})();
var salva = createNewPerson('Salva');```

答:
Functions are objects and can have properties.

function createNewPerson(name) {
  var obj = {};
  obj.name = name;
  obj.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
  return obj;
}

createNewPerson.mm = 3; //assigns 3 to createNewPerson property mm

createNewPerson.xx = (function() { //assigns result of anonymous function to property xx
  alert("hello");
})();
createNewPerson.prototype.xx = (function() { //assigns result of function to xx
  alert("hello");
})();
var salva = createNewPerson('Salva');//creates new generic object

alert(// these are values of the function, not the object salva
    'mm: ' + createNewPerson.mm +
    '\nxx: ' + createNewPerson.xx
);

//To add a function to a function:

createNewPerson.foo = function(){
    alert('I\'m just a function hanging off another function. I know nothing about the function I hang on.');
};
alert('the above code didn\'t alert, but we can alert it now');
createNewPerson.foo();```
</div>
</div>
</p>

<p>Attaching new members to a function does not give them special access to the function.</p>

<p><strong>UPDATE:</strong> because when you call createNewPerson('Salva'); the context is "window", the only way to get at mm is by referencing createNewPerson.mm;</p>

<p>If you're looking for something shorter like "this.mm", you can update your code to bind the context. I've added updated code to reflect this.</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-js lang-js prettyprint-override"><code>var createNewPerson = (function (name) {
  alert(this.prior);
  alert(this.after);
  var obj = { name: name };
  return obj;
});

createNewPerson.prior = 'prior to binding';

createNewPerson=createNewPerson.bind(createNewPerson); //this makes the createNewPerson its own context when it is called.

createNewPerson.after = 'after to binding';//property is hung from the function instance created with "bind"
var person = createNewPerson('salva');</code>```

Body:
So, I know how to apply the prototype property to modify constructors that will effectively affect instances. Theoretically, the prototype should work on a normal function as well (though not necessarily have an effect if it's not a prototype of a certain instance). So I tried the code (createNewFunction is a normal function that's not a constructor)(full code is at the end)

createNewPerson.prototype.xx = (function() { //alerts hello
            alert("hello");
        })();

I'm wondering what this actually does as to how xx is appended to the function. Is it stored as variable xx that is equal to the anon function? Or is stored as this.xx = function? How will this compare to storing the following code:

createNewPerson.xx = (function() { //alerts hello
        alert("hello");
    })();

This also makes me wonder as to how this this line will be stored(As in if it will be stored as var mm = 3, or it won't append at all?):

createNewPerson.mm = 3;

Full code for reference:

function createNewPerson(name) {
  var obj = {};
  obj.name = name;
  obj.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
  return obj;
}

createNewPerson.mm = 3; //does nothing when i tested it

createNewPerson.xx = (function() { //alerts hello
  alert("hello");
})();
createNewPerson.prototype.xx = (function() { //alerts hello
  alert("hello");
})();
var salva = createNewPerson('Salva');

Body:
Functions are objects and can have properties.

function createNewPerson(name) {
  var obj = {};
  obj.name = name;
  obj.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
  return obj;
}

createNewPerson.mm = 3; //assigns 3 to createNewPerson property mm

createNewPerson.xx = (function() { //assigns result of anonymous function to property xx
  alert("hello");
})();
createNewPerson.prototype.xx = (function() { //assigns result of function to xx
  alert("hello");
})();
var salva = createNewPerson('Salva');//creates new generic object

alert(// these are values of the function, not the object salva
    'mm: ' + createNewPerson.mm +
    '\nxx: ' + createNewPerson.xx
);

//To add a function to a function:

createNewPerson.foo = function(){
    alert('I\'m just a function hanging off another function. I know nothing about the function I hang on.');
};
alert('the above code didn\'t alert, but we can alert it now');
createNewPerson.foo();

Attaching new members to a function does not give them special access to the function.

UPDATE: because when you call createNewPerson('Salva'); the context is "window", the only way to get at mm is by referencing createNewPerson.mm;

If you're looking for something shorter like "this.mm", you can update your code to bind the context. I've added updated code to reflect this.

var createNewPerson = (function (name) {
  alert(this.prior);
  alert(this.after);
  var obj = { name: name };
  return obj;
});

createNewPerson.prior = 'prior to binding';

createNewPerson=createNewPerson.bind(createNewPerson); //this makes the createNewPerson its own context when it is called.

createNewPerson.after = 'after to binding';//property is hung from the function instance created with "bind"
var person = createNewPerson('salva');


问:
Moving texts from one div to another while also changing its background color, font and text color
I've been trying to move the input texts from the first page to the second page with the help of jquery, while also trying making sure that the changes chosen in the first page only show up to the second page after the print button has been pressed but I haven't gotten it to work and I'm wondering what it is that I'm doing wrong.

document.getElementById("page2").style.display = 'none'; // Hide div with name 'page2'
document.getElementById("reset").addEventListener("click", function() {
  // body...
});
document.getElementById("byt1").addEventListener("click", function() {
  document.getElementById("page1").style.display = 'none'; // Hide div with name 'page1'
  document.getElementById("page2").style.display = 'block'; // Show div with name 'page2'
  function changecolor(color) {
    var color = document.getElementById("select_bgcolor").value;
    document.getElementById.style.backgroundColor = select_bgcolor.value;
  }
  // Move text from input field in page 1 to presenting area in page 2
  document.getElementById("area1").innerHTML = document.getElementById("txt1").value;
  document.getElementById("area3").innerHTML = document.getElementById("txt2").value;
  document.getElementById("area2").innerHTML = document.getElementById("txt3").value;
  document.getElementById("area4").innerHTML = document.getElementById("txt4").value;
  document.getElementById("area5").innerHTML = document.getElementById("txt5").value;
  document.getElementById("area6").innerHTML = document.getElementById("txt6").value;
});
document.getElementById("byt2").addEventListener("click", function() {
  document.getElementById("page1").style.display = 'block';
  document.getElementById("page2").style.display = 'none';
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page1">
  <h2>Order your business card here:</h2>
  <p>
    Company... <input type="text" id="txt1" />
  </p>
  <p>
    Last name... <input type="text" id="txt2" />
  </p>
  <p>
    First name... <input type="text" id="txt3" />
  </p>
  <p>
    Titel... <input type="text" id="txt4" />
  </p>
  <p>
    Telefon... <input type="text" id="txt5" />
  </p>
  <p>
    E-mail... <input type="text" id="txt6" />
  </p>
  <form>
    Background color <select id="select_bgcolor" onchange="byt1">
        <option value="lightblue">Light blue</option>
        <option value="lighyellow">Light yellow</option>
        <option value="white">White</option>
        <option value="turquoise">Turquoise</option>
      </select>
  </form>
  </p>
  <p>
    <form>
      Text color <select id="select_txtcolor" onchange="byt1">
        <option value="black">Black</option>
        <option value="blue">Blue</option>
        <option value="red">Red</option>
        <option value="darkgreen">Dark green</option>
      </select>
    </form>
  </p>
  <p>
    <form>
      font <select id="select_txtfont" onchange="byt1">
        <option value="verdana">Verdana</option>
        <option value="Arial">Arial</option>
        <option value="tahoma">Tahoma</option>
        <option value="impact">Impact</option>
      </select>
    </form>
  </p>
  <p>
    <input type="button" id="reset" value="Reset" />
    <input type="button" id="byt1" value="Print" />
  </p>
</div>

<div id="page2">
  <h2>Page 2</h2>

  <p id="area"></p>
  <input type="button" id="byt2" value="Back to page 1" />
</div></code>```

答:
I have restructure your code. This will help you to get expected OP.

var reset = document.getElementById("reset");
var print = document.getElementById("byt1");
var back = document.getElementById("byt2");
var color = document.getElementById("select_bgcolor").value;
var font = document.getElementById("select_txtcolor").value;
var tcolor =  document.getElementById("select_txtfont").value;

var cssvalue = [];
reset.addEventListener("click", function(){
 document.getElementById("form").reset();
 });

print.addEventListener("click", function(){
 var printtext = document.querySelector("#printarea");
 cssvalue.push(color,font,tcolor);
 document.getElementById("page2").appendChild(printtext);
 document.getElementById("page2").style.display = "block";
 document.getElementById("page1").style.display = "none";
 document.getElementById("page2").style.backgroundColor = cssvalue[0];
 document.getElementById("page2").style.color = cssvalue[1];
 document.getElementById("page2").style.fontFamily = cssvalue[2];

 });

back.addEventListener("click", function(){
 var printtext = document.querySelector("#printarea");
 document.getElementById("page1").prepend(printtext);
 document.getElementById("page1").style.display = "block";
 document.getElementById("page2").style.display = "none";
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#page2{
 display:none;
}</code>```

<form id="form" name="style">

Order your business card here:

    Company... <input type="text" id="txt1" />

    Last name... <input type="text" id="txt2" />

    First name... <input type="text" id="txt3" />

    Titel... <input type="text" id="txt4" />

    Telefon... <input type="text" id="txt5" />

    E-mail... <input type="text" id="txt6" />

  Background color <select id="select_bgcolor" onchange="byt1">
    <option value="lightblue">Light blue</option>
    <option value="lighyellow">Light yellow</option>
    <option value="white">White</option>
    <option value="turquoise">Turquoise</option>
  </select>

  Text color <select id="select_txtcolor" onchange="byt1">
    <option value="black">Black</option>
    <option value="blue">Blue</option>
    <option value="red">Red</option>
    <option value="darkgreen">Dark green</option>
  </select>

  font <select id="select_txtfont" onchange="byt1">
    <option value="verdana">Verdana</option>
    <option value="Arial">Arial</option>
    <option value="tahoma">Tahoma</option>
    <option value="impact">Impact</option>
  </select>
  </form>

    <input type="button" id="reset" value="Reset" />
      <input type="button" id="byt1" value="Print" />

Page 2

  <input type="button" id="byt2" value="Back to page 1" />

```

Body:
I've been trying to move the input texts from the first page to the second page with the help of jquery, while also trying making sure that the changes chosen in the first page only show up to the second page after the print button has been pressed but I haven't gotten it to work and I'm wondering what it is that I'm doing wrong.

document.getElementById("page2").style.display = 'none'; // Hide div with name 'page2'
document.getElementById("reset").addEventListener("click", function() {
  // body...
});
document.getElementById("byt1").addEventListener("click", function() {
  document.getElementById("page1").style.display = 'none'; // Hide div with name 'page1'
  document.getElementById("page2").style.display = 'block'; // Show div with name 'page2'
  function changecolor(color) {
    var color = document.getElementById("select_bgcolor").value;
    document.getElementById.style.backgroundColor = select_bgcolor.value;
  }
  // Move text from input field in page 1 to presenting area in page 2
  document.getElementById("area1").innerHTML = document.getElementById("txt1").value;
  document.getElementById("area3").innerHTML = document.getElementById("txt2").value;
  document.getElementById("area2").innerHTML = document.getElementById("txt3").value;
  document.getElementById("area4").innerHTML = document.getElementById("txt4").value;
  document.getElementById("area5").innerHTML = document.getElementById("txt5").value;
  document.getElementById("area6").innerHTML = document.getElementById("txt6").value;
});
document.getElementById("byt2").addEventListener("click", function() {
  document.getElementById("page1").style.display = 'block';
  document.getElementById("page2").style.display = 'none';
});

Order your business card here:

    Company... <input type="text" id="txt1" />

    Last name... <input type="text" id="txt2" />

    First name... <input type="text" id="txt3" />

    Titel... <input type="text" id="txt4" />

    Telefon... <input type="text" id="txt5" />

    E-mail... <input type="text" id="txt6" />

  <form>
    Background color <select id="select_bgcolor" onchange="byt1">
        <option value="lightblue">Light blue</option>
        <option value="lighyellow">Light yellow</option>
        <option value="white">White</option>
        <option value="turquoise">Turquoise</option>
      </select>
  </form>

    <form>
      Text color <select id="select_txtcolor" onchange="byt1">
        <option value="black">Black</option>
        <option value="blue">Blue</option>
        <option value="red">Red</option>
        <option value="darkgreen">Dark green</option>
      </select>
    </form>

    <form>
      font <select id="select_txtfont" onchange="byt1">
        <option value="verdana">Verdana</option>
        <option value="Arial">Arial</option>
        <option value="tahoma">Tahoma</option>
        <option value="impact">Impact</option>
      </select>
    </form>

    <input type="button" id="reset" value="Reset" />
    <input type="button" id="byt1" value="Print" />

Page 2

  <input type="button" id="byt2" value="Back to page 1" />

Body:
I have restructure your code. This will help you to get expected OP.

var reset = document.getElementById("reset");
var print = document.getElementById("byt1");
var back = document.getElementById("byt2");
var color = document.getElementById("select_bgcolor").value;
var font = document.getElementById("select_txtcolor").value;
var tcolor =  document.getElementById("select_txtfont").value;

var cssvalue = [];
reset.addEventListener("click", function(){
 document.getElementById("form").reset();
 });

print.addEventListener("click", function(){
 var printtext = document.querySelector("#printarea");
 cssvalue.push(color,font,tcolor);
 document.getElementById("page2").appendChild(printtext);
 document.getElementById("page2").style.display = "block";
 document.getElementById("page1").style.display = "none";
 document.getElementById("page2").style.backgroundColor = cssvalue[0];
 document.getElementById("page2").style.color = cssvalue[1];
 document.getElementById("page2").style.fontFamily = cssvalue[2];

 });

back.addEventListener("click", function(){
 var printtext = document.querySelector("#printarea");
 document.getElementById("page1").prepend(printtext);
 document.getElementById("page1").style.display = "block";
 document.getElementById("page2").style.display = "none";
});

#page2{
 display:none;
}

<div id="page1">
<form id="form" name="style">
<div id="printarea">
  <h2>Order your business card here:</h2>
  <p>
    Company... <input type="text" id="txt1" />
  </p>
  <p>
    Last name... <input type="text" id="txt2" />
  </p>
  <p>
    First name... <input type="text" id="txt3" />
  </p>
  <p>
    Titel... <input type="text" id="txt4" />
  </p>
  <p>
    Telefon... <input type="text" id="txt5" />
  </p>
  <p>
    E-mail... <input type="text" id="txt6" />
  </p>
 </div>
  Background color <select id="select_bgcolor" onchange="byt1">
    <option value="lightblue">Light blue</option>
    <option value="lighyellow">Light yellow</option>
    <option value="white">White</option>
    <option value="turquoise">Turquoise</option>
  </select>

  Text color <select id="select_txtcolor" onchange="byt1">
    <option value="black">Black</option>
    <option value="blue">Blue</option>
    <option value="red">Red</option>
    <option value="darkgreen">Dark green</option>
  </select>

  font <select id="select_txtfont" onchange="byt1">
    <option value="verdana">Verdana</option>
    <option value="Arial">Arial</option>
    <option value="tahoma">Tahoma</option>
    <option value="impact">Impact</option>
  </select>
  </form>
 <div style="margin-top:15px;">
    <input type="button" id="reset" value="Reset" />
      <input type="button" id="byt1" value="Print" />
 </div>

</div>

<div id="page2">
  <h2>Page 2</h2>
  <p id="area"></p>
  <input type="button" id="byt2" value="Back to page 1" />
</div>


问:
Merge 'Specific' file(from dev branch) into master(branch)
My dev branch has several files and commits from all the developers but I am only interested to merge back changes from one specific file

```<code>File-A
File-B
File-C
</code>```

I need to merge everything from File-B (at dev branch) to master

Make File-B at master same as File-B at dev-branch, (preserving all the commit logs)

答:
Even with the clarification, something is still missing.  But you can perhaps get what you want using git merge-file.  Or maybe not.

I need to merge everything from File-B (at dev branch) to master

(OK so far)

Make File-B at master same as File-B at dev-branch, (preserving all the commit logs)

This part makes no sense.

First, "merge" doesn't mean "make the same as".

Second, git log shows commits.  The commits in a repository are the history in the repository.  Each commit is a complete snapshot of a source tree.  Commit 19afc3d may hold 23 files, and subsequent-or-previous commit b099ca2 may hold 23 files of the same name, 22 of which have the same content.  But they're just two separate commits, each holding 23 files.

Adding a new commit to a repository does just that: adds a new commit, with a new snapshot.

Running git merge does something more complex.  Depending on the existing commit graph and options you supply at the time you run git merge, it can make a true merge.  It does this by traversing the commit graph to find a merge base commit, which is the first commit where the two parts of the graph rejoin:

```<code>...--A--B--C--D   <-- master (HEAD)
         \
          E--F--G   <-- dev
</code>```

Here, the merge base is commit B.  Git can then figure out what we changed:

```<code>git diff --find-renames <hash-of-B> <hash-of-D>
</code>```

and find out what they changed:

```<code>git diff --find-renames <hash-of-B> <hash-of-G>
</code>```

Git then then combine these changes, to get both sets of changes.  So if, with respect to commit B, we changed File-B to add three lines, and they changed File-B to remove an unrelated set of three lines, the total change will be: add our three lines and remove their three lines.

If Git is able to combine all the changes to all the files, Git will then make a new merge commit, with two parents instead of one:

```<code>...--A--B--C--D---H   <-- master (HEAD)
         \       /
          E--F--G   <-- dev
</code>```

That is a merge commit (merge as an adjective) or a merge (merge as a noun), made using, as its snapshot, all files from the base B as changed by the combination of our changes (B-to-D) and their changes (B-to-G).

Some of the files in H may be the same as some of the files in any of B, D, and G, but if so, that's because of the results of combining the two sets of changes.

If you run git merge-file, you must supply the base version of the file and both branch-tip versions of the file.  Git will combine the changes into that one file, the way Git normally does with an actual merge.  Git will not make a new commit from the result, and if you do, it will not be a merge commit, it will just be an ordinary commit:

```<code>...--A--B--C--D---H   <-- master (HEAD)
         \
          E--F--G   <-- dev
</code>```

If you literally want the file to be the same—i.e., ignore any changes we made in commits C and D, and just take the version of the file from commit G directly—you can do that with git checkout dev -- File-B.  Again, committing the result will make an ordinary, non-merge commit.

If you want to make a merge commit, doing a proper merge of File-B but ignoring their changes to all files except that one specific file, that takes a slightly more complicated set of Git commands:

```<code>git merge --no-commit dev
git checkout master -- [all files except for FileB]
</code>```

(or, equivalently, save the merged version somewhere, check everything out from master with git checkout master -- ., then put the merged file back in place and git add FileB).  Note, however, that recording this as a merge commit tells Git that the correct result for doing the complete merge is whatever you just committed.  If you want, later, to merge other changes from dev, you will be making this much harder for yourself.

Body:
My dev branch has several files and commits from all the developers but I am only interested to merge back changes from one specific file

File-A
File-B
File-C

I need to merge everything from File-B (at dev branch) to master

Make File-B at master same as File-B at dev-branch, (preserving all the commit logs)

Body:
Even with the clarification, something is still missing.  But you can perhaps get what you want using git merge-file.  Or maybe not.

I need to merge everything from File-B (at dev branch) to master

(OK so far)

Make File-B at master same as File-B at dev-branch, (preserving all the commit logs)

This part makes no sense.

First, "merge" doesn't mean "make the same as".

Second, git log shows commits.  The commits in a repository are the history in the repository.  Each commit is a complete snapshot of a source tree.  Commit 19afc3d may hold 23 files, and subsequent-or-previous commit b099ca2 may hold 23 files of the same name, 22 of which have the same content.  But they're just two separate commits, each holding 23 files.

Adding a new commit to a repository does just that: adds a new commit, with a new snapshot.

Running git merge does something more complex.  Depending on the existing commit graph and options you supply at the time you run git merge, it can make a true merge.  It does this by traversing the commit graph to find a merge base commit, which is the first commit where the two parts of the graph rejoin:

...--A--B--C--D   <-- master (HEAD)
         \
          E--F--G   <-- dev

Here, the merge base is commit B.  Git can then figure out what we changed:

git diff --find-renames <hash-of-B> <hash-of-D>

and find out what they changed:

git diff --find-renames <hash-of-B> <hash-of-G>

Git then then combine these changes, to get both sets of changes.  So if, with respect to commit B, we changed File-B to add three lines, and they changed File-B to remove an unrelated set of three lines, the total change will be: add our three lines and remove their three lines.

If Git is able to combine all the changes to all the files, Git will then make a new merge commit, with two parents instead of one:

...--A--B--C--D---H   <-- master (HEAD)
         \       /
          E--F--G   <-- dev

That is a merge commit (merge as an adjective) or a merge (merge as a noun), made using, as its snapshot, all files from the base B as changed by the combination of our changes (B-to-D) and their changes (B-to-G).

Some of the files in H may be the same as some of the files in any of B, D, and G, but if so, that's because of the results of combining the two sets of changes.

If you run git merge-file, you must supply the base version of the file and both branch-tip versions of the file.  Git will combine the changes into that one file, the way Git normally does with an actual merge.  Git will not make a new commit from the result, and if you do, it will not be a merge commit, it will just be an ordinary commit:

...--A--B--C--D---H   <-- master (HEAD)
         \
          E--F--G   <-- dev

If you literally want the file to be the same—i.e., ignore any changes we made in commits C and D, and just take the version of the file from commit G directly—you can do that with git checkout dev -- File-B.  Again, committing the result will make an ordinary, non-merge commit.

If you want to make a merge commit, doing a proper merge of File-B but ignoring their changes to all files except that one specific file, that takes a slightly more complicated set of Git commands:

git merge --no-commit dev
git checkout master -- [all files except for FileB]

(or, equivalently, save the merged version somewhere, check everything out from master with git checkout master -- ., then put the merged file back in place and git add FileB).  Note, however, that recording this as a merge commit tells Git that the correct result for doing the complete merge is whatever you just committed.  If you want, later, to merge other changes from dev, you will be making this much harder for yourself.


问:
How to set an Image Relative to another Image View
I want to set an image on another image .
The base image is of 3600px X 2400px (WxH)
The image I want to insert has these conditions:-
X: 471px
Y: 282px
W: 1053px
H: 936px
 X & Y are relative to the base image.
All coordinates are in px.</p>

答:
Use a FrameLayout. Generally, a FrameLayout is used to hold a single child view otherwise it is difficult.
See the documentation</p>


问:
How to read test data from csv for JSON requests other than using set options
I used the set feature of Karate to change the values in keys using JSON expression.  I used it mainly to change the request contents based on test scenarios. This gave me the capability to avoid reading lot of test data from csv files. However, still in some situations, I prefer to use csv.

For example, I have around 230 test scenarios as post requests and I have 130 different customer information which I need to use on the 230 test cases based on the context. The customer information includes first, last names, age, address etc. However, the schema is same. If I need to use something like groovy template engines what will be the best approach to use in Karate

I need to keep these data in a csv, read it and pass the values to a JSON template before I fire the request. I need to still rely on csv/ external sources because these data becomes obsolete very often and I need to change it frequently. Could you please share your thoughts on this?

答:
Using a similar approach to this example (JDBC) you should be able to write a CSV to JSON converter in less than an hour: dogs.feature

IMO once you get used to the table or set multiple syntax, it is far better than CSV-s as it is more readable. You can use call and load the data from a second feature file that only contains the data.

Personally I would recommend using a JSON array instead of CSV. There are plenty of tools that allow you to edit JSON. And it is so easy to read JSON in Karate and use that for data-driven testing. You can even combine set or table, take a look at this for ideas: dynamic-params.feature

I guess you are aware of JSON templating built-in to Karate: embedded expressions - and you should look at the extensive test-case examples here: js-arrays.feature

Make sure you go through the demo-examples.


问:
What is wrong with this function call
Behold the code:

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
ui->viewLabel->setPixmap(QPixmap::fromImage(qi,Qt::AutoColor));
</code>```

Why does this give me an error? What is it trying to get me to change the qi argument to in the call to fromImage? I am relatively new to C++ and it seems like I am setting this up correctly. It works if I change the line to

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
    ui->viewLabel->setPixmap(QPixmap::fromImage(qi[0],Qt::AutoColor));
</code>```

But is that the correct way to do this?

答:
It's because QPixmap::fromImage expects a reference to an image, not a pointer to one.

However, change your qi[0] to *qi, that makes the intention cleaner. (or just refrain from using a pointer and start with QImage qi(fullCharArray ...).

Title: What is wrong with this function call

Body:
Behold the code:

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
ui->viewLabel->setPixmap(QPixmap::fromImage(qi,Qt::AutoColor));

Why does this give me an error? What is it trying to get me to change the qi argument to in the call to fromImage? I am relatively new to C++ and it seems like I am setting this up correctly. It works if I change the line to

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
    ui->viewLabel->setPixmap(QPixmap::fromImage(qi[0],Qt::AutoColor));

But is that the correct way to do this?


问:
I want to select the username textfield from listview and use that username to delete data present in mysql database
I want to show MySQL table data in listview and also have to put delete button on the bottom of screen. User have to select list item and by clicking on delete button the particular data should be removed from mysql table and listview. I can display records properly but cannot select the username field from list item.

View User Activity

```<code>public class ViewUser extends AppCompatActivity implements View.OnClickListener {

    private static final String VIEW_URL= "http://ajaygohel012.000webhostapp.com/ViewUser.php";

    ListView listUser;
    List<User> userlist;
    private Button btnDelete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_user);

        listUser= findViewById(R.id.listUser);
        userlist= new ArrayList<>();
        btnDelete= (Button) findViewById(R.id.btnDelete);

        final TextView viewUserName = (TextView) findViewById(R.id.viewUserName);

        loadUserList();

        listUser.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                listUser.setOnItemSelectedListener(this);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String username = viewUserName.getText().toString();
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                            try {
                                JSONObject js = new JSONObject(response);
                                boolean success = js.getBoolean("success");
                                if (success){
                                    finish();
                                    startActivity(getIntent());
                                }
                            }catch(JSONException e){
                                e.printStackTrace();
                            }
                    }
                };

                DeleteRequest deleteRequest= new DeleteRequest(username, responseListener);
                RequestQueue queue= Volley.newRequestQueue(ViewUser.this);
                queue.add(deleteRequest);
            }
        });
    }
    private void loadUserList(){
        final ProgressBar progressBar= (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);

        StringRequest stringRequest= new StringRequest(Request.Method.GET, VIEW_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                progressBar.setVisibility(View.INVISIBLE);

                try {
                    JSONObject jsonObject= new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("data");

                    for (int i=0;jsonArray.length()>i;i++){
                        final JSONObject j= jsonArray.getJSONObject(i);
                        User user=new User();

                        String name = j.getString("name");
                        String empcode = j.getString("empcode");
                        String location = j.getString("location");
                        String department = j.getString("department");
                        String username = j.getString("username");

                        user.setName(name);
                        user.setEmpcode(empcode);
                        user.setLocation(location);
                        user.setDepartment(department);
                        user.setUsername(username);
                        userlist.add(user);
                    }
                    ListViewAdapter adapter = new ListViewAdapter(userlist, ViewUser.this);
                    listUser.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(ViewUser.this, error.getMessage(), Toast.LENGTH_SHORT);
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    @Override
    public void onClick(View view) {
        if (view==btnDelete){
            finish();
            startActivity(new Intent(this, ViewUser.class));
        }
    }
}
</code>```

DeleteRequest

```<code>class DeleteRequest extends StringRequest{
    private static final String LOGIN_REQUEST_URL= "http://ajaygohel012.000webhostapp.com/DeleteUser.php";
    private Map<String, String> params;

    public DeleteRequest(String username, Response.Listener<String> listener) {
        super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
        params = new HashMap<>();
        params.put("username", username);
    }
    public Map<String, String> getParams(){
        return params;
    }

}
</code>```

User class

```<code>public class User {
    String name, empcode, location, department, username;

    public User(){
        this.name=name;
        this.empcode=empcode;
        this.location=location;
        this.department=department;
        this.username=username;
    }

    public String getName() {
        return name;
    }

    public String getEmpcode() {
        return empcode;
    }

    public String getLocation() {
        return location;
    }

    public String getDepartment() {
        return department;
    }

    public String getUsername() {
        return username;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setEmpcode(String empcode) {
        this.empcode = empcode;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

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

ListViewAdapter

```<code>public class ListViewAdapter extends ArrayAdapter<User> {
    private List<User> userlist;
    private Context cntx;

    public ListViewAdapter(List<User> userlist, Context cntx){
        super(cntx, R.layout.list_item, userlist);
        this.userlist=userlist;
        this.cntx=cntx;
    }
    public View getView(int position, View convertView, ViewGroup parent){
        LayoutInflater inflater= LayoutInflater.from(cntx);
        View listViewitem= inflater.inflate(R.layout.list_item,null, true);

        TextView viewName= listViewitem.findViewById(R.id.viewName);
        TextView viewEmployeeCode= listViewitem.findViewById(R.id.viewEmployeeCode);
        TextView viewLocation= listViewitem.findViewById(R.id.viewLocation);
        TextView viewDepartment= listViewitem.findViewById(R.id.viewDepartment);
        TextView viewUserName= listViewitem.findViewById(R.id.viewUserName);

        User user=userlist.get(position);

        viewName.setText(user.getName());
        viewEmployeeCode.setText(user.getEmpcode());
        viewLocation.setText(user.getLocation());
        viewDepartment.setText(user.getDepartment());
        viewUserName.setText(user.getUsername());

        return listViewitem;
    }
}
</code>```

DeleteUser PHP

```<code><?php
$connection = mysqli_connect("localhost", "abc", "xyz", "id3275958_user");

if(isset($_POST['username'])) {
$username = $_POST['username'];

$result = mysql_query("DELETE FROM user WHERE username = $username");

$response = array();

if (mysql_affected_rows() > 0) {
    $response["success"] = 1;
    $response["message"] = "User successfully deleted";
} else {
    $response["success"] = 0;
    $response["message"] = "No User found";
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
}
echo json_encode($response);
?>
</code>```

I also made php script and giving me proper response. Just want send username from my app is remaining.

答:
It's a lot of reading, but I think the follow link will help

https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/

Body:
I want to show MySQL table data in listview and also have to put delete button on the bottom of screen. User have to select list item and by clicking on delete button the particular data should be removed from mysql table and listview. I can display records properly but cannot select the username field from list item.

View User Activity

public class ViewUser extends AppCompatActivity implements View.OnClickListener {

    private static final String VIEW_URL= "http://ajaygohel012.000webhostapp.com/ViewUser.php";

    ListView listUser;
    List<User> userlist;
    private Button btnDelete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_user);

        listUser= findViewById(R.id.listUser);
        userlist= new ArrayList<>();
        btnDelete= (Button) findViewById(R.id.btnDelete);

        final TextView viewUserName = (TextView) findViewById(R.id.viewUserName);

        loadUserList();

        listUser.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                listUser.setOnItemSelectedListener(this);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String username = viewUserName.getText().toString();
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                            try {
                                JSONObject js = new JSONObject(response);
                                boolean success = js.getBoolean("success");
                                if (success){
                                    finish();
                                    startActivity(getIntent());
                                }
                            }catch(JSONException e){
                                e.printStackTrace();
                            }
                    }
                };

                DeleteRequest deleteRequest= new DeleteRequest(username, responseListener);
                RequestQueue queue= Volley.newRequestQueue(ViewUser.this);
                queue.add(deleteRequest);
            }
        });
    }
    private void loadUserList(){
        final ProgressBar progressBar= (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);

        StringRequest stringRequest= new StringRequest(Request.Method.GET, VIEW_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                progressBar.setVisibility(View.INVISIBLE);

                try {
                    JSONObject jsonObject= new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("data");

                    for (int i=0;jsonArray.length()>i;i++){
                        final JSONObject j= jsonArray.getJSONObject(i);
                        User user=new User();

                        String name = j.getString("name");
                        String empcode = j.getString("empcode");
                        String location = j.getString("location");
                        String department = j.getString("department");
                        String username = j.getString("username");

                        user.setName(name);
                        user.setEmpcode(empcode);
                        user.setLocation(location);
                        user.setDepartment(department);
                        user.setUsername(username);
                        userlist.add(user);
                    }
                    ListViewAdapter adapter = new ListViewAdapter(userlist, ViewUser.this);
                    listUser.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(ViewUser.this, error.getMessage(), Toast.LENGTH_SHORT);
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    @Override
    public void onClick(View view) {
        if (view==btnDelete){
            finish();
            startActivity(new Intent(this, ViewUser.class));
        }
    }
}

DeleteRequest

class DeleteRequest extends StringRequest{
    private static final String LOGIN_REQUEST_URL= "http://ajaygohel012.000webhostapp.com/DeleteUser.php";
    private Map<String, String> params;

    public DeleteRequest(String username, Response.Listener<String> listener) {
        super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
        params = new HashMap<>();
        params.put("username", username);
    }
    public Map<String, String> getParams(){
        return params;
    }

}

User class

public class User {
    String name, empcode, location, department, username;

    public User(){
        this.name=name;
        this.empcode=empcode;
        this.location=location;
        this.department=department;
        this.username=username;
    }

    public String getName() {
        return name;
    }

    public String getEmpcode() {
        return empcode;
    }

    public String getLocation() {
        return location;
    }

    public String getDepartment() {
        return department;
    }

    public String getUsername() {
        return username;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setEmpcode(String empcode) {
        this.empcode = empcode;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

ListViewAdapter

public class ListViewAdapter extends ArrayAdapter<User> {
    private List<User> userlist;
    private Context cntx;

    public ListViewAdapter(List<User> userlist, Context cntx){
        super(cntx, R.layout.list_item, userlist);
        this.userlist=userlist;
        this.cntx=cntx;
    }
    public View getView(int position, View convertView, ViewGroup parent){
        LayoutInflater inflater= LayoutInflater.from(cntx);
        View listViewitem= inflater.inflate(R.layout.list_item,null, true);

        TextView viewName= listViewitem.findViewById(R.id.viewName);
        TextView viewEmployeeCode= listViewitem.findViewById(R.id.viewEmployeeCode);
        TextView viewLocation= listViewitem.findViewById(R.id.viewLocation);
        TextView viewDepartment= listViewitem.findViewById(R.id.viewDepartment);
        TextView viewUserName= listViewitem.findViewById(R.id.viewUserName);

        User user=userlist.get(position);

        viewName.setText(user.getName());
        viewEmployeeCode.setText(user.getEmpcode());
        viewLocation.setText(user.getLocation());
        viewDepartment.setText(user.getDepartment());
        viewUserName.setText(user.getUsername());

        return listViewitem;
    }
}

DeleteUser PHP

<?php
$connection = mysqli_connect("localhost", "abc", "xyz", "id3275958_user");

if(isset($_POST['username'])) {
$username = $_POST['username'];

$result = mysql_query("DELETE FROM user WHERE username = $username");

$response = array();

if (mysql_affected_rows() > 0) {
    $response["success"] = 1;
    $response["message"] = "User successfully deleted";
} else {
    $response["success"] = 0;
    $response["message"] = "No User found";
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
}
echo json_encode($response);
?>

I also made php script and giving me proper response. Just want send username from my app is remaining.


问:
PowerShell - Rename several files in several folders with increment
My quest is how I can change the name of each file in several folders at once and still use incrementation unique to the folder.

More specifically I want to rename the .jpg-files in folders e.g. named 1.1, 1.2, 1.3, ... , 99.1, ... to the same name as the folder + and extra extension '.X'; where X = 1,2,...,99.

E.g. if the folder 1.1 contains 3 files I would like to name them: 1.1.1.jpg, 1.1.2.jpg and 1.1.3.jpg.

I am new to PowerShell, but I thought I managed to solve the issue with the following code:

```<code>$i = 1
Get-ChildItem "C:\Users\Rename" -Recurse | Where {$_.extension -eq ".jpg"} | %{Rename-Item $_.FullName -Newname ($_.Directory.Name+'.{0}.jpg' -f $i++)}
</code>```

However, the incrementation does of course not understand when the folders change...

I was wondering if anyone might have an elegant solution to this issue or if I will have to learn how to use if/for statements in PowerShell?

I am grateful for any answers! (Will also greatly appreciate tips with "for" etc. coding with PowerShell.)

/Eric

答:
Get your list of folder first, then loop through them, resetting $i to 1 each time:</p>

```<code>$folders = Get-ChildItem "C:\Users\Rename" -Recurse | where {$_.PSIsContainer -eq $true} | select FullName

foreach ($folder in $folders) {

Set-Location $folder.FullName

$i = 1

Get-ChildItem -Filter "*.jpg" | % {Rename-Item $_.FullName -Newname ($_.Directory.Name+'.{0}.jpg' -f $i++)}
}
</code>```

Body:
My quest is how I can change the name of each file in several folders at once and still use incrementation unique to the folder.

More specifically I want to rename the .jpg-files in folders e.g. named 1.1, 1.2, 1.3, ... , 99.1, ... to the same name as the folder + and extra extension '.X'; where X = 1,2,...,99.

E.g. if the folder 1.1 contains 3 files I would like to name them: 1.1.1.jpg, 1.1.2.jpg and 1.1.3.jpg.

I am new to PowerShell, but I thought I managed to solve the issue with the following code:

$i = 1
Get-ChildItem "C:\Users\Rename" -Recurse | Where {$_.extension -eq ".jpg"} | %{Rename-Item $_.FullName -Newname ($_.Directory.Name+'.{0}.jpg' -f $i++)}

However, the incrementation does of course not understand when the folders change...

I was wondering if anyone might have an elegant solution to this issue or if I will have to learn how to use if/for statements in PowerShell?

I am grateful for any answers! (Will also greatly appreciate tips with "for" etc. coding with PowerShell.)

/Eric

Body:
Get your list of folder first, then loop through them, resetting $i to 1 each time:

$folders = Get-ChildItem "C:\Users\Rename" -Recurse | where {$_.PSIsContainer -eq $true} | select FullName

foreach ($folder in $folders) {

Set-Location $folder.FullName

$i = 1

Get-ChildItem -Filter "*.jpg" | % {Rename-Item $_.FullName -Newname ($_.Directory.Name+'.{0}.jpg' -f $i++)}
}


答:
Here is a function that seems to do the trick with any size of a matrix but I'm not quite sure if you wanted always to find the first "1" in the matrix  even if it was alone on the line and on the right side..
Using your arrays as test parameters</p>

```<code>    var array = [
    '00000',
    '01111',
    '11000',
    '00100'];

var error_array = [
    '000000',
    '000011',
    '111111',
    '111111',
    '000000',
    '000010',
    '100000'
    ]

getLeftBottom(error_array);

function getLeftBottom(testArray)
{
    var firstFound;
    for (var index = testArray.length; index > 0; index--)
    {
        console.log(testArray[index-1]);
        str = testArray[index-1];
        firstFound = str.indexOf("1");
        if (firstFound !== -1)
        {
            console.log("Coordinates: x = {0}, y = {1}", firstFound, index)   // Apparently this doesn't work as I expected in JS but you can still see the coordinates
            break;
        }

    }
}
</code>```

Title: (Javascript - Arrays) Get most left and most right connected character

Body:
Here is a function that seems to do the trick with any size of a matrix but I'm not quite sure if you wanted always to find the first "1" in the matrix  even if it was alone on the line and on the right side..
Using your arrays as test parameters

    var array = [
    '00000',
    '01111',
    '11000',
    '00100'];

var error_array = [
    '000000',
    '000011',
    '111111',
    '111111',
    '000000',
    '000010',
    '100000'
    ]

getLeftBottom(error_array);

function getLeftBottom(testArray)
{
    var firstFound;
    for (var index = testArray.length; index > 0; index--)
    {
        console.log(testArray[index-1]);
        str = testArray[index-1];
        firstFound = str.indexOf("1");
        if (firstFound !== -1)
        {
            console.log("Coordinates: x = {0}, y = {1}", firstFound, index)   // Apparently this doesn't work as I expected in JS but you can still see the coordinates
            break;
        }

    }
}


问:
SuiteScript 2.0 Map Reduce Script Parameters
I have written a map/reduce script to check a box on thousands of journal entry records. I have a dynamic parameter that passes in journal status when script is run. In suitescript 1.0 I grab script parameters off context object.

I'm sure it is similar in 2.0, but I can't seem to find it on context object in 2.0.

答:
import N/runtime

then

```<code>var me = runtime.getCurrentScript();
var paramVal = me.getParameter({name:'custscript_my_script_param'});
</code>```

Body:
import N/runtime

then

var me = runtime.getCurrentScript();
var paramVal = me.getParameter({name:'custscript_my_script_param'});


问:
TypeScript error with Promise.reject
Why do I receive the following compilation error with this TypeScript method which I wrote:

```<code>getFile(path: string): Promise<FileEntry> {
  return this.file.resolveLocalFilesystemUrl(path)
    .then(entry => {
      if (entry.isFile) {
        return <FileEntry>entry;
      } else {
        let err = new FileError(13);
        err.message = 'input is not a file';
        return Promise.reject(err);
      }
    });
}
</code>```

I get the error:

```<code>Argument of type '(entry: Entry) => Promise<never> | FileEntry' is not assignable to parameter of type '(value: Entry) => PromiseLike<never>'. Type 'Promise<never> | FileEntry' is not assignable to type 'PromiseLike<never>'. Type 'FileEntry' is not assignable to type 'PromiseLike<never>'. Property 'then' is  missing in type 'FileEntry'.
</code>```

The definition for resolveLocalFilesystemUrl is as follows:

```<code>resolveLocalFilesystemUrl(fileUrl: string): Promise<Entry>;
</code>```

FileEntry is a subclass of Entry, hence the casted return. However, the error is around Promise.reject.

If I change my reject line to the following, it works:

```<code>return Promise.reject<FileEntry>(err);
</code>```

Do I need to return Promise.reject(...) and what is the correct implementation?

答:
To return a promise you create a new Instance of a promise and return this instance. The constructor takes a function that receives the resolve and reject callbacks you should call, when your logic succeeds or fails.

To let your promise "return" your result, you don't write return result, but call resolve(result).

```<code>getFile(path: string): Promise<FileEntry> {
  return new Promise<FileEntry>((resolve, reject) => {
    // Your logic here.
    // call resolve() on success
    // or reject() on failure
  });
}
</code>```

So in your case it should look like the following:

```<code>getFile(path: string): Promise<FileEntry> {
  return new Promise<FileEntry>((resolve, reject) => {
    this.file.resolveLocalFilesystemUrl(path)
    .then(entry => {
      if (entry.isFile) {
        resolve(<FileEntry>entry); // Success
      } else {
        let err = new FileError(13);
        err.message = 'input is not a file';
        reject(err); // Error
      }
    });
  });
}
</code>```

If you want to learn more about promises read for example here:
https://developers.google.com/web/fundamentals/primers/promises

Title: TypeScript error with Promise.reject

Body:
Why do I receive the following compilation error with this TypeScript method which I wrote:

getFile(path: string): Promise<FileEntry> {
  return this.file.resolveLocalFilesystemUrl(path)
    .then(entry => {
      if (entry.isFile) {
        return <FileEntry>entry;
      } else {
        let err = new FileError(13);
        err.message = 'input is not a file';
        return Promise.reject(err);
      }
    });
}

I get the error:

Argument of type '(entry: Entry) => Promise<never> | FileEntry' is not assignable to parameter of type '(value: Entry) => PromiseLike<never>'. Type 'Promise<never> | FileEntry' is not assignable to type 'PromiseLike<never>'. Type 'FileEntry' is not assignable to type 'PromiseLike<never>'. Property 'then' is  missing in type 'FileEntry'.

The definition for resolveLocalFilesystemUrl is as follows:

resolveLocalFilesystemUrl(fileUrl: string): Promise<Entry>;

FileEntry is a subclass of Entry, hence the casted return. However, the error is around Promise.reject.

If I change my reject line to the following, it works:

return Promise.reject<FileEntry>(err);

Do I need to return Promise.reject(...) and what is the correct implementation?

Body:
To return a promise you create a new Instance of a promise and return this instance. The constructor takes a function that receives the resolve and reject callbacks you should call, when your logic succeeds or fails.

To let your promise "return" your result, you don't write return result, but call resolve(result).

getFile(path: string): Promise<FileEntry> {
  return new Promise<FileEntry>((resolve, reject) => {
    // Your logic here.
    // call resolve() on success
    // or reject() on failure
  });
}

So in your case it should look like the following:

getFile(path: string): Promise<FileEntry> {
  return new Promise<FileEntry>((resolve, reject) => {
    this.file.resolveLocalFilesystemUrl(path)
    .then(entry => {
      if (entry.isFile) {
        resolve(<FileEntry>entry); // Success
      } else {
        let err = new FileError(13);
        err.message = 'input is not a file';
        reject(err); // Error
      }
    });
  });
}

If you want to learn more about promises read for example here:
https://developers.google.com/web/fundamentals/primers/promises


问:
Dropbox not uploading the changed files frequently
I have installed the dropbox and linked with eclipsed workspace but I have found that file which is on server is old one. I have made many changes using control s and its not saving

or is there any way by which I can manually click on sync now.

or any other software

答:
I have noticed with dropbox that sometimes a file will not update, this happens a lot with my password safe file if I have it open on more then one machine. Could this be your problem?

It may not open if something is locking the file.

OwnerDisplayName: John