text:
Q: the Conversion from string "" to type 'Double' is not valid this code below is for the quantity. The price of the product times the quantity then you get the total
If CheckedListBox1.Text = "1" Then
        TextBox5.Text = 1
        TextBox4.Text = TextBox5.Text * TextBox4.Text<<<<<<  This part keeps saying "Conversion from string "" to type 'Double' is not valid". Please help!
        Exit Sub
    End If
    If CheckedListBox1.Text = "2" Then
        TextBox5.Text = 2
        TextBox4.Text = TextBox4.Text * TextBox5.Text
        Exit Sub
    End If
    If CheckedListBox1.Text = "3" Then
        TextBox5.Text = 3
        TextBox4.Text = TextBox5.Text * TextBox4.Text
        Exit Sub
    End If
    If CheckedListBox1.Text = "4" Then
        TextBox5.Text = 4
        TextBox4.Text = TextBox5.Text * TextBox4.Text
        Exit Sub
    End If

A: Change this line of code (And all others like it in your various if statements)
TextBox4.Text = TextBox5.Text * TextBox4.Text

To this
TextBox4.Text = (CDbl(TextBox5.Text) * CDbl(TextBox4.Text)).ToString()

This way your text is being casted to a double before being operated on and then once your mathematical operation is complete the result is converted back to text via the .ToString() function
Note: If you use text boxes for user input numerical data you are also going to have to handle for non-numerical input and disallow the user from typing anything but numbers and decimal points. (This includes handling for empty strings as noted by @Jeroen) I would recommend you consider using a NumericUpDown control instead

A: Carrying on from previous answer, I would say this:
Dim dbl1, dbl2 As Double
If Double.TryParse(TextBox4.Text, dbl1) AndAlso Double.TryParse(TextBox5, dbl2) Then
    TextBox4.Text = dbl1 * dbl2
Else
    MsgBox("Danger, Will Robinson!")
End If

However, if you expect there to be a double you need to make sure the user enters a value that can correctly be converted. Doing it later on in the code, is just a quick fix for a problem that should have been caught long before you ever started writing code that performs maths...


text:
Q: why python not converts float or any other data type to string when written with string? Suppose
p1="python"
p2="script"
r=0.242424

print(p1+" "+p2+" "+r)          #wrong or error in python
print(p1+" "+p2+" "+str(r))       #correct

Why do I we have to convert a float to string explicitly in Python, but other languages like Java convert it implicitly?

A: You don't. You only need to convert it explicitly when concatenating. print() will use spaces to separate arguments on its own, converting each to a string:
print(p1, p2, r)

Quoting the print() documentation:

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.

sep defaults to the ' ' string.
You usually use string formatting to interpolate values into a string:
print("Running a {} {} to show the value of r={:.6f}".format(p1, p2, r))

Otherwise, trying to concatenate strings with other values does not convert values implicitly; this goes against the Zen of Python:

Explicit is better than implicit.

A: If you want to join various data types into a string, concatenation with + or with the str.join method will require them to be strings before you do it.
As Martijn shows, it's not needed for printing, but that can be confusing because printing by default includes newlines and a space that separates elements separated by commas that are being printed.
If you want to implicitly convert them to strings, I recomend the string.format method:
>>> '{0} {1} {2}'.format(p1, p2, r)
'python script 0.242424'

This is quite a useful and efficient way to format text and not have to worry about the types, so long as you don't mind getting their default string representation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: can we have a non primary key as partition key in azure cosmos DB? I am creating a Collection in cosmos db which can exceed 10GB. The collection does not have any primary key. is it good idea to make the  non primary key  field which i will be querying frequently as the partition key?

A:
is it good idea to make the non primary key field which i will be
  querying frequently as the partition key?

Actually, the choice of partition key is a question that deserves to be weighed repeatedly. The best partition key is one that provides for even distribution and higher cardinality.
Since choosing to be the non primary key that you will query frequently is your option now, I just discuss some of the possible positive and negative things as your references.
Firstly, we could say that the primary key is the safest and probably, most appropriate choice for a partition key.
It guarantees uniqueness of the value, which other than unique keys, is the only way to achieve. The distribution will be even and because the primary key will be your partition key, you will be able to use it in order to retrieve the document by reading it, instead of querying, which reduces operation speed and cost.
In terms of performance, if your query frequently field is not partition key, your query will definitely reduce query performance by crossing partitions. Surely, if the amount of data is large, it will have much effect.
In terms of cost, cosmos db is charged primarily by storage space and RUs consumption. As you said, choosing non primary key as partition key will lead less indexes storage. If mostly queries are not cross-partition, it also saves RUs consumption.
In terms of using of stored procedure, triggers or UDF, you can't use cross-partition transactions via stored procedures and triggers. Because then are partitioned so that you need to specify the partition key(cardinality is only 1) when you use them.
Just note that if partition key is created, it cannot be deleted or modified later. So consider it before you choose and make sure you do the data backup.
More details, still refer to the official doc.


text:
Q: look for differences between similarily named vectors (e.g. *_pre and *_post) in R i have a dataframe with multiple columns that code an exposure (as 1/0) over multiple time points and follow a naming pattern, e.g. exposure1_pre2, exposure1_pre1, exposure1_post ... exposuren_pre2, ...
working example
library(dplyr)

df <- tibble(exposure1_pre2 = sample(c(0, 1), size = 20, replace = T),
             exposure1_pre1 = sample(c(0, 1), size = 20, replace = T),
             exposure1_post = sample(c(0, 1), size = 20, replace = T),
             exposure2_pre2 = sample(c(0, 1), size = 20, replace = T),
             exposure2_pre1 = sample(c(0, 1), size = 20, replace = T),
             exposure2_post = sample(c(0, 1), size = 20, replace = T)
             )

i would like to code dummy variables that are set to 1/0 if there is a directional change from one time point to another, i.e. when exposure1_pre2 is 0 and exposure1_pre1 is 1 the new column exposure1_pre2_to_pre1 == 1.
i am trying to realize this with dplyr if_else - or ideally case_when for all possible combinations - and am thinking along the lines of
df %>%
  mutate(
    across(contains("pre2"),
    ~if_else(.x == 0 & ??? == 1, 1, 0), .names = "{???}_pre2_to_pre1")
  )

as is obvious, i am lost how to structure the condition so that it looks for the similarly named *_pre2 variable to assess for a difference and also would need to take only the exposure part from the input column for the naming of the new column - i suppose a grep could do here?
thank you very much and have a good day!

A: Loop across the 'pre2' column, get the column name (cur_column()), replace the substring with 'pre1', get the value, do the compound logical expression and coerce the output logical to binary with + (or as.integer)
library(dplyr)
library(stringr)
 df %>%
  mutate(
     across(contains("pre2"),
             ~ +(. == 0 & get(str_replace(cur_column(), 'pre2', 'pre1')) == 1),
              .names = '{.col}_to_pre1'))

-output
# A tibble: 20 x 8
   exposure1_pre2 exposure1_pre1 exposure1_post exposure2_pre2 exposure2_pre1 exposure2_post exposure1_pre2_to_pre1 exposure2_pre2_to_pre1
            <dbl>          <dbl>          <dbl>          <dbl>          <dbl>          <dbl>                  <int>                  <int>
 1              1              0              1              0              1              1                      0                      1
 2              1              0              1              1              0              0                      0                      0
 3              1              0              1              1              0              0                      0                      0
 4              1              1              1              0              1              0                      0                      1
 5              0              1              1              0              0              0                      1                      0
 6              1              1              1              0              1              1                      0                      1
 7              0              1              0              1              0              0                      1                      0
 8              0              1              0              1              1              1                      1                      0
 9              0              1              0              0              1              0                      1                      1
10              1              0              1              1              1              0                      0                      0
11              0              0              1              0              0              1                      0                      0
12              0              1              1              1              1              1                      1                      0
13              0              1              1              1              1              0                      1                      0
14              1              1              1              0              0              1                      0                      0
15              1              1              1              1              0              0                      0                      0
16              1              1              1              0              0              1                      0                      0
17              0              0              0              1              0              0                      0                      0
18              1              0              0              0              0              0                      0                      0
19              1              0              0              0              0              1                      0                      0
20              1              0              1              1              0              1                      0                      0


text:
Q: boosted regression trees train error in caret package I am trying to use the code below to train a boosted regression tree by CV of AUC.
But I am getting the message:
Error in { : task 1 failed - "subscript out of bounds"

If I didn't specify distribution="gaussian", I will not receive the error message.
Any ideal to fix this problem? Thank you very much.
 gbmGrid <- expand.grid(interaction.depth=(3:6), n.trees=(1:40)*100, shrinkage=.01)
 gbmGrid$n.minobsinnode = rep(10,nrow(gbmGrid))
 head(gbmGrid)

 bootControl <- trainControl(method='cv',classProbs = TRUE,number=3,summaryFunction = twoClassSummary)

 gmbFit<- caret::train(X,Y,
                  distribution="gaussian",
                  method = "gbm",
                  verbose = F,
                  trControl = bootControl,
                  bag.fraction=0.5,
                  metric="ROC",
                  tuneGrid=gbmGrid)


text:
Q: How to prove this inequality in a metric space I have $(X, d)$, a metric space, and I have to prove that
$$|d(x,u)-d(y,u)|\le d(x,y)+d(u,v).$$ I can see that what I have to prove are two inequalities $-d(x,y)-d(u,v)\le d(x,u)-d(y,u)$ and $d(x,u)-d(y,u)\le d(x,y)+d(u,v)$. For the second one I used this inequality (that I already proved) $|d(x,u)-d(y,u)|\le d(x,y)$ and I get $d(x,u)-d(y,u)\le d(x,y)\le d(x,y)+d(u,v)$, I hope it's ok. However with the first one, I got a little frustrated.

A: By the triangle inequality $d(x,u)\le d(x,y)+d(y,u)\le d(x,y)+d(u,v)+d(y,v).$ Similarly, $d(y,v)\le d(x,y)+d(x,v)\le d(x,y)+d(u,v)+d(x,u)$, so $d(x,u)-d(y,v)\le d(x,y)+d(u,v)$ and $d(y,v)-d(x,u)\le d(x,y)+d(u,v).$ Combine the last two to get $|d(x,u)-d(y,v)|\le d(x,y)+d(u,v).$

A: I thought a little picture might help the intuition (as suggested by @Jack)

*

*Case 1 : $ d(x,u)-d(y,v) \le d(x,y)+d(u,v)$
$\Leftrightarrow \color{\red}{d(x,u)} \le \color{\green}{d(x,y) +d(y,v) + d(v,u)}$ (by symmetry of $d(\cdot)$). This holds by a twofold application of the triangle inequality which can be visualized in the following picture.

*

*Case 2 : $ d(y,v) - d(x,u) \le d(x,y)+d(u,v)$
$\Leftrightarrow \color{\red}{d(y,v)} \le \color{\green}{d(y,x) + d(x,u) + d(u,v)}$ (by symmetry of $d(\cdot)$). Again a similar picture can be drawn to illustrate the double application of the triangle inequality.


text:
Q: Links in HTML email not clickable outside browser I am sending out an email announcement which was an image I converted to HTML after hosting it online and mapping it to add clickable areas.
It looks perfect on both computer and mobile. Unfortunately though, the clickable areas only seem to work when viewing the email in a browser or on webmail from a desktop.
The links are not clickable when opening the email on mobile (whether in a mobile app or on a mobile browser) or on desktop when viewing through a mail app (such as the Outlook app).
Is something wrong with my code?
Edit: thanks a lot for everyone's answers! I really appreciate it.

<img src="https://www.jlgc.org.uk/en/wp-content/uploads/2021/08/JET-Alumni-Careers-Fair-Default-announcement-768x2172.png" usemap="#image-map">

<map name="image-map">
    <area target="" alt="https://www.eventbrite.co.uk/e/152680281833" title="https://www.eventbrite.co.uk/e/152680281833" href="https://www.eventbrite.co.uk/e/152680281833" coords="285,537,490,625" shape="rect">
    <area target="" alt="https://www.eventbrite.co.uk/e/152680281833" title="https://www.eventbrite.co.uk/e/152680281833" href="https://www.eventbrite.co.uk/e/152680281833" coords="281,1558,488,1649" shape="rect">
    <area target="" alt="https://www.linkedin.com/groups/9061378/" title="https://www.linkedin.com/groups/9061378/" href="https://www.linkedin.com/groups/9061378/" coords="257,1339,420,1377" shape="rect">
    <area target="" alt="https://forms.gle/MFK1U2XzE3G4vAscA" title="https://forms.gle/MFK1U2XzE3G4vAscA" href="https://forms.gle/MFK1U2XzE3G4vAscA" coords="440,1766,505,1803" shape="rect">
    <area target="" alt="https://www.jetaa.org.uk/events/uk-jet-returnees-online-careers-fair-2020/" title="https://www.jetaa.org.uk/events/uk-jet-returnees-online-careers-fair-2020/" href="https://www.jetaa.org.uk/events/uk-jet-returnees-online-careers-fair-2020/" coords="252,1848,468,1884" shape="rect">
    <area target="" alt="https://www.linkedin.com/company/69498145/" title="https://www.linkedin.com/company/69498145/" href="https://www.linkedin.com/company/69498145/" coords="154,2121,31" shape="circle">
    <area target="" alt="https://twitter.com/jlgclondon" title="https://twitter.com/jlgclondon" href="https://twitter.com/jlgclondon" coords="308,2122,30" shape="circle">
    <area target="" alt="https://www.facebook.com/jlgclondon" title="https://www.facebook.com/jlgclondon" href="https://www.facebook.com/jlgclondon" coords="471,2121,30" shape="circle">
    <area target="" alt="https://www.instagram.com/jlgclondon" title="https://www.instagram.com/jlgclondon" href="https://www.instagram.com/jlgclondon" coords="621,2121,31" shape="circle">
</map>

A: Email does not support just any html tag that you can use in the browser.
To see which tags are safe to use in emails you might also check out this answer.

A: The map tag is not supported. The fact is that Outlook uses Word for rendering message bodies. Read more about supported and unsupported HTML elements, attributes, and cascading style sheets properties in the following articles:

*

*Word HTML and CSS Rendering Capabilities in Outlook (Part 1 of 2)

*Word HTML and CSS Rendering Capabilities in Outlook (Part 2 of 2)


text:
Q: Greeter for lightDM not accepting changes Basically the greeter has changed to the greeter usually used in xubuntu. I did install the xubuntu desktop package over kubuntu, but I've removed it by now. however it's managed to reinstall itself(I did confirm that it was removed). What is going on.
Edit for clarity: What I mean is, unity has it's greeter to log in, KDE has its own, and so does xfce. I'd first installed kubuntu then switched it to XFCE for the desktop, which also gave me the XFCE greeter then to unity which gave me the unity greeter. then I uninstalled XFCE and its packages. however when I restarted my computer the XFCE packages were re-added and the greeter had been switched to that of XFCE which I'm now unable to get rid of which is what I'm trying to do.

A: Try this is a terminal:
sudo apt-get purge abiword abiword-common abiword-plugin-grammar abiword-plugin-mathview alacarte bison blueman brltty-x11 catfish espeak exo-utils flex fonts-droid fonts-lyx gigolo gmusicbrowser gnome-system-tools gnome-time-admin gstreamer0.10-gnomevfs gthumb gthumb-data gtk2-engines-pixbuf indicator-application-gtk2 indicator-sound-gtk2 leafpad libabiword-3.0 libbison-dev libdigest-crc-perl libexo-1-0 libexo-common libexo-helpers libfl-dev libgarcon-1-0 libgarcon-common libgdome2-0 libgdome2-cpp-smart0c2a libglade2-0 libgnomevfs2-0 libgnomevfs2-common libgnomevfs2-extra libgsf-1-114 libgsf-1-common libgstreamer-perl libgtk2-notify-perl libgtk2-trayicon-perl libgtkmathview0c2a libgtkspell0 libido-0.1-0 libindicate-gtk3 libintl-perl libjpeg-progs libjpeg-turbo-progs libkeybinder0 liblink-grammar4 libloudmouth1-0 libnet-dbus-perl liboobs-1-5 libotr5 libots0 librarian0 libsexy2 libtagc0 libthunarx-2-0 libtidy-0.99-0 libtie-ixhash-perl libtumbler-1-0 libunique-1.0-0 libvte-common libvte9 libwv-1.2-4 libxfce4ui-1-0 libxfce4ui-utils libxfce4util-bin libxfce4util-common libxfce4util6 libxfcegui4-4 libxfconf-0-2 libxml-parser-perl libxml-twig-perl libxml-xpath-perl lightdm-gtk-greeter link-grammar-dictionaries-en m4 orage parole pastebinit pavucontrol pidgin pidgin-data pidgin-libnotify pidgin-microblog pidgin-otr plymouth-theme-xubuntu-logo plymouth-theme-xubuntu-text python-configobj rarian-compat ristretto screensaver-default-images scrollkeeper shimmer-themes system-tools-backends tcl8.5 thunar thunar-archive-plugin thunar-data thunar-media-tags-plugin thunar-volman tumbler tumbler-common xbrlapi xchat xchat-common xfburn xfce-keyboard-shortcuts xfce4-appfinder xfce4-cpugraph-plugin xfce4-dict xfce4-indicator-plugin xfce4-mailwatch-plugin xfce4-netload-plugin xfce4-notes xfce4-notes-plugin xfce4-notifyd xfce4-panel xfce4-places-plugin xfce4-power-manager xfce4-power-manager-data xfce4-quicklauncher-plugin xfce4-screenshooter xfce4-session xfce4-settings xfce4-systemload-plugin xfce4-taskmanager xfce4-terminal xfce4-verve-plugin xfce4-volumed xfce4-weather-plugin xfce4-xkb-plugin xfconf xfdesktop4 xfdesktop4-data xfwm4 xscreensaver xscreensaver-data xscreensaver-gl xubuntu-artwork xubuntu-default-settings xubuntu-desktop xubuntu-docs xubuntu-icon-theme xubuntu-wallpapers && sudo apt-get install --reinstall ubuntu-desktop
and then reboot.
It should remove all the Xubuntu related stuff and then reinstall anything that might be missing that Unity needs.


text:
Q: How to Configure a Spring Boot CXF Configuration with more that one service wsdl I have the challenge that I have a WSDL file with more that one service definiton inside
----- Customer WSDL file, can not change it ----
  <service name="DocumentOperationService">
    <port name="DocumentOperationPort" binding="tns:DocumentOperationBinding">
      <soap:address location="REPLACE_WITH_ACTUAL_URL" />
    </port>
  </service>

  <service name="PermissionEvaluatorService">
    <port name="PermissionEvaluatorPort" binding="tns:PermissionEvaluatorBinding">
      <soap:address location="REPLACE_WITH_ACTUAL_URL" />
    </port>
  </service>

  <service name="ConfigurationResolverService">
    <port name="ConfigurationResolverPort" binding="tns:ConfigurationResolverBinding">
      <soap:address location="REPLACE_WITH_ACTUAL_URL" />
    </port>
  </service>
------

How can I configure the Spring Configuration Class
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebServiceConfiguration {
...
    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), dmsPortService());

        // CXF JAX-WS implementation relies on the correct ServiceName as QName-Object with
        // the name-Attribute´s text <wsdl:service name="Weather"> and the targetNamespace
        // "http://www.codecentric.de/namespace/weatherservice/"
        // Also the WSDLLocation must be set
        endpoint.setServiceName(dmsOperationService().getServiceName());
        endpoint.setWsdlLocation(dmsOperationService().getWSDLDocumentLocation().toString());
//        endpoint.setWsdlLocation("classpath:/service-api-definition/journalexportservice.wsdl");
        endpoint.publish("/DocumentOperation");
        return endpoint;
    }

    @Bean
    public DocumentOperationService dmsOperationService() {
        // Needed for correct ServiceName & WSDLLocation to publish contract first incl. original WSDL
        return new DocumentOperationService();
    }

That all 3 Services are loaded.
In the moment I can only load one Service, I could not find any example how this could be done.
I triad with 3 config files, but then only the last is active, and how to configure 3 services in the same config file I could not figure out.

A: You might want to take a look at this tutorial describing your exact use case with exactly your stack.
In short:

*

*Your Configuration Bean needs to provide a ServletRegistrationBean with a cxfServlet, a SpringBus and an Endpoint. (Pretty much like your posted code. Juding from the comments it might even be from this very tutorial)

*Your Endpoint should point to the overall wdsl location

*Then you need to implement a Service that encomapsses all of your intended webservices

*In this service you need one method per webservice


text:
Q: How to set .htaccess for Vue Router createWebHistory() when the Vue app is on a WordPress page? We have a WordPress website, and one of the pages contains a Vue SPA ( /admin ). Everything works correctly unless you try to go directly to one of the routes within the SPA ( /admin/billing ). This gives a 404 error, since the page doesn't actually exist.
How can I keep the default WordPress routing for all pages except /admin, and have Vue Router handle the routing correctly when e.g. /admin/billing is loaded? I'm not super well versed with .htaccess, but I've spent a good amount of time researching this and have tried a number solutions. Any help would be greatly appreciated!
Here are a few solutions I've tried:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/admin/(.+)
RewriteRule . /index.php [L]
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^admin.* admin/index.php [L]
RewriteRule . /index.php [L]
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /admin
RewriteRule ^admin/index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /admin/index.php [L]
</IfModule>


text:
Q: Include  in GPX when writing from ogr2ogr http://www.gdal.org/drv_gpx.html seems to indicate that ogr2ogr should be able to write <link>[1] elements into a GPX file, however when using ogr2ogr to convert from PostGIS to GPX, I get the message,
Field of name 'link_href' is not supported in GPX schema. Use GPX_USE_EXTENSIONS creation option to allow use of the <extensions> element.

I've tried naming the field, link, href, link_href and link0_href, but none work. Any hints?
[1] http://www.topografix.com/GPX/1/1/#type_linkType
Update: Looking at the sources http://sources.debian.net/src/gdal/1.10.1%2Bdfsg-8/ogr/ogrsf_frmts/gpx/ogrgpxlayer.cpp/ it doesn't seem like it supports writing  elements, only reading, is this correct?


text:
Q: React state variable not updating within fetch call So I am trying to make a react component which calls an API and displays that data in a table. The problem is that when I call the api with fetch, it does not update the d state, but if I print the the data in the fetch call to console, it does indeed appear, it just isn't setting the d state to that data coming from the call. When print d to the console log it says null. I have fetched data from the same API in other parts of my code in the same way as below and works fine but I don't know why it isn't working in this case. I have tried many things like having the d state in the dependency array or just removing that array all together.
const UnusualTable = () => {
  const [d, setD] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    if(!d) {
      fetch(api_url)
      .then((response) => response.json())
      .then((data) => setD(data))
      .then(console.log(d));
    }
    setLoading(false);
  }, []);
  return (
    <Grommet full theme={grommet} themeMode="dark">
      { loading != true ? (
       <Box>
          <Table align="center" margin="small">
.
.
.
   );
}


text:
Q: How to add a blank new row to WPF DataGrid automatically when user start editing current row I have a DataGrid bind with ObservableCollection<MydataObject> MyDatalist With all the default settings, if user change the focus from the DataGrid (e.g. clicked a button) while editing a cell, all the data showing in the DataGrid includes the one the user is editing are stored to MyDatalist, this is great, but the user need to hit "Tab" (while in the last cell) or "Enter" to create a new row.
I want the DataGrid to generate a new row automatically when user start editing any cell of the last row. I have tried the CurrentCellChanged event and I can have the new row automatically created by doing this:
void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
{
     dataGrid1.CommitEdit();
}

However, with this implemented, if user change the focus from the DataGrid (e.g. clicked a button) while editing a cell, the one that the user is editing is not stored to MyDatalist, How can I have this feature back with the new row automatically added?

A: OK here is a Binding.UpdateSourceTrigger Property set this solved my problem:
Binding="{Binding Path=field1, UpdateSourceTrigger=PropertyChanged}"


text:
Q: Cucumber-Capybara: save_screenshot(path, full: true) is not capturing the full browser? I'm using the latest Chrome browser, Version 57.0.2987.133 (64-bit), with the latest chromedriver v2.29 (although I've tried with Chrome 56 and chromedriver 2.27 as well) and I've got a problem where I am not able to capture the full browser when a test fails.
This is the code I've got on my env.rb file:
Capybara::Screenshot.register_driver(:chrome) do |driver, path|
  driver.browser.save_screenshot(path, full: true)
end

However, the screenshots I am getting are just a partial part, what I can see on the screen rather than the complete browser.
Any idea if I'm doing something wrong or if I can try something different?
Thank you!

A: Since you're using chrome, I assume you're using the selenium driver (selenium-webdriver).  The selenium driver doesn't support any options being passed to save_screenshot, and passing options to  page.driver.screenshot -https://github.com/SeleniumHQ/selenium/blob/master/rb/lib/selenium/webdriver/common/driver_extensions/takes_screenshot.rb#L34 - will raise a too many arguments error (which in your case I assume the capybara_screenshot gem catches and ignores) and not save a screenshot.  If instead you call driver.save_screenshot(path, full: true) it will take a shot, but any options passed will be ignored since they aren't supported.  Additionally, since the WebDriver spec is defined as taking a shot of the viewport (visible window), I would not expect selenium to support full screen shots any time soon.
If you are using selenium for your screenshots and you want larger your only option is to increase the window size before taking your screenshot.


text:
Q: What is the difference between SGD and back-propagation? Can you please tell me the difference between Stochastic Gradient Descent (SGD) and back-propagation?

A: [Quick Answer]
TL;DR

*

*Backpropagation is a trick to find the derivative of the error for every parameter W[i]

*Stochastic Gradient Descent (SGD) updates W[i]

A: Stochastic gradient descent (SGD) is an optimization method used e.g. to minimize a loss function.
In the SGD, you use 1 example, at each iteration, to update the weights of your model, depending on the error due to this example, instead of using the average of the errors of all examples (as in "simple" gradient descent), at each iteration. To do so, SGD needs to compute the "gradient of your model".
Backpropagation is an efficient technique to compute this "gradient" that SGD uses.

A: Backpropagation is an efficient method of computing gradients in directed graphs of computations, such as neural networks. This is not a learning method, but rather a nice computational trick which is often used in learning methods. This is actually a simple implementation of chain rule of derivatives, which simply gives you the ability to compute all required partial derivatives in linear time in terms of the graph size (while naive gradient computations would scale exponentially with depth).
SGD is one of many optimization methods, namely first order optimizer, meaning, that it is based on analysis of the gradient of the objective. Consequently, in terms of neural networks it is often applied together with backprop to make efficient updates. You could also apply SGD to gradients obtained in a different way (from sampling, numerical approximators etc.). Symmetrically you can use other optimization techniques with backprop as well, everything that can use gradient/jacobian.
This common misconception comes from the fact, that for simplicity people sometimes say "trained with backprop", what actually means (if they do not specify optimizer) "trained with SGD using backprop as a gradient computing technique". Also, in old textbooks you can find things like "delta rule" and other a bit confusing terms, which describe exactly the same thing (as neural network community was for a long time a bit independent from general optimization community).
Thus you have two layers of abstraction:

*

*gradient computation - where backprop comes to play

*optimization level - where techniques like SGD, Adam, Rprop, BFGS etc. come into play, which (if they are first order or higher) use gradient computed above

A: Back-propagation is just a method for calculating multi-variable derivatives of your model, whereas SGD is the method of locating the minimum of your loss/cost function.


text:
Q: How to Have a Discord Bot Select a Channel Okay so I was wondering if anyone knew how I'd go about having a bot select a channel. I'm creating a multi-server bot for discord, and was wondering how I'd go about with selecting a role/channel with a command. For example, I have this code that auto roles members:
client.on("guildMemberAdd", member => {

    //Change "RoleName" tto the role yoou want to give them
    var role = member.guild.roles.find ("name", "RoleName")
    member.addRole (role)
        if (role = null)
        return;
})

Now, obviously not every server is going to have their member role as, "RoleName," so what I was wondering is, how would I make the bot choose the role they wish to be given to new members with a command. So if they were to do: "cb!autorole set Member" it would then make that role be what they automatically give new members, but if someone in a different server did "cb!autorole set Newbie" it would make it that servers auto role, withoout changing or adding a different servers autorole.
And same with channels. Example: "cb!welcome set #welcome" it'd set that servers welcome message channel, without changing or adding a different servers selected channel.
I'd also like to know how to unset them as well. Example: "cb!unset welcome" and "cb!unset autorole" and of course it'd only unset that server's stuff.
If it's too long to explain but you know a link, please do share it with me.
I'm sorry if this is confusing, if you have any questions on what I mean just comment. I'm new to coding and such so I probably got some of the terminology wrong.
Thank you for taking the time to read this.

A: You should use a database to set the channel (for example the channel id / role id) and then you can do:
var chan = member.guild.channels.get(channelid).catch(console.error);
if(chan) chan.send(`welcome ${member} to the server`);

var role = member.guild.roles.get(roleid).catch(console.error);
if(role) member.addRole(role);

If you're not really experienced with databases I suggest quick.db. Then you can do
const db = require("quick.db");
client.on("message", message => {
    const args = message.content.slice(prefix.length).trim().split(/ +/g);
    const command = args.shift().toLowerCase();
    if(command == "setautorole"){
        let roleName = args.slice(0).join(" ");
        let role = message.guild.roles.find(role => role.name == roleName).catch(message.reply("Couldn't find that role")
        db.set(`autorole_${message.guild.id}`, role.id)
    }
    if(command == "unsetautorole"){
        db.delete(`autorole_${message.guild.id})
    }
    if(command == "setwelcomechannel"){
        let channelName = args.slice(0).join(" ");
        let channel = message.guild.channels.find(channel => channel.name == channelName).catch(message.reply("Couldn't find that channel")
        db.set(`welcomechannel_${message.guild.id}`, channel.id)
    }
    if(command == "unsetwelcomechannel"){
        db.delete(`welcomechannel_${message.guild.id})
    }
})
client.on("guildMemberAdd", member => {
    let roleId = db.get(`autorole_${member.guild.id}`);
    if(roleId) member.addRole(roleId).catch(console.error);
    let channelId = db.get(`welcomechannel_${member.guild.id}`);
    if(channelId) channel = member.guild.channels.get(channelId).catch(console.error);
    if(channel) channel.send("x")
})

setautorole
setwelcomechannel
Of course, you can modify this to use another way to save it.


text:
Q: How to hide response from dbus-send (print-reply)? I have following script for playing/pausing current song on spotify. However it prints output to the terminal. When I remove --print-reply \ part it doesn't work despite documentation shows it is optional. How to hide the response from this command?
dbus-send \
    --print-reply \
    --dest=org.mpris.MediaPlayer2.spotify \
    /org/mpris/MediaPlayer2 \
    org.mpris.MediaPlayer2.Player.PlayPause

Example output:
method return time=1588176965.415166 sender=:1.189 -> destination=:1.193 serial=42 reply_serial=2

A: Redirect all output to /dev/null:
<dbus-send etc> 2>/dev/null
Or if you still want to see any errors, use:
<dbus-send etc> 1>/dev/null
Full command:
dbus-send \
    --print-reply \
    --dest=org.mpris.MediaPlayer2.spotify \
    /org/mpris/MediaPlayer2 \
    org.mpris.MediaPlayer2.Player.PlayPause 1>/dev/null

A: I was asking a similar question.  Actually there is a post from Simon McVittie, For original post see Fix dbus-send not returning an error exit code in case an error occurred and --print-reply is not set
The answer from Simon, which I have copy&pasted:
Question:

Fix dbus-send not returning an error exit code in case an error occured
and --print-reply is not set

Answer:

This is an incompatible change to dbus-send's behaviour. Previously,
it could be used in two modes:

*

*no special options: send message (method call or signal), don't wait (analogous to dbus_connection_send())

*--print-reply: send message, wait (makes no sense for signals), process reply (analogous to
dbus_connection_send_with_reply_and_block())

This change makes the first mode impossible. In particular, if we send
a signal rather than a method call, we are not going to get a reply,
so we'd just block until the timeout and then fail every time.
Making --print-reply the default (at least for method calls) would
have been better, but we're about 15 years too late to design the
dbus-send CLI, and I don't think it's a good idea to be changing it
incompatibly now.
I think "gdbus call" is a better CLI for method calls (it's missing a
--no-wait option, but that's quite a rare thing to want in practice), and "gdbus emit" is a better CLI for signals. In particular, the
design of the gdbus(1) CLI is in terms of operations that make sense
in the high-level model of D-Bus that we encourage people to think in,
whereas the design of dbus-send is down at the level of
message-passing.
One better solution than this would be to change the man page to say
something like this:
""" To call a method, always use --print-reply, unless you are
deliberately not waiting to see whether the method succeeded.
--print-reply is not the default for historical reasons, but it should have been.
To emit a signal, use --type=signal and do not use --print-reply. """
Perhaps another better solution would be "dbus-call" and "dbus-emit"
tools that closely resemble dbus-send but with more sensible defaults

*

*but "gdbus call" and "gdbus emit" are basically already those tools, so perhaps implementing them would be a waste of time.

::: doc/dbus-send.1.xml.in @@ +156,5 @@

*

*EXIT STATUS

*

*dbus-send

*exits with status 0 on success and status 1 in case of errors.

*In the error case a related message will be printed to stderr.

This is still useful documentation without the behaviour change, but
if --print-reply isn't used, "the service sent back an error reply" is
not an error that is (or can be) detected. It could perhaps become
something like this:
""" If the --print-reply option is used, dbus-send exits with status 0
after a successful reply, or a nonzero status otherwise (if connecting
to the bus fails, if it receives an error reply, or if the timeout is
reached).
If the --print-reply option is not used, dbus-send exits with status 0
when the message has been successfully sent, or a nonzero status
otherwise (for example if connecting to the bus fails). In this case
dbus-send does not wait for the message to be processed, so it cannot
report an error reply.
On failure, a diagnostic message is printed to stderr. """


text:
Q: What's wrong with my showChar method? Simple program intro to methods //Ch5a Program
'I'm supposed to use a method to display a certain letter of a word input by the user.
I need to use showChar.
There aren't really any obvious errors that I can see and I've worked on it for a couple hours.'
import javax.swing.JOptionPane;
public class Ch5a {
    public static void main(String[] args){
        String inputString = JOptionPane.showInputDialog("What word would you like to analyze?");
        String inputNumberString = JOptionPane.showInputDialog("What letter would you like to see? (Eg: For the second letter of 'dog', input 2)");
        int inputNo;
        inputNo = Integer.parseInt(inputNumberString);
    /**
     At this point, i have an input number from the user(inputNo) and I have a word from the user(inputString).
     I then print the inputNo for testing.
     */
        System.out.println(inputNo);
    //time to call the method.
        char answer;
    //I declare the character answer.
        answer = showChar(inputString, inputNo);
    //i set it equal to the result of the method.
        System.out.println("The " + inputString +" number character in " + inputNo + " is" + answer);

}
    public static char showChar(String inputString, int inputNo){
     //local variable
        char result;
        result = showChar(inputString, inputNo); //user's chosen character
    //returning whatever i want in place of the method call(in this case, "result")
        return result;
    }
}

A: I think you want something like this:
public static char showChar(String inputString, int inputNo){
    char result;
    result = inputString.charAt(inputNo -1);   // since index starts at 0
    return result;
}

A: have a look at String.charAt() method.  I think you want something more like:
    public static char showChar(String inputString, int inputNo){

       char result;

       result = inputString.charAt(inputNo - 1);

       return result;
    }

or to simplify:
    public static char showChar(String inputString, int inputNo){
       return inputString.charAt(inputNo - 1);
    }

see http://www.tutorialspoint.com/java/java_string_charat.htm for more info

A:  public static char showChar(String inputString, int inputNo){
    inputNo = inputNo-1; // first letter in String has position 0
    if(inputNo<0 || inputNo>=inputString.length())
    {
        // if the number is out of Bounds
        return ' ';
    }
return inputString.charAt(inputNo);
}


text:
Q: Using string lengths specified in element to check another element I am writing a stylesheet to create a report on which text strings in a file are longer than allowed. (As far as know this is not possible to do with a schema 1.0.)
For each Text I am checking that the length of the string contained in the Value element does not exceed what is specified in the Info element for that particular text.
However, I have found out that my maxLength variable cannot be used as a global variable. So even though I am able to get the info about the max lengths I am not able to use those values in my checks.
I could use some advice on how to best re-design my stylesheet.
My XSL:
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <!-- Message template -->
    <xsl:template match="Text" >
        <xsl:variable name="messageNumber" select="@Id"/>
        <xsl:variable name="maxLength"/>

        <xsl:choose>
            <xsl:when test="(normalize-space(Info)='')">
                <xsl:variable name="maxLength" select="40" />
                Message <xsl:value-of select="$messageNumber"/> is missing Max Length. Using <xsl:value-of select="$maxLength"/>
            </xsl:when>
            <xsl:when test="contains(Info,'char')">
                <xsl:variable name="maxLength1" select="substring-before(Info, 'char')"/>
                <xsl:variable name="maxLength" select="substring($maxLength1,  string-length($maxLength1) - 2)" />
            </xsl:when>
            <xsl:otherwise></xsl:otherwise>
        </xsl:choose>

        <xsl:choose>
            <xsl:when test="string-length(Value) > $maxLength">
                Message <xsl:value-of select="$messageNumber"/> too long: <xsl:value-of select="string-length(Value)"/> chars (max is <xsl:value-of select="$maxLength"/>)
            </xsl:when>
            <xsl:otherwise>
                Message <xsl:value-of select="$messageNumber"/> is OK: <xsl:value-of select="string-length(Value)"/> chars (max is <xsl:value-of select="$maxLength"/>)
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

My XML:
<?xml version="1.0" ?>
<Texts>
  <Text Id="1">
    <Value>OK</Value>
    <Info>Text length for button, max 6 chars</Info>
  </Text>
  <Text Id="2">
    <Value>Cancel</Value>
    <Info>Button, Maximum length 9 chars</Info>
  </Text>
  <Text Id="3">
    <Value>Continue</Value>
    <Info>This text cannot be longer than 14 characters. Use short form if required.</Info>
  </Text>
  <Text Id="4">
    <Value>Twinkle, twinkle little star</Value>
    <Info>Title text, Maximum length 14 chars.</Info>
  </Text>
  <Text Id="5">
    <Value>Twinkle, twinkle little star again</Value>
    <Info></Info>
  </Text>
</Texts>

The desired output is something like this:
Message 1 is OK: 2 chars (max is 6)
Message 2 is OK: 6 chars (max is 9)
Message 3 is OK: 8 chars (max is 14)
Message 4 too long: 28 chars (max is 14)
Message 5 is missing Max Length. Using 40
Message 5 is OK: 34 chars (max is 40)

A: Variables in XSLT are immutable, and cannot be changed once set. What your XSLT is doing is initialising a new variable called maxLength within the xsl:when statements, which is local in scope to that block (It is said to "shadow" the main variable).
What you need to do have separate statements to initialise maxLength and to display the message.
Try this XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <!-- Message template -->
    <xsl:template match="Text" >
        <xsl:variable name="messageNumber" select="@Id"/>

        <xsl:variable name="maxLength">
            <xsl:choose>
                <xsl:when test="(normalize-space(Info)='')">40</xsl:when>
                <xsl:when test="contains(Info,'char')">
                    <xsl:variable name="maxLength1" select="substring-before(Info, 'char')"/>
                    <xsl:value-of select="substring($maxLength1,  string-length($maxLength1) - 2)" />
                </xsl:when>
            </xsl:choose>
        </xsl:variable>

        <xsl:if test="(normalize-space(Info)='')">
            Message <xsl:value-of select="$messageNumber"/> is missing Max Length. Using <xsl:value-of select="$maxLength"/>
        </xsl:if>

        <xsl:choose>
            <xsl:when test="string-length(Value) > $maxLength">
                Message <xsl:value-of select="$messageNumber"/> too long: <xsl:value-of select="string-length(Value)"/> chars (max is <xsl:value-of select="$maxLength"/>)
            </xsl:when>
            <xsl:otherwise>
                Message <xsl:value-of select="$messageNumber"/> is OK: <xsl:value-of select="string-length(Value)"/> chars (max is <xsl:value-of select="$maxLength"/>)
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>


text:
Q: format numbers in reference so they sort correctly This is a followup to question list of occurences of references. In the MWE below the index lists the Goals in alphabetic order where numeric is needed for the second token:

The solution I found (on SE - sorry I lost the link) for the chapter and section numbers for the subsidiary indexing doesn't seem to work for the main headings. I tried a few others, to no avail.
Edit: the solution to convert outcome of reference to regular number looks as if it ought to work but I tried something like that and it failed.
\documentclass[12pt]{book}

\usepackage{amsthm}
\usepackage{environ}
\usepackage{imakeidx}
\usepackage{refcount}
\usepackage{hyperref}

\makeindex[intoc]
\makeindex[name=goals,title=Goal References,columns=1,intoc]

\newcommand{\gref}[1]{%
   [Goal~\ref{goal:#1}]
   \index[goals]{Goal~\getrefnumber{goal:#1}!Section
    \ifnum\value{chapter}<10 0\fi\arabic{chapter}.%
    \ifnum\value{section}<10 0\fi\arabic{section}}
}

\makeatletter
\newcommand\l@goal[1]{%
  \addpenalty{\@highpenalty}%
  \vskip \z@ \@plus \p@
  \begingroup
  \parindent\z@
  \rightskip\@pnumwidth
  \parfillskip-\@pnumwidth
  \leavevmode #1\nobreak\hfil\nobreak\null\par
  \penalty\@highpenalty
  \endgroup}

\newcommand{\egregaddtocontents}[1]{%
  \addtocontents{toc}{\protect\l@goal{#1}}}

% arrange goal numbering by chapter
\newtheorem{Goal}{Goal}[chapter]

% define a shorthand to be able to get at \BODY with \expandafter
\newcommand\indexgoal[1]{\goalindex[goals]{Goal~\theGoal! #1}}

% save a copy of \index
\let\goalindex\index
\NewEnviron{goal}[1]{%
\begin{Goal}
   \label{goal:#1}%
   % here we neutralize \index so that it won't do damages
   \begingroup
   \renewcommand\index[2][]{}%
   % but the main command uses \goalindex, so it's safe
   \expandafter\indexgoal\expandafter{\BODY}%
   \egregaddtocontents{\BODY}
   \endgroup
   %{\em label:} #1 %comment in/out to restore/suppress printing label
   \normalfont{}\noindent
   \BODY
}
[\end{Goal}]
\makeatother

\newenvironment{goals}
{%
{\textbf Chapter goals:}
\egregaddtocontents{Chapter goals:}
}
{}

\begin{document}

\tableofcontents{}

\setcounter{chapter}{1}
\chapter{TWO}

\tracingmacros=1

\begin{goals}

\begin{goal}{twofirst}
learn more \LaTeX
\end{goal}

\end{goals}

\tracingmacros=0

\begin{goal}{twosecond}
spend time on content, not \LaTeX
\end{goal}

\section{two-one}
stuff\index{stuff}
Reference to a chapter 11 goal: \gref{elevenfirst}

\setcounter{chapter}{10}
\chapter{ELEVEN}

\begin{goal}{elevenfirst}
have fun in any case\index{fun}
\end{goal}

Chapter contents here, referring to some goals:

\setcounter{section}{1}

\section{whatever}

Reference to a chapter 2 goal: \gref{twosecond}

Reference to a chapter 11 goal: \gref{elevenfirst}

\setcounter{section}{10}
\section{another}

Second reference to a chapter 2 goal: \gref{twofirst}

\printindex[goals]
\printindex

\end{document}

A: You have to format the entries in such a way that the alphabetization is correct. So I use a trick:
\documentclass[12pt]{book}

\usepackage{amsthm}
\usepackage{environ}
\usepackage{imakeidx}
\usepackage{refcount}
\usepackage{hyperref}

\makeindex[intoc]
\makeindex[name=goals,title=Goal References,columns=1,intoc]

\makeatletter
\newcommand{\gref}[1]{%
   [Goal~\ref{goal:#1}]
   \edef\@goal@number{\getrefnumber{goal:#1}}%
   \edef\@the@section{\thesection}%
   \index[goals]{Goal~\expandafter\sortgref\@goal@number.0\sortgref!%
   \expandafter\sortgref\@the@section.0\sortgref @%
   Section~\thesection}%
}
\def\sortgref#1.#2#3\sortgref{%
  \ignoresort{\ifnum#1<10 0\fi#1.\ifnum#2<10 0\fi#2}#1.#2%
}
\protected\def\ignoresort#1{}

\newcommand\l@goal[1]{%
  \addpenalty{\@highpenalty}%
  \vskip \z@ \@plus \p@
  \begingroup
  \parindent\z@
  \rightskip\@pnumwidth
  \parfillskip-\@pnumwidth
  \leavevmode #1\nobreak\hfil\nobreak\null\par
  \penalty\@highpenalty
  \endgroup}

\newcommand{\egregaddtocontents}[1]{%
  \addtocontents{toc}{\protect\l@goal{#1}}}

% arrange goal numbering by chapter
\newtheorem{Goal}{Goal}[chapter]

% define a shorthand to be able to get at \BODY with \expandafter
\newcommand\indexgoal[1]{\edef\@goal@number{\theGoal}%
  \goalindex[goals]{Goal~\expandafter\sortgref\@goal@number.0\sortgref! #1}}

% save a copy of \index
\let\goalindex\index
\NewEnviron{goal}[1]{%
\begin{Goal}
   \label{goal:#1}%
   % here we neutralize \index so that it won't do damages
   \begingroup
   \renewcommand\index[2][]{}%
   % but the main command uses \goalindex, so it's safe
   \expandafter\indexgoal\expandafter{\BODY}%
   \egregaddtocontents{\BODY}
   \endgroup
   %{\em label:} #1 %comment in/out to restore/suppress printing label
   \normalfont{}\noindent
   \BODY
}
[\end{Goal}]
\makeatother

\newenvironment{goals}
{%
{\textbf Chapter goals:}
\egregaddtocontents{Chapter goals:}
}
{}

\begin{document}

\tableofcontents{}

\setcounter{chapter}{1}
\chapter{TWO}

\tracingmacros=1

\begin{goals}

\begin{goal}{twofirst}
learn more \LaTeX
\end{goal}

\end{goals}

\tracingmacros=0

\begin{goal}{twosecond}
spend time on content, not \LaTeX
\end{goal}

\section{two-one}
stuff\index{stuff}
Reference to a chapter 11 goal: \gref{elevenfirst}

\setcounter{chapter}{10}
\chapter{ELEVEN}

\begin{goal}{elevenfirst}
have fun in any case\index{fun}
\end{goal}

Chapter contents here, referring to some goals:

\setcounter{section}{1}

\section{whatever}

Reference to a chapter 2 goal: \gref{twosecond}

Reference to a chapter 11 goal: \gref{elevenfirst}

\setcounter{section}{10}
\section{another}

Second reference to a chapter 2 goal: \gref{twofirst}

\printindex[goals]
\printindex

\end{document}

The in goals.idx you'll find
\indexentry{Goal\nobreakspace  {}\ignoresort {02.01}2.1! learn more \LaTeX  |hyperpage}{3}
\indexentry{Goal\nobreakspace  {}\ignoresort {02.02}2.2! spend time on content, not \LaTeX  |hyperpage}{3}
\indexentry{Goal\nobreakspace  {}\ignoresort {11.01}11.1!\ignoresort {02.01}2.1@Section\nobreakspace  {}2.1|hyperpage}{3}
\indexentry{Goal\nobreakspace  {}\ignoresort {11.01}11.1! have fun in any case\index {fun}|hyperpage}{5}
\indexentry{Goal\nobreakspace  {}\ignoresort {02.02}2.2!\ignoresort {11.02}11.2@Section\nobreakspace  {}11.2|hyperpage}{5}
\indexentry{Goal\nobreakspace  {}\ignoresort {11.01}11.1!\ignoresort {11.02}11.2@Section\nobreakspace  {}11.2|hyperpage}{5}
\indexentry{Goal\nobreakspace  {}\ignoresort {02.01}2.1!\ignoresort {11.01}11.1@Section\nobreakspace  {}11.11|hyperpage}{5}

so that the sorting will be done correctly: here is goals.ind
\begin{theindex}

  \item Goal\nobreakspace  {}\ignoresort {02.01}2.1
    \subitem Section\nobreakspace  {}11.11, \hyperpage{5}
    \subitem  learn more \LaTeX  , \hyperpage{3}
  \item Goal\nobreakspace  {}\ignoresort {02.02}2.2
    \subitem Section\nobreakspace  {}11.2, \hyperpage{5}
    \subitem  spend time on content, not \LaTeX  , \hyperpage{3}
  \item Goal\nobreakspace  {}\ignoresort {11.01}11.1
    \subitem Section\nobreakspace  {}2.1, \hyperpage{3}
    \subitem Section\nobreakspace  {}11.2, \hyperpage{5}
    \subitem  have fun in any case\index {fun}, \hyperpage{5}

\end{theindex}

The \ignoresort macro does nothing with its argument, so the entries will be printed without padding zeros.


text:
Q: How do I disable a button in a form? I want the signup button to be disabled whenever the form is complete.
<form [formGroup]="service.formModelInstrumexts" autocomplete="off" (submit)="onSubmit()"
  style="background-color: #0067b8 !important; margin-top: 25px; margin-left: 600px; margin-right: 600px;">

    اضافه کردن ساز

    <select   id="ddl" style="width:200px; margin-right: 1%; margin-bottom: 10px; border-radius: 0px;" dir="rtl"
      class="custom-select custom-select-sm">
      <option> لطفا نوع ساز را انتخاب نمایید</option>
      <option *ngFor="let item of type; let i = index" style="color: black;" (click)="test(item.id)" >{{item.name}}
      </option>
    </select>

      نام
      <input style="width: 40%; margin-left: 60%; border-radius: 0px;" class="form-control" formControlName="Name">

      توضیحات
      <textarea [(ngModel)]="name"  style="direction: rtl; color: rgb(3, 0, 0); border-radius: 0px;" class="form-control" formControlName="Comment"
        aria-label="With textarea"></textarea>

      <app-upload style=" width: 100px; "
        (onUploadFinished)="uploadFinished($event)"></app-upload>

        <button style="width: 100px; color: #0067b8; background-color: #fff; border-color: transparent; border-radius: 0px;margin-left: 8px;" type="submit" class="btn btn-lg btn-block"
          [disabled]="!service.formModelInstrumexts.valid" >ثبت
        </button>

</form>

A: Your submit button will be dependent on form Validity.
[disabled]= "!service.formModelInstrumexts.valid"

Another way would be template reference variables
<form #myForm [formGroup]="service.formModelInstrumexts"  (submit)="onSubmit()">

then
[disabled]= "!myForm.valid"

A: One thing worth to mention is case when you want to disable eg. input with directive formControl or formControlName, then Angular then inform you about it as warning in console:

  It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
  when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
  you. We recommend using this approach to avoid 'changed after checked' errors.

  Example:
  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });

Another approach would be to disable/enable certain button or control inside ts code:
form: FormGroup;

this.form = new FormGroup({
  someControl: new FormControl('', Validators.required)
});

this.form.statusChanges.subscribe(status => {
  if (status === 'VALID') {
    this.form.controls.someControl.disable({emitEvent: false}); // Prevent circular status change notification
  } else {
    this.form.controls.someControl.enable({emitEvent: false}); // Prevent circular status change notification
  }
});

setTimeout(() => this.form.controls.someControl.setValue('123'), 1000);
setTimeout(() => this.form.controls.someControl.setValue(''), 2000);


text:
Q: Position of verbals In the first sentence, We move the infinitive to the end of the sentence and place a prepatory object after verb. But when we use gerund, we keep it after verb as in second sentence . I was wondering reason of it , could you please explain to me ?
1-I find it hard to live in a city.
2-I find living in a city stresfull.

A: "I find it interesting reading that question" and please consider: "I find it stresfull living in a city"


text:
Q: Problem with Zoho Invocing API {"code":1038,"message":"JSON is not well formed»} I am struggling with the invoicing API.
So I am using the following Python script to create invoices, however it appears to be erroneous:
import urllib.parse
import requests
import json
data = {     "customer_id": 982000000567001, "contact_persons": [ "982000000870911", "982000000870915" ], "invoice_number": "INV-00003", "reference_number": " ", "place_of_supply": "TN", "gst_treatment": "business_gst", "gst_no": "22AAAAA0000A1Z5", "template_id": 982000000000143, "date": "2013-11-17", "payment_terms": 15, "payment_terms_label": "Net 15", "due_date": "2013-12-03", "discount": 0, "is_discount_before_tax": "true", "discount_type": "item_level", "is_inclusive_tax": "false", "exchange_rate": 1, "recurring_invoice_id": " ", "invoiced_estimate_id": " ", "salesperson_name": " ", "custom_fields": [ { "label": "Record Number", "value": 23 } ], "project_id": " ", "line_items": [ { "item_id": 982000000030049, "project_id": " ", "time_entry_ids": [ {} ], "expense_id": " ", "name": "Hard Drive", "product_type": "goods", "hsn_or_sac": 80540, "item_order": 1, "rate": 120, "quantity": 1, "unit": " ", "discount": 0, "tax_id": 982000000557028, "tax_exemption_id": 11149000000061054, "tax_name": "VAT", "tax_type": "tax", "tax_percentage": 12.5, "item_total": 120 } ], "payment_options": { "payment_gateways": [ { "configured": "true", "additional_field1": "standard", "gateway_name": "paypal" } ] }, "allow_partial_payments": "true", "custom_body": " ", "custom_subject": " ", "notes": "Looking forward for your business.", "terms": "Terms & Conditions apply", "shipping_charge": 0, "adjustment": 0, "adjustment_description": " ", "reason": " ", "tax_authority_id": 11149000000061052, "tax_exemption_id": 11149000000061054 }
headers = {"content-type": "application/x-www-form-urlencoded;charset=UTF-8","Authorization":"Zoho-authtoken <MY_TOKEN>","X-com-zoho-invoice-organizationid": "<MY_ORGANIZATION_ID>"}
url = "https://invoice.zoho.com/api/v3/invoices"
r = requests.post(url, data=json.dumps(data), headers=headers)

print(r.json())

What I get is: {"code":1038,"message":"JSON is not well formed»}
Can you help me and tell me how should I encode my data?

A: As pointed out by Klaus on your question the issue here is likely the 'ContentType' header you've set. I had a similar issue with Zoho's Subscription API but resolved it with the following:
import requests
import json
from pprint import pprint

# This Script Will Need To Be Updated to new OAUTH SOON
ZOHO_AUTHTOKEN = 'PUTYOURAUTHTOKENHERE'
DUMMY_ORGANIZATION_ID = 'OrganizationIDFROMZOHO'
BASE_URL = "https://subscriptions.zoho.com/api/v1"

headers = {"Authorization": "Zoho-authtoken " + ZOHO_AUTHTOKEN}
subscription_id = '1234'
dict_data = {} #Put required data to send here
json_string = json.dumps(dict_data)
headers['ContentType'] = 'application/json'
updated_subscription_request = requests.put(BASE_URL+"/subscriptions/"+subscription_id, headers=headers, params={
    "organization_id": DUMMY_ORGANIZATION_ID}, data=json_string)

pprint(updated_subscription_request.json())


text:
Q: PHP error validation with action I am trying to create a simple form that gives the users an error on the same page if they do not put in a zip code. If they put in their zip code I want the form to go to another page. Can someone please let me know what I am doing wrong?
<?php

$errors = "";

if(isset($_GET['submit'])){

if(0 === preg_match("/\S+/", $_GET['zip']))
   $errors['zip'] = '
To proceed please enter a valid ZIP Code.
';
} else {
    die(header("Location: success.php"));
}

?>

<?php

if ($errors != "") {
    echo $errors['zip'];
}

?>

<form name="zipcodeform" id="zipcodeform" action="" method="GET">

Try your self :

            Zip Code :
            <input type="text" name="zip" id="zip" value="<?php echo $_GET['zip']; ?>"  />

            <input type="submit" name="submit"   id="submit"      value="Get Quotes >> " />

</form>

A: There are a bunch of things you should look for:

*

*Is $errors a string or an array? If it is an array, you should initialize it properly.

*Use stricter error_reporting (E_ALL). You will get a notice that $_GET['plz'] isn't set when you open the page, without having submitted the form.

*Always use {}. It's good coding style.

If you take all this into account the script should be running fine or at least you should see your mistakes. It runs fine at my place.

A: Try this,
Say your first (form.html) page is this

 ...

 <form method='get' action='proceed.php'>
   Pin code : <input type='text' name='pincode'>
 <input type='Submit'>
</form>

Then your PHP page that deals with the form(proceed.php);

 ...

<?PHP
  if($_GET['pincode']==''){
//Copy and paste the contents of body of 'form.html' with errors displayed!
   echo'<form method="get" action="proceed.php">
   Pin code : <input style="background:#FAA;" type="text" name="pincode">

To proceed please enter a valid ZIP Code.

   <input type="Submit">';
  }
</form>

A: You have multiple errors in your script. Try
<?php

$errors = array();

if(isset($_GET['submit'])){
  if( !preg_match("/\S+/", $_GET['zip']) ){
        $errors['zip'] = '
To proceed please enter a valid ZIP Code.
';
  }

  if( !empty($errors) ){
      echo $errors['zip'];
  } else {
      header("Location: success.php");
      exit();
  }

}

?>

<form name="zipcodeform" id="zipcodeform" action="" method="GET">

Try your self :

Zip Code :
<input type="text" name="zip" id="zip" value="<?php if(isset($_GET['zip'])) echo $_GET['zip']; ?>"  />

<input type="submit" name="submit"  id="submit"   value="Get Quotes >>" />

</form>


text:
Q: WebSQL Transaction Won't Run In JS Callback Functions I am using PhoneGap and jQuery Mobile. I am trying to get some JSON data from a remote location and then populate a local WebSQL database with it. Here is my JS function:
function getLocations() {

    var tx = window.openDatabase('csdistroloc', '1.0', 'Distro DB', 1000000);
    tx.transaction(function(tx) {
        tx.executeSql('DROP TABLE IF EXISTS locations'); //this line works!
        tx.executeSql('CREATE TABLE IF NOT EXISTS locations (id, name, address, postalcode, phone, category)'); //this line works!

        $.ajax({
          url: "http://mydomain.com/api.php",
          dataType: 'json',
          data: { action: "getlocations" },
          success: function(data) {
            tx.executeSql("INSERT INTO locations (id, name, address, postalcode, phone, category) VALUES (2,'cheese','232','seven',5,6)"); //this line produces an error
        }});

    }, dberror, dbsuccess);

}

Running the above function gives me an error "INVALID_STATE_ERR: DOM Exception 11" on the line noted above. It does the same thing when I am actually trying to use the returned JSON data to insert data. I have also tried the $.getJSON technique with the exact same result.
Any advice would be appreciated!

A: Although the accepted answer is correct, I would like to expand upon it because I encountered the same problem and that answer doesn't say why it doesn't work as the OP had it.
When you create a transaction in Web SQL, the transaction processing remains alive only so long as there are any statements queued up in the transaction. As soon as the pipeline of statements in the transaction dries up, the engine closes (commits) the transaction. The idea is that when the function(tx) { ... } callback runs,

*

*It executes all of the statements it need to. executeSql is asynchronous, so it returns immediately even though the statement has not yet been executed.

*It returns control back to the Web SQL engine.

At this point the engine notices that there are statements queued up and runs them to completion before closing the transaction. In your case, what happens is this:

*

*You call executeSql twice to queue up two statements.

*You request something through ajax.

*You return

The engine runs the two statements that it has queued up. The ajax request is also running asynchronously but it must access the network which is slow so it likely has not completed yet. At this point, the statement queue is empty and the Web SQL engine decides that it's time to commit and close the transaction! It has no way of knowing that there is going to be another statement coming later! By the time the ajax call returns and it attempts to execute the INSERT INTO locations, it's too late, the transaction is already closed.
The solution suggested by the accepted answer works: don't use the same transaction inside the ajax callback but create a new one. Unfortunately, it has the pitfall you would expect from using 2 transactions instead of 1: the operation is no longer atomic. That may or may not be important for your application.
If atomicity of the transaction is important for you, your only 2 recourses are:

*

*Do everything (all 3 statements) in one transaction inside the ajax callback.
This is what I recommend. I think it's very likely that waiting until after the ajax request completes before creating the table is compatible with your application requirements.

*Perform the ajax request synchronously as explained here.
I don't recommend that. Asynchronous programming in JavaScript is a good thing.
By the way, I encountered the problem in the context of Promises, in code that looked something like this:
// XXX don't do this, it doesn't work!
db.transaction(function(tx) {
    new Promise(function(resolve, reject) {
        tx.executeSql(
            "SELECT some stuff FROM table ....", [],
            function(tx, result) {
                // extract the data that are needed for
                // the next step
                var answer = result.rows.item( .... ).some_column;
                resolve(answer);
            }
        )
    }).then(function(answer) {
        tx.executeSql(
            "UPDATE something else",
            // The answer from the previous query is a parameter to this one
            [ ... , answer, .... ]
        )
    });
});

The problem is that, with promises, the chained .then() clause is not run immediately upon resolution of the original promise. It is only queued for later execution, much like the ajax request. The only difference is that, unlike the slow ajax request, the .then() clause runs almost immediately. But "almost" is not good enough: it may or may not run soon enough to slip in the next SQL statement into the queue before the transaction gets closed; accordingly, the code may or may not produce the invalid state error depending on timing and/or browser implementation.
Too bad: Promise would have been useful to use inside SQL transactions. The above pseudo-example can easily be rewritten without promises, but some use cases can greatly take advantage of chains of many .then()s as well as things like Promise.all that can make sure that an entire collection of SQL statements run in any order but all complete prior to some other statement.

A: I would first suggest not naming your database 'tx' but rather db or database. This could be a variable naming problem since both the function parameter and your database variables are called "tx"
EDIT: I had this same problem and solved it by making the query within the callback it's own transaction. Like so:
success: function(data) {
tx.transaction(function(transaction){
    transaction.executeSql("INSERT INTO locations (id, name, address, postalcode, phone, category)
VALUES (2,'cheese','232','seven',5,6)"); //now more DOM exception!
  }
}}

I think the problem is by the time the callback is fired the outer transaction has completed because webSQL's transactions are not synchronous.

A: We do have a way to lock the transaction, while you do any AJAX or other async operation. Basically before calling AJAX you need to start a dummy db operation and on success of that operation check if AJAX is done or not, and again call the same dummy operation till your AJAX is done. When AJAX is done you can now reuse the transaction object do next set of executeSQLs. This approach is thoroughly explained in this article here. (I hope someone will not delete this answer too, as someone did earlier on a similar question)
Try this approach


text:
Q: shutil moving only one file instead of many files in a directory I wrote a code which moves the files which has a substring in them.
import os
import shutil

def move():
    path = os.getcwd()
    shutil.rmtree('Animals')
    firstfolder = 'Animals'
    if not os.path.isdir(firstfolder):
        os.mkdir('Animals')

    for file in os.listdir():
        Buffalo = '1837'
        donkey = '6104'
        Chimpanzee = '9731'
        cat = '2905'
        rat = '6648'
        sheep = '3128'
        lizard = '3053'
        insect = '2681'
        dog = '3901'
        #Buffalo
        if Buffalo in file:
            secondfolder = 'Animals/Buffalo'
            thirdfolder = 'Animals/Buffalo/testfolder'
            if not os.path.isdir(secondfolder):
                os.mkdir(secondfolder)
            if not os.path.isdir(thirdfolder):
                os.mkdir(thirdfolder)
                shutil.move(file, thirdfolder)
        #donkey
        if donkey in file:
            secondfolder = 'Animals/donkey'
            thirdfolder = 'Animals/donkey/testfolder'
            if not os.path.isdir(secondfolder):
                os.mkdir(secondfolder)
            if not os.path.isdir(thirdfolder):
                os.mkdir(thirdfolder)
                shutil.move(file, thirdfolder)
        #Chimpanzee
        if Chimpanzee in file:
            secondfolder = 'Animals/Chimpanzee'
            thirdfolder = 'Animals/Chimpanzee/testfolder'
            if not os.path.isdir(secondfolder):
                os.mkdir(secondfolder)
            if not os.path.isdir(thirdfolder):
                os.mkdir(thirdfolder)
                shutil.move(file, thirdfolder)
        #cat
        if cat in file:
            secondfolder = 'Animals/cat'
            thirdfolder = 'Animals/cat/testfolder'
            if not os.path.isdir(secondfolder):
                os.mkdir(secondfolder)
            if not os.path.isdir(thirdfolder):
                os.mkdir(thirdfolder)
                shutil.move(file, thirdfolder)

        #rat
        if rat in file:
            secondfolder = 'Animals/rat'
            thirdfolder = 'Animals/rat/testfolder'
            if not os.path.isdir(secondfolder):
                os.mkdir(secondfolder)
            if not os.path.isdir(thirdfolder):
                os.mkdir(thirdfolder)
                shutil.move(file, thirdfolder)
        #sheep
        if sheep in file:
            secondfolder = 'Animals/sheep'
            thirdfolder = 'Animals/sheep/testfolder'
            if not os.path.isdir(secondfolder):
                os.mkdir(secondfolder)
            if not os.path.isdir(thirdfolder):
                os.mkdir(thirdfolder)
                shutil.move(file, thirdfolder)
        #lizard
        if lizard in file:
            secondfolder = 'Animals/lizard'
            thirdfolder = 'Animals/lizard/testfolder'
            if not os.path.isdir(secondfolder):
                os.mkdir(secondfolder)
            if not os.path.isdir(thirdfolder):
                os.mkdir(thirdfolder)
                shutil.move(file, thirdfolder)
        #insect
        if insect in file:
            secondfolder = 'Animals/insect'
            thirdfolder = 'Animals/insect/testfolder'
            if not os.path.isdir(secondfolder):
                os.mkdir(secondfolder)
            if not os.path.isdir(thirdfolder):
                os.mkdir(thirdfolder)
                shutil.move(file, thirdfolder)
        #dog
        if dog in file:
            secondfolder = 'Animals/dog'
            thirdfolder = 'Animals/dog/testfolder'
            if not os.path.isdir(secondfolder):
                os.mkdir(secondfolder)
            if not os.path.isdir(thirdfolder):
                os.mkdir(thirdfolder)
                shutil.move(file, thirdfolder)

move()

In my Current Working Directory, i have these files:
1):- 2905r20.wav
2):- 5fm2905.wav
3):- nso2905.wav
4):-1sny2905wn3i56.wav
When i Run the Code, it is only moving the last file which is 1sny2905wn3i56.wav. It is Not Moving all the files which has 2905 in them. It Should move all 4 files. but i don't know why it is only moving last file. When I Run the Code again after moving the last file, it is moving 3rd file and deleting 4th file which was moved. And When i run the code again, it is deleting 3rd file and moving 2nd file and so on...
how to fix that ??

A: Edit :
You can considerably optimize your code like below.
Note the use os.path (it's more portable, smart and clear) :
animals = {}
animals["Buffalo"] = '1837'
animals["donkey"] = '6104'
animals["Chimpanzee"] = '9731'
animals["cat"] = '2905'
animals["rat"] = '6648'
animals["sheep"] = '3128'
animals["lizard"] = '3053'
animals["insect"] = '2681'
animals["dog"] = '3901'

wd_path = os.getcwd()
animals_path = os.path.join(wd_path, "Animals")
if not os.path.isdir(firstfolder):
    os.mkdir('Animals')

for file in os.listdir(animals_path):
    file_path = os.path.join(animals_path, file)

    for animal, id in animals.items():
        if id in file_path:
            secondfolder = os.path.join(animals_path, animal)
            thirdfolder = os.path.join(secondfolder, "testfolder")
            if not os.path.isdir(secondfolder):
                os.mkdir(secondfolder)
            if not os.path.isdir(thirdfolder):
                os.mkdir(thirdfolder)
            shutil.copy(file_path, thirdfolder)


text:
Q: How to execute RoboSpice requests synchronously? How to execure RoboSpice requests synchronously? Is it possible? I would like to use RoboSpice in IntentService.
Edit:
From time to time comes the need to execute something synchronously e.g. in service. In my recent project I have to queue some different types of requests and I wanted to use IntentService with RoboSpice. In my case when I'm executing different requests I need to wait for results from request1 then pass data from it to request2 and execute it.
I want to have some kind of batch request queue. Lets say we have two types of request: request1 and request2. request2 needs data fetched by request1:

*

*execute request1

*wait

*get data fetched by request1 and pass to request2

*execute request2

*wait

*goto 1.

I wanted to use IntentService (queue) but it dies after starting requests because of async.
In my opinion using listeners or CountDownLatch isn't the best way.

A: As proposed by Riccardo Ciovatti on the RoboSpice mailing list, a direct answer to your question is :
final CountDownLatch latch = new CountDownLatch(1);

final YourRequest request = new YourRequest();
spiceManager.execute(request, new RequestListener<YourResponse>() {

    @Override
    public void onRequestFailure(SpiceException spiceException) {
        latch.countDown();
    }

    @Override
    public void onRequestSuccess(YourResponse response) {
        latch.countDown();
    }
});

latch.await();

But this isn't a good idiom to use unless it's being executed on a background thread. Asynchronous processing is an essential feature of RoboSpice; it keeps the UI thread free.

A: Using RoboSpice in IntentService. Solved the problem with help of CountDownLatch. Let's say we have 2 different SpiceManagers and some syncMethods to execute in sequence in the IntentService.
Globals:
private final SpiceManager aSpiceManager =
       new SpiceManager(ASpiceService.class);
private final SpiceManager bSpiceManager =
       new SpiceManager(BSpiceService.class);

private CountDownLatch handleIntentLatch;

onHandleIntent: Before we execute syncMethodA - we init our CountDownLatch with 1. After executing syncMethodA we await() for countDown() on our latch. When later some method will call countDown() on our latch at least once - method onHandleIntent will continue it's execution and finish which will trigger IntentService onDestroy() callback.
@Override
protected void onHandleIntent(Intent intent) {
    handleIntentLatch = new CountDownLatch(1);

    syncMethodA();

    try {
        handleIntentLatch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

syncMethodA():
Suppose we need to launch some sync methods in sequence (syncMethodA which callback executes syncMethodB etc).
private void syncMethodA() {
    SpiceRequest requestA = new SpiceRequest();

    if (!aSpiceManager.isStarted()) {
        LogUtils.LOGD(TAG, "starting aSpiceManager");
        aSpiceManager.start(getApplicationContext());
    }

    aSpiceManager.execute(requestA , new RequestListener<ResponseA>() {
        @Override
        public void onRequestSuccess(final ResponseA responseA) {
            // SOME LOGIC

            syncMethodB();

            // SOME LOGIC

        @Override
        public void onRequestFailure(SpiceException spiceException) {
            handleIntentLatch.countDown();
            // SOME LOGIC
        }
    });
}

syncMethodB, syncMethodC etc are the same - in onRequestSuccess we start next syncMethodX. In on onRequestFailure we countDown() our latch (handleIntentLatch).
Very important!!!
In last syncMethodX in sequence (after which completion we want onHandleIntent method to continue it's execution and finish which will result IntentService to stop) - we countDown() our latch in onRequestSuccess ALSO.
onDestroy: here we stop our SpinceManagers.
@Override
public void onDestroy() {
    super.onDestroy();
    LogUtils.LOGD(TAG, "onDestroy");
    shutDownSpiceManagers();
}

shutDownSpiceManagers:
private void shutDownSpiceManagers() {
    if (aSpiceManager.isStarted()) {
        LogUtils.LOGD(TAG, "stopping aSpiceManager");
        aSpiceManager.shouldStop();
    }
    if (bSpiceManager.isStarted()) {
        LogUtils.LOGD(TAG, "stopping bSpiceManager");
        bSpiceManager.shouldStop();
     }
}

All should be OK now: no leaked Context, SpiceManagers will be killed in onDestroy AND ONLY AFTER callbacks are resolved.

A: If you don't want exactly synchronous execution, but only want requests to be executed sequentially in some order, you may write your own simple class which will just execute request B when request A succeeded or failed. Like that: https://github.com/Deepscorn/Shared/blob/master/app/src/main/java/com/gamelift/shared/request/base/RequestSequenceExecutor.java.
So, code will look like:
sequenceExecutor.setRequest(new FirstRequest());
sequenceExecutor.setOnSuccessListener(FirstRequest.class, new OnSuccessListener {
   public void onSuccess() {
     sequenceExecutor.setRequest(new SecondRequest());
   }
};

sequenceExecutor.setOnFaulListener(FirstRequest.class, new OnFailListener {
   public void onFail() {
     sequenceExecutor.setRequest(new OnFirstFailRequest());
   }
};

sequenceExecutor.setOnSuccessListener(SecondRequest.class, new OnSuccessListener {
   public void onSuccess() {
     notifyDone();
     return;
   }
};

sequenceExecutor.setDefaultOnFailListener(new OnFailListener {
   public void onFail(Exception e) {
     notifyDone();
     log(e);
     return;
   }
};
sequenceExecutor.execute() //starts execution


text:
Q: Deadlock reading async response content from async DelegatingHandler in webapi Problem
I'm using a DelegatingHandler in WebAPI to read the response Content and audit it to the database.
When the code gets to .ReadAsStringAsync() it appears to lock and prevent other requests from completing. I only know this, because when I remove the offending line, it works perfectly.
public static void Register(HttpConfiguration config)
{
    config.MessageHandlers.Add(new ResourceAuditHandler());
}

public class ResourceAuditHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                           CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        string content = "";
        if (response.Content != null)
        {
            //THIS SEEMS TO CREATE DEADLOCK!
            content = await response.Content.ReadAsStringAsync();
        }

        AuditResponseToDatabase(content);

        return response;
    }
}

Possible cause
I've read this can happen when two bits of the application are trying to read the content from same request/response (a DelegatingHandler and Controller/ModelBinder)... Or more specifically when one tries to read the .Result of the async response, but the other instance has already read the Result / Response Stream, which is then null.
My first request, hits a simple controller, but the second request, hits a controller with an attribute that checks the Action parameter "id" to check its not null. I've read that, when both a DelegatingHandler and the controller ModelBinder are trying to read from the Response you get deadlock.
Alternative method (which also fails)
I've also tried using the other approach (as seen in other SO questions) which uses .ReadAsByteArrayAsync() but this still seems to lock. I understood that this method doesn't use the .Result approach and reads it directly from the response stream (somehow).
 var response = await base.SendAsync(request, cancellationToken);

 string content= "";
 if (response.Content != null)
 {
     var bytes = await response.Content.ReadAsByteArrayAsync();
     responseContent = Encoding.UTF8.GetString(bytes);
 }

 AuditResponseToDatabase(content);

Please help!

A: Peter, first of all, you are right about the cause of this deadlock. Try to use async/await all the way down. In other words, do not block on async code. Another thing you should do is using the .ConfigureAwait(false):
    var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

    string content = "";
    if (response.Content != null)
    {
        content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    }

More info you can find at this link
If none of the above work, please provide a complete example, ok?
Hope this helps!


text:
Q: Regex to replace file extension I would like a regex to replace the .html file extension with a / so www.example.com/page.html becomes www.example.com/page/. I want to also exclude a folder from this rule so anything within www.example.com/specialdir/ should be excluded.
EDIT: This will be used in php

A: Better to use htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.html [L,QSA]

Source: Snipplr
So it will change all http://somesite/someurl to http://somesite/someurl.html in server side.

A: Search for
(www\.example\.com/(?!specialdir/).*)\.html$

and replace all with \1 or $1, depending on your regex implementation.
EDIT: In PHP:
$result = preg_replace('%(www\.example\.com/(?!specialdir/).*)\.html$%', '\1', $subject);


text:
Q: Assigning values to pointer types in a go struct In an attempt to handle null values when trying to input a struct of data to a database row (using goqu) I've defined a struct similar to
type datain struct {
   id *float32 `db:"id"`
   tempr *float32 `db:"temperature"`
}

and as these are all coming from strings I've made a function
func stringToFloat32(instr string) float32 {
    value, err := strconv.ParseFloat(instr, 32)
    if err != nil {
        log.Crit("error converting to float", "stringToFloat32", err)
    }
    return float32(value)
}

to convert the strings to float32's... however when I try and use
var datastruct datain
*datastruct.id = stringToFloat32("1234.4")

I get an error, invalid address or nil pointer dereference
which sort of makes sense to me.. but try as I might, I can't work out how to put a value in these structure fields if one exists.
I'm trying to use this mechanism to allow nulls when there is no value for one of the fields in the input csv string.
Maybe I'm doing this the hard way? I definitely have the syntax wrong somewhere.
Further digging.. seems I might need a new() function to assign a real variable to each pointer... Still can't help but feel this is doing things the hard way though.

A: When you defined a datain variable without any initialization, the value of the id was nil, which means you couldn't de-reference it.
var datastruct datain
id := stringToFloat32("1234.4")
datastruct.id = &id


text:
Q: How to fetch data from three firebase collections into one table in react.js I have three different collections in cloud firestore and I am storing my feedback app data in these collections. In the beginning I am storing students data into the students collection, after that I am storing the feedback of the student inside feedback collection and finally I am storing some extra information inside the details collections. Now I am fetching all the data in my admin panel table. I have fetched the details collection data successfully but not getting the logic of how get other informations in the table, and how will I relate the data with each other?
import React, { useEffect, useState } from 'react';
import MaterialTable from 'material-table';
import AdminNavbar from '../../layout/AdminNavbar';
import firebase from '../../../config/fbConfig';

const Dashboard = (props) => {
  const [tableData, settableData] = useState();
  useEffect(() => {
    getdata();
  });

  console.log(props);
  async function getdata() {
     const ref = firebase
      .firestore()
      .collection("details");
    const snapshot = await ref.get();
    settableData(snapshot.docs.map(doc=>doc.data()))
  }

  const tableCol = [
    {
      title: "Course expectations",
      field: "course_delivering_on_your_expectations"
    },
    {
      title: "Oppurtunities",
      field: "enough_opportunities_to_apply"
    },
    {
      title: "Explanation Clear",
      field: "explanation_of_concepts_clear"
    },
    {
      title: "Knowledge",
      field: "instructor_knowledgeable_about_the_topics"
    },
    {
      title: "Engaging",
      field: "instructors_delivery_engaging"
    },
    {
      title: "Learning",
      field: "learning_valuable_information"
    }
  ];

    return (
        <>
            <AdminNavbar />
            <div className="table-div">
                <MaterialTable
          title={"Student's Feedback"}
            data={tableData}
          columns={tableCol}

          options={{
            headerStyle: {
              backgroundColor: "#01579b",
              color: "#FFF"
            },
            exportButton: true,
            selection: false,
            search: true
          }}

        />
            </div>

        </>
    );
}

export default Dashboard;

A: There is no way for fetching 3 collections at the same time in a single query because Firestore queries are shallow.
You can use collection groups to achieve your goal. If the collections have different IDs, you would need multiple reads and join them client side.


text:
Q: Removing dynamically created EditText from Android SQLite database My activity's layout contains a ListView type list which I've created dynamically (I didn't use an actual ListView). An add button is clicked, which creates a row containing an EditText and a delete button. The user's input is saved from the EditText into a SQLite table. Everything works aside from the delete button. I'm able to delete the view, but the data remains in the table. The emulator crashes on click of the delete button.
The table contains only an "_Id" column and "Comment" column. I'm a beginner in Android development, but especially inexperienced with SQLite; this is my first attempt.
Sorry if I've added too much code. I added the whole datasource class, but felt like I was going overboard. If you'd like to see more, just let me know, cause I never know if all that I've attached is useful or not.
Here is my method that saves a row's EditText input to the database.
public Comment createComment(String comment) {
    ContentValues values = new ContentValues();
    values.put(SQLiteHelper.COLUMN_COMMENT, comment);
    long insertId = database.insert(SQLiteHelper.TABLE_COMMENTS, null,
            values);
    Cursor cursor = database.query(SQLiteHelper.TABLE_COMMENTS,
            allColumns, SQLiteHelper.COLUMN_ID + " = " + insertId, null,
            null, null, null);
    cursor.moveToFirst();
    Comment newComment = cursorToComment(cursor);
    cursor.close();
    return newComment;
}

And here is my attempt to remove a row's data from the database.
public void deleteComment(String comment) {
    ContentValues values = new ContentValues();
    values.put(SQLiteHelper.COLUMN_COMMENT, comment);

    database.delete(SQLiteHelper.TABLE_COMMENTS, SQLiteHelper.COLUMN_COMMENT
            + " = " + values, null);

}

This is my Comment class. Not sure if it was necessary considering the comment is just a string in an EditText. I borrowed a lot of code from an online source, so I'm not completely clear on how it should all be put together.
public class Comment {
private long id;
private String comment;

public long getId() {
    return id;
}

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

public String getComment() {
    return comment;
}

public void setComment(String comment) {
    this.comment = comment;
}

// Will be used by the ArrayAdapter in the ListView
@Override
public String toString() {
    return comment;
}

}
Here's some code from my main activity which dynamically creates the views.
// onClick handler for the "Add new" button;
public void onAddNewClickedStrengths(View v) {
    // Inflate a new row and hide the button self.

    inflateEditRowStrengths(null);

    v.setVisibility(View.GONE);
}

// Helper for inflating a row
private void inflateEditRowStrengths(String name) {

    idCount++;
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.list_row, null);
    final ImageButton deleteButton = (ImageButton) rowView
            .findViewById(R.id.button);
    final EditText editText = (EditText) rowView
            .findViewById(R.id.editText);
    editText.setId(idCount);

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        public void onFocusChange(View v, boolean hasFocus) {
            if(!hasFocus) {

                comment = datasource.createComment(editText.getText().toString());

            }

        }
    });

    load.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            datasource = new CommentsDataSource(getBaseContext());
            datasource.open();

            List<Comment> values = datasource.getAllComments();

            for (int i = 1; i < values.size(); i++){
                inflateEditRowStrengths(values.get(i).toString());

            }

        }
    });

    clear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            datasource.deleteAllComments();

            List<Comment> values = datasource.getAllComments();

            for (int i = 0; i < values.size(); i++){
                inflateEditRowStrengths(values.get(i).toString());

            }
        }
    });

    deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String toFind = editText.getText().toString();

            datasource.deleteComment(toFind);
            mContainerViewStrengths.removeView(rowView);

        }
    });

    if (name != null && !name.isEmpty()) {
        editText.setText(name);
    } else {
        mExclusiveEmptyView = rowView;
        deleteButton.setVisibility(View.INVISIBLE);
    }

    // A TextWatcher to control the visibility of the "Add new" button and
    // handle the exclusive empty view.
    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

            if (s.toString().isEmpty()) {
                mAddButtonStrengths.setVisibility(View.GONE);
                deleteButton.setVisibility(View.INVISIBLE);

                if (mExclusiveEmptyView != null
                        && mExclusiveEmptyView != rowView) {
                    mContainerViewStrengths.removeView(mExclusiveEmptyView);
                    editText.getText();
                }
                mExclusiveEmptyView = rowView;
            } else {

                if (mExclusiveEmptyView == rowView) {
                    mExclusiveEmptyView = null;
                }

                mAddButtonStrengths.setVisibility(View.VISIBLE);
                deleteButton.setVisibility(View.VISIBLE);

            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }
    });

    // Inflate at the end of all rows but before the "Add new" button

    mContainerViewStrengths.addView(rowView, mContainerViewStrengths.getChildCount() - 1);
}

A: ContentValues are used for inserting or updating, not for deleting. For the delete call you provide these three parameters:

*

*The table name

*The where clause

*The where clause arguments which replace the ?s in your where clause

So you need:
String where = SQLiteHelper.COLUMN_COMMENT + " = ? ";
String[] whereArgs = new String[] {comment};
database.delete(SQLiteHelper.TABLE_COMMENTS, where, whereArgs);

As SQL, that compiles internally as:
DELETE FROM COMMENTS WHERE comment = 'the value of comment'

Note that you can put the argument directly in the where clause if you wish like:
String where = SQLiteHelper.COLUMN_COMMENT + " = '" + comment + "'";
database.delete(SQLiteHelper.TABLE_COMMENTS, where, null);

However it is best practice to use the ? style arguments when you can.

A: At a first glance I would say that this is the line with the problem:
database.delete(SQLiteHelper.TABLE_COMMENTS, SQLiteHelper.COLUMN_COMMENT
            + " = " + values, null);

You should not pass the "values" object, instead pass the comment.


text:
Q: Including a Python function in an R package without importing the entire package each time the function is used If I'm calling a function within an R package that I created, I prefix it with the package name in which it resides. For example, if I wish to use gam from the mgcv package in the myfunc function of my package, I could write something like,
myfunc <- function(y, x, df){
    mgcv::gam(y ~ s(x), data = df)
}

Now, say I want to use the Python function indexes from the package peakutils. I could write,
myfunc <- function(y){
    pu <- reticulate::import("peakutils")
    pu$indexes(y)
}

but this would import the entire package each time myfunc was called, which is not ideal. What is the correct way of doing this? Presumably, Imports: in the DESCRIPTION file is just for R packages. Or is there a way to include it there somehow?

A: The solution is to import the Python library in the .onLoad function of the package being sure to specify delay_load = TRUE.
For example,
# Global reference to peakutils package - initialized in .onLoad
peakutils <- NULL

# Called upon loading the package
.onLoad <- function(libname, pkgname) {
  # Use superassignment to update global reference to peakutils
  peakutils <<- reticulate::import("peakutils", delay_load = TRUE)
}

While this loads the entire package, it does so only once rather than each time a function from the Python library is needed. A thorough explanation is given here.


text:
Q: Find all the natural numbers $n$ such that $\left\lfloor\frac{n^2}{3}\right\rfloor$ is prime How many natural numbers $n$ exist for which $\left\lfloor\frac{n^2}{3}\right\rfloor$ is prime?
I thought a lot but I don't  how to calculate the correct part.

A: So it's pretty clear that $n = 3k$ only works for $k=1$ i.e. $n=3$.
For $n = 3k+1$ we have that $n^2 = 9k^2 + 6k + 1$, so $\lfloor \frac{n^2}{3}\rfloor = 3k^2 + 2k$. If $k$ is even then this number is divisible by $2$. If $k$ is odd, then this number is divisible by $k$, which means that we still have a solution when $k=1$ i.e. $n=4$.
For $n=3k-1$ we can apply a similar technique and get $n^2 = 9k^2 - 6k + 1$ so $\lfloor \frac{n^2}{3}\rfloor = 3k^2 - 2k$. In this case $k=1$ gives us $1$ which is not a prime.

A: Outline:
You want $3p\leq n^2<3p+3.$
Show that, for $n>3,$ $3p\neq n^2.$
For any $p$, show that $3p+2$ is never a square.
This leaves $3p+1=n^2$, which can be written as $3p=n^2-1.$ Factor the right hand side, and deduce what $n$ can be.


text:
Q: Binomial coefficient paths? Here's a problem and my attempt to answer it:
We want to get a binomial coefficient identity depending on grid walking. Starting from the bottom left corner and going to the top right corner. You can only move 1 step up and 1 left right. There are n rows and m columns in the grid. Any particular path has to use only 1 edge in the k-th column. Depending on which of the n+1 edges used, classify your paths. E.g. the blue lines, has n = m = 10 and k = 4 (if we count from 0). Then, the identity will be:
$$\sum_{i=0}^{n} f(n,m,k,i)  $$ = $m+n\choose n$
Find out the value of f(n,m,k,i). What is the identity for the picture below?

What do you think of my answer here?

A: Your solution seems to be correct. I don't how to derive your solution, but here's my insight. Note that to find the total number of ways passing through one blue segment in the $k-$th column and $i-$th we can split the way into two smaller pieces. Eventually you have to lend at the intersection of the $k-$th vertical line and $i-$th horizontal line (bottom one and the left-most one are 0). The total number of ways is
$$Y = \binom{k+i}{k}$$
Then we have to go one step right and we find all the ways from the intersection of the $(k+1)-$th line and $i-$th line. The total number of ways is:
$$Z = \binom{m-(k+1) + (n-i)}{n-i}$$
Now just multiply the two results.