text:
Q: pandas does not read csv data with exponetial form I'm trying to read a simple csv data file using pandas read_csv command. For some reason all values expressed in exponential form are converted to zeros.
Can someone please help me understand what is going wrong here and give me the instructions on how to do this correctly?
nlv12097@acv0105 TEST $ python
Job <886418> is submitted to queue <interq>.
<<Waiting for dispatch ...>>
<<Starting on apv0033>>
Enthought Python Distribution -- www.enthought.com
Version: 7.3-2 (64-bit)

Python 2.7.3 |EPD 7.3-2 (64-bit)| (default, Apr 11 2012, 17:52:16)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "credits", "demo" or "enthought" for more information.
>>> import pandas as pd
>>> print pd.__version__
0.7.3
>>> data = pd.read_csv('path_1_setup_sta_tta_MC30k.data', skiprows=[1])
>>> data.head()
                                               output name  mean  std.dev.  -sigma value  output value  +sigma value  output value.1
0              capture_path_clk_delay_mult1/out_reg_127/ck     0         0            -3             0             3               0
1  data_path_mult1/areg_reg_9/ck_delay_mult1/out_reg_127/d     0         0            -3             0             3               0
2          launch_clock_path_clk_delay_mult1/areg_reg_9/ck     0         0            -3             0             3               0
3                launch_path_clk_delay_mult1/out_reg_127/d     0         0            -3             0             3               0
4  stage_0001_delay_mult1/rc_cg_hier_inst5/rc_cgic_inst/ck     0         0            -3             0             3               0
>>> data.describe()
       mean  std.dev.  -sigma value  output value  +sigma value  output value.1
count   832       832           832           832           832             832
mean      0         0            -3             0             3               0
std       0         0             0             0             0               0
min       0         0            -3             0             3               0
25%       0         0            -3             0             3               0
50%       0         0            -3             0             3               0
75%       0         0            -3             0             3               0
max       0         0            -3             0             3               0
>>>

Including a sample data set:
nlv12097@acv0105 TEST $ head path_1_setup_sta_tta_MC30k.data
output name,mean,std.dev.,-sigma value,output value,+sigma value,output value

capture_path_clk_delay_mult1/out_reg_127/ck,2.240e-10,1.042e-11,-3.000,1.968e-10,3.000,2.607e-10
data_path_mult1/areg_reg_9/ck_delay_mult1/out_reg_127/d,1.074e-08,7.784e-11,-3.000,1.044e-08,3.000,1.097e-08
launch_clock_path_clk_delay_mult1/areg_reg_9/ck,2.438e-10,1.056e-11,-3.000,2.154e-10,3.000,2.816e-10
launch_path_clk_delay_mult1/out_reg_127/d,1.098e-08,7.860e-11,-3.000,1.068e-08,3.000,1.122e-08
stage_0001_delay_mult1/rc_cg_hier_inst5/rc_cgic_inst/ck,0.000e+00,0.000e+00,-3.000,0.000e+00,3.000,0.000e+00
stage_0001_slew_mult1/rc_cg_hier_inst5/rc_cgic_inst/ck,4.055e-12,2.390e-18,-3.000,4.055e-12,3.000,4.055e-12
stage_0002_delay_mult1/rc_cg_hier_inst5/rc_cgic_inst/q,2.438e-10,1.056e-11,-3.000,2.154e-10,3.000,2.816e-10
stage_0002_slew_mult1/rc_cg_hier_inst5/rc_cgic_inst/q,1.631e-10,4.559e-12,-3.000,1.498e-10,3.000,1.776e-10

A: Your version is 0.7.3!? I can't even find documentation for that version anymore. Unless this version is absolutely critical to your system, please update it. That version has to be 7 years old or more. (Ok it's only 5 years old, but still.)
Alright. So I was able to find that version and do some testing. Given your sample set the view is as you say, but if you access an individual data point the numbers are as expected. For example:
df['mean'][0]
2.24e-10

My assumption is that internally somewhere, and we can't see the source so we have no idea where, there is a setting that says values this low are essentially 0. This is not the behavior in the current stable version of pandas (0.19.2). Again I strongly suggest upgrading.


text:
Q: Maven Jackson-Databind I use such pom.xml
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.9</version>
</dependency>

But realy in my project I have
jackson-annotaions 2.8.0
jackson-core 2.8.9
Why jackson-annotaions is 2.8.0 ???

A: The jackson-databind library uses two other libraries: jackson-core and jackson-annotations. The FasterXML team (the makers of Jackson) release these libraries independently so they have their own version numbers. This just happens to be the version that was used by jackson-databind when 2.8.9 was released.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need to Re Design existing logic for dynamic input I have a method getFormattedValue(List<String> dataHeaders, List<String> data) that returns String value based contents of dataHeaders and data list. dataHeaders list can have 10 distinct values and based on value at particular index output string formation changes.
Below code was working fine tiil the time when dataHeaders contents are received in specific order , but lately this order is changing many atimes. As this input is received from other app/ system, i do not have control over order of elements. Hence i want to update my code so that it works correctly even after input order is altered.
If 1'st element of dataHeaders list is "OPERATION_NAME" then i need not take any action, but if "OPERATION_NAME" comes at 2'nd index in dataHeaders list then i need to do special formatting to output value. And so on....
My Pain is that i receive 10 dataHeaders. Please suggest me any good approach to handle this issue. I am posting my code below, suggestions are welcome.
    import java.util.ArrayList;
import java.util.List;

public class ValueGenerator {

    public String getFormattedValue(List<String> dataHeaders, List<String> data){

        String formattedOutValue=null;

        if(dataHeaders!=null && data!=null &&
                dataHeaders.size() == data.size()){
            if(dataHeaders.get(0).equals("OPERATION_NAME")){
                formattedOutValue=data.get(0); // Add no spaces
            }else if(dataHeaders.get(1).equals("OPERATION_NAME")){
                formattedOutValue=data.get(1)+"    "; // Add 4 blank spaces
            }else if(dataHeaders.get(2).equals("OPERATION_NAME")){
                formattedOutValue=data.get(2)+"      "; // Add 6 blank spaces
            }

        }

           //likewise i want to avoid redundant if - else if check

        return formattedOutValue;
    }

}

A: I assume that you want data.get(2) in the case of dataHeaders.get(2) and not data.get(1)
Basically you just need to find the index of the string OPERATION_NAME in dataHeaders and use it for data. The simplest way is to iterate over the list dataHeaders with an index and stop when you find it.
If you need to handle more strings then you could use a Map to map the strings you want to evaluate to their indices, this could look like this:
final static Map<Integer, String> formatByIndexMap;
static {
    formatByIndexMap = new HashMap<>();
    formatByIndexMap.put(0, "");
    formatByIndexMap.put(1, "    ");
    formatByIndexMap.put(2, "      ");
    // and so on
    formatByIndexMap.put(9, "----format for 10----");
}

public String getFormattedValue(List<String> dataHeaders, List<String> data){
    String formattedOutValue = null;
    if (dataHeaders != null && data != null &&
            dataHeaders.size() == data.size()) {
        Map<String, Integer> dhm = new HashMap<>();
        for(int i = 0; i < dataHeaders.size(); i++) {
            dhm.put(dataHeaders.get(i), i);
        }
        Integer operationNameIndex = dhm.get("OPERATION_NAME");
        if(operationNameIndex != null) {
            formattedOutValue = data.get(operationNameIndex.intValue()) +
                    formatByIndexMap.get(operationNameIndex);
        }
    }
    return formattedOutValue;
}

The format map formatByIndexMap is defines as final static.
An for some basic testing:
@Test
public void getFormattedValue() {
    List<String> data = Arrays.asList("operation", "foo", "bar");
    List<String> dataHeaders;
    String formated;

    dataHeaders = Arrays.asList("OPERATION_NAME", "FOO_NAME", "BAR_NAME");
    formated = getFormattedValue(dataHeaders, data);
    Assert.assertEquals("operation", formated); // no spaces

    dataHeaders = Arrays.asList("FOO_NAME", "OPERATION_NAME", "BAR_NAME");
    formated = getFormattedValue(dataHeaders, data);
    Assert.assertEquals("foo    ", formated); // four spaces

    dataHeaders = Arrays.asList("FOO_NAME", "BAR_NAME", "OPERATION_NAME");
    formated = getFormattedValue(dataHeaders, data);
    Assert.assertEquals("bar      ", formated); // six spaces

    dataHeaders = Arrays.asList("FOO_NAME", "BAR_NAME", "", "", "", "", "",
             "", "", "OPERATION_NAME");
    data = Arrays.asList("operation", "foo", "bar", "", "", "", "",
            "", "", "tail");
    formated = getFormattedValue(dataHeaders, data);
    // ----format for 10----
    Assert.assertEquals("tail----format for 10----", formated);
}


text:
Q: Solve the equation on the interval $0 \le \theta\le2\pi $ I have this Final Math Exam Review, for Math Analysis/Trig = Pre-calculus. So I stumbled upon my review and this section arose where it told me to

Solve the equation on the interval $0 \le \theta \le 2\pi $

Honestly, I completely forgot this topic and have no idea how to do this. The questions of that topic is (the review is multiple choice)

$2\cos^2\theta -1 = 0$
$\sec(\frac{3\theta}{2}) = -\sqrt2$
$\cos(2\theta) = \frac{\sqrt3}{2}$
$\cos(2\theta - \frac{\pi}{2}) = \frac{\sqrt2}{2}$

If you guys can kindly solve one of them for me, I am pretty sure I can solve the rest, or tell me the logic necessary to solve these types of questions.

A: Let's examine the first problem.
\begin{align*}
2\cos^2\theta - 1 & = 0\\
2\cos^2\theta & = 1\\
\cos^2\theta & = \frac{1}{2}\\
\cos\theta & = \pm \frac{1}{\sqrt{2}}\\
\cos\theta & = \pm \frac{\sqrt{2}}{2}
\end{align*}
Treating the two cases separately yields
\begin{align*}
\cos\theta & = \frac{\sqrt{2}}{2} & \cos\theta & = -\frac{\sqrt{2}}{2}\\
\cos\theta & = \cos\left(\frac{\pi}{4}\right) & \cos\theta & = \cos\left(\frac{3\pi}{4}\right)
\end{align*}
By symmetry, $\cos\theta = \cos(-\theta)$.

Since coterminal angles have the same cosine, we conclude that $\cos\theta = \cos\varphi$ if
$$\varphi = \pm\theta + 2n\pi, n \in \mathbb{Z}$$
Hence,
$$\cos\theta = \cos\left(\frac{\pi}{4}\right) \implies \theta = \pm \frac{\pi}{4} + 2n\pi, n \in \mathbb{Z}$$
and
$$\cos\theta = \cos\left(\frac{3\pi}{4}\right) \implies \theta = \pm \frac{3\pi}{4} + 2n\pi, n \in \mathbb{Z}$$
The requirement that $0 \leq \theta \leq 2\pi$ determines the permissible values of $n$.
\begin{align*}
\theta & = \frac{\pi}{4} + 2n\pi \in [0, 2\pi] \implies n = 0 \implies \theta = \frac{\pi}{4}\\
\theta & = -\frac{\pi}{4} + 2n\pi \in [0, 2\pi] \implies n = 1 \implies \theta = \frac{7\pi}{4}\\
\theta & = \frac{3\pi}{4} + 2n\pi \in [0, 2\pi] \implies n = 0 \implies \theta = \frac{3\pi}{4}\\
\theta & = -\frac{3\pi}{4} + 2n\pi \in [0, 2\pi] \implies n = 1 \implies \theta = \frac{5\pi}{4}
\end{align*}
Substituting these values into the original equation demonstrates that they are valid solutions.  For instance,
\begin{align*}
2\cos^2\left(\frac{\pi}{4}\right) - 1 & = 2\left[\cos\left(\frac{\pi}{4}\right)\right]^2 - 1\\
& = 2\left(\frac{\sqrt{2}}{2}\right)^2 - 1\\
& = 2\left(\frac{1}{\sqrt{2}}\right)^2 - 1\\
& = 2\left(\frac{1}{2}\right) - 1\\
& = 1 - 1\\
& = 0
\end{align*}
Hence, the solution set is $$S = \left\{\frac{\pi}{4}, \frac{3\pi}{4}, \frac{5\pi}{4}, \frac{7\pi}{4}\right\}$$

A: Well for the first equation you can isolate $\theta$:
$2\left(cos(\theta)^2\right)=1$
$\left(cos(\theta)\right)^2=\frac12$
$\left(cos(\theta)\right)=\pm\sqrt{\frac{1}{2}}=\pm\frac{1}{\sqrt{2}}$
Can you solve the rest of this question?
The rest of them are quite similar. The only thing that might be different is using a trigonometric identity to bring it to a form thats easier to solve
Edit: Here is a unit circle. Find all the angles where
$cos\theta=\pm\frac{1}{\sqrt{2}}$ in your interval. It's crude, and you should probably know how to solve this off by heart. Use this as a starting point.

Another hint:
$\frac{1}{\sqrt{2}}=\frac{\sqrt{2}}{2}$

A: You have to know the "well known" special values of the trig functions $\cos$ and $\sin$, as well as their global symmetries. I'll do problem 3) here:
We know that within a full period $[-\pi,\pi]$ one has $\cos x={\sqrt{3}\over2}$ iff $x=\pm{\pi\over6}$. Therefore $2\theta=\pm{\pi\over6}$ mod $2\pi$. This implies $\theta=\pm{\pi\over12}$ mod $2\pi$, or else $\theta=\pm{\pi\over12}+\pi$ mod $2\pi$. It follows that we obtain four solutions per period. Their representants in the interval $[0,2\pi]$ are $\bigl\{{\pi\over12}, {5\pi\over12}, {7\pi\over12}, {11\pi\over12}\bigr\}$.


text:
Q: Selecting from multiple tables with LEFT JOIN I have 3 tables
t1 (select these records)
-------------
id
offer_id
business_id

t2 (offer details)
-------------
id
offer_details
business_id

t3 (business details)
-------------
id
business_name

I need to select all records from t1 and add information from t2 and t3. Seems basic but I can't seem to be able to get it right -- must be the heat.
SELECT t2.offer_details, t3.business_name
FROM t2
LEFT JOIN t1 ON (t1.offer_id = t2.id)
LEFT JOIN t3 ON (t1.business_id = t3.id)

A: How about this
Select t2.offer_details, t3.business_name
From t1
Left Join t2 ON (t1.offer_id = t2.id)
Left Join t3 ON (t1.business_id = t3.id)

A: should be
 SELECT t2.offer_details, t3.business_name
 FROM t1
 LEFT JOIN t1 ON (t1.offer_id = t2.id)
 LEFT JOIN t3 ON (t1.business_id = t3.id)

Your lead table is t1 and the join should be based  on this table

A: If you want all records from t1, add t1.* on your select part. Assuming that all IDs in t1 exists in the other 2 tables
SELECT
    t1.*, t2.offer_details, t3.business_name
FROM
    t1
    JOIN t2 ON t2.id = t1.offer_id
    JOIN t3 ON t3.id = t1.business_id

Modify to LEFT JOIN if the IDs in t1 may be missing in t2 or t3.


text:
Q: Delete a row through DataGridView I have a Button that lists to me everything from a database and another Button that was made to delete something from database by "Name". To do that, I have a TextBox where I input the "Name" and delete it from the database.
To make things easy and faster I had another solution which is simpler than what I am currently doing. What I want it to do is click on a row and then press the delete Button and have the row be deleted from the database. I found this solution but this doesn't work:
For Each row As DataGridViewRow In myDataGrid.SelectedRows
    myDataGrid.Rows.Remove(row)
Next

Basically what I have to do in the code is make a query and select the row that I want right?

A: The For[...]Next statement will only delete the DataGridViewRow from the DataGridView. It won't commit any changes to the database.
A DataGridView is a view of the data. You would need to commit the changes on the DataSet.
If you want a more specific answer post the code that shows how you are binding the data to the DataGridView.

A: My apologies I am not able to comment. In either case, if you are trying to delete the record from the database, you will have to use a delete query.
Below is an example on how to do it:
delete selected row from datagridview and datasource table
Without using a stored procedure you can use this code:
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim cnstring As String = "Your connection String"
Dim sqlstring As String = "Delete from yourTable where column= your record"
cn = New OleDbConnection(cnstring)
cmd = New OleDbCommand(sqlstring, cn)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()


text:
Q: Carousel slider with description below changing I`m working on a website for my paintings with a carousel and description of a painting below. I would like the description below the carousel to change with each painting whenever I click on the arrows of the carousel.
Here`s the code: https://mirek88.github.io/paintings/index-2.html
I would really appreciate any help.
Thanks!
Mirek


text:
Q: PHP,SMARTY - File upload not working in IE alone I have a form defined via smarty, consisting of multiple tabs for various purposes. Two of the tabs have file upload controls placed inside it. The form submission works without any flaws in Firefox, but when I do the same in IE8/7, form submission is working only for the first file upload control. The second file control is not at all picked up by the Browser, especially while submitting the form. The file upload control is defined in the normal way, and not making use of smarty tags to do that.

<input type="file" name="e2c[vids_upload]" maxlength="100000"/> this is the code. Working in Firefox without issues

A: My guess is that you have 2 inputs with the same name.  Browsers expect unique names for each file input instance.  To see both with similar names, I'd suggest doing this:
<input type="file" name="e2c[vids_upload][]" maxlength="100000" />

This will essentially put each file into it's own index under e2c[vids_upload] so that you can see them both on the other side.
Admittedly, if this is the issue, I'm surprised that Firefox is working at all.


text:
Q: TortoiseSVN Error I have some problems with SVN.
Can anybody help me?
When I tray to merge branch to trunk i get flowing error:

Server sent unexpected return value
  (403 Forbidden) in response to OPTIONS

Same error get when tray to create new tag or branch.
I have Read/write permisions.
I use VisualSVN  and TortoiseSVN.
Thanks

A: 403 Forbidden is one of the HTTP Status Codes. As per the definition:

The server understood the request, but
  is refusing to fulfill it.
  Authorization will not help and the
  request SHOULD NOT be repeated. If the
  request method was not HEAD and the
  server wishes to make public why the
  request has not been fulfilled, it
  SHOULD describe the reason for the
  refusal in the entity. If the server
  does not wish to make this information
  available to the client, the status
  code 404 (Not Found) can be used
  instead.

I imagine that your repository is something like http://server/repo/project/ so try browsing that URL with your regular browser. Maybe is not related to Subversion authentication but HTTP authentication.
I know it is not a good answer, but it might give you a hint to expand the question :)


text:
Q: AddRequest Is Not Respected in HttpURLConnection I am trying to attach the "Accept-Language" header to a get request that I am making but when I check the request using Charles Proxy then the header is not there. I add the header like so.
private HttpURLConnection getConnection(Uri uri) throws Exception {
    URL url = new URL(uri.toString());
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.addRequestProperty(ACCEPT_LANGUAGE_HEADER, LanguageProvider.getLanguage());
    return urlConnection;
}

The odd this is if I log the requestproperties after I add then I can see it is set in the HttpURLConnection. Why is this removed before it is sent?
UPDATE
I noticed that the following headers where added automatically

Host  appname-api-staging.herokuapp.com
User-Agent Dalvik/1.6.0 (Linux; U; Android 4.3.1; Galaxy Nexus Build/JLS36I)
Proxy-Connection  Keep-Alive

I modified my code to try and change the User-Agent so like
    URL url = new URL(uri.toString());
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.addRequestProperty("User-Agent", "test");
    urlConnection.setRequestProperty(ACCEPT_LANGUAGE_HEADER, LanguageProvider.getLanguage());

Lo and behold this changes the host header to "test". What is the difference between adding a new request property and modifying and old one?

A: something like this works for me: httppost.setHeader("Accept", "application/json");
hence, you should do httppost.setHeader(ACCEPT_LANGUAGE_HEADER, "es_ES") if u want to read Don Quijote in the original language... :P
BTW, I use the HttpClient:
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, HTTP_CON_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParameters, HTTP_CON_TIMEOUT);

        HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpGet httpGet = new HttpGet(baseUrl);
        httpGet.setHeader("Accept", "application/json");

        HttpResponse response = httpclient.execute(httpGet);

A: I know this is an old question, and the original poster has probably moved on, but this answer is for anyone else (like me) who seems to have the same issue.
The problem may not be in the HttpURLConnection at all. It may be related to the name of the header and the server's configuration. I ran similar tests, such as pausing execution and checking to see if the header I added was set in the HttpURLConnection (and it was), changing the value of another header that was added automatically (which did work), and changing the name of the header to some test name such as XYZ, which worked; I was able to retrieve the value on the server side. And one more, I used an HTTP tool to set the header and send the request. That also only worked if I changed the name of the header.
So, in my case, the problem was on the server side. Apache or PHP was removing the header for some reason. So as a workaround/solution, I added the following directives to apache configuration:
RewriteCond %{HTTP:Header_Name} (.+)
RewriteRule .* - [env=HTTP_HEADER_NAME:%1]


text:
Q: alternative way to explore .net framework source code While developing with Java in Eclipse it was very handy: you can attach sources and explore core java code just like your own. In Visual Studio I know about watching at the .net source code is possible only when debugging (and I can't say this feature works well).
Are there any alternatives of exploring .net source code?

A: Source code of many .NET framework libraries is available for download. It is released under reference license so you can certainly browse through code.
Also refer this and this blog post about how to setup visual studio to step-in while debugging.

A: Using ReSharper you can do "Go to Declaration" directly from within visual studio and it will take you the actual, original source code that is not part of your solution. It works both while debugging and in normal mode. It doesn't just work for the .NET source it works for any assemblies that you have pdbs for (given that the source code is anywhere on your disk or in your network).
In conjunction with the ReflectorNavigator PowerToy "Go to Declaration" even works for assemblies that you neither have the source code nor the pdbs for. It will use reflector behind the scenes to decompile the assembly and presents you the source code directly in visual studio.
Here is an article that discusses all that.

A: you can see the source code from the tool called Reflector. Some companies obfuscate their DLLs(for security reasons) in which case Reflector will unable to show source code.

A: You can look at the Mono source code.
Mono is an open source implementation of the CLR and many base class libraries.
As for the Microsoft ones - they are proprietary, so any access to them is determined by Microsoft. As you have seen, debugging is one way of doing so and some companies have signed NDAs with Microsoft that allow them to see the source (an unlikely option for any individual, unfortunately).
Having said that, some libraries are available to download (provided you agree to the EULA), as @Hemant says in his answer.
Another option (since all of the .NET library code is compiled to IL) is to use a tool like Reflector to see a disassembled version (it will not give you the original C#, but a best effort decompilation).

A: Have you tried Reflector? Might do the job.

A: You should take a look at Reflector which allow you to read bytecode compiled .NET assemblies. It's a mandatory tool for any .NET developper ;)


text:
Q: Two column layout with fixed margins in between columns and one column fluid, one fixed? I am new to html/css and I am stumped trying to set up a two column design where the left column is a column of text that has a fixed width of 300px and the right column is a photo that has a width of 40% of the screen. Also, and this is where I am getting hung up, the two columns should always maintain a fixed margin between them, even at different screen sizes. I want it so any excess screen width beyond the 300px that the text column takes up and the 40% of the screen that the photo takes up is evenly distributed to the left and right edges of the screen, instead of going in between the two columns. Currently, when I expand the screen all the excess space goes in between the two columns (while I want there to instead be a fixed margin between them and the excess space to go to the edges). What would be the best way to do this?
I have tried a couple different methods, but here is my code for the closest I have gotten:

 Header Here

Paragraph with text here. Paragraph with text here.

.pic {
  width: 40%;
  margin: 0;
  padding: 0;
  display: inline-block;
}

.f {
  float: left;
  margin: 0;
  padding: 0;
  width: 300px;
  text-align: justify;
  display: inline-block;
}

.group:after {
  content: "";
  display: table;
  clear: both;
}

Thanks so much for any help. I've tried floating it, using in-line blocks, and relative/absolute.

A: If I understood your question correctly, you want a fixed width between the text and picture? And any extra space evenly spread to the sides?

* {
    margin: 0;
    padding: 0;
    text-align: center;
}
.group {
    display: flex;
    justify-content: center;
}
.f {
    width: 300px;
    height: 200px;
    border: 1px solid black;
}
.middle {
    width: 10%;
}
.pic {
    width: 40%;
    height: 200px;
    background-color: green;
}

        fixed width: 300px;

        fixed width: 10%;

        fixed width: 40%;

A: Is this something like you're trying to achieve?

.pic {
  max-width: 100%;
  margin: 0;
  padding: 0;

}
.group {
  width: 100%;
  display: table;
  table-layout: fixed;
}
.group > * {
  display: table-cell;
  vertical-align: top;
}

.group .f {
  width: 300px;
}

 Header Here

Paragraph with text here. Paragraph with text here.


text:
Q: requests in python get error WSAECONNRESET I'm trying to get exchange rate with a request:
r = requests.get('https://www.boi.org.il/currency.xml?curr=01')

I'm getting an error :
{ConnectionError}('Connection aborted.', OSError("(10054, 'WSAECONNRESET')"))
What is the solution for that error?

A: The server does a check for valid/supported browsers. You need to pass one it accepts e.g.
import requests

headers = {'User-Agent': 'Safari/537.36'}
r = requests.get('https://www.boi.org.il/currency.xml?curr=01', headers=headers)


text:
Q: How to modify software serial to give me more interrupts (Mega)? I have an Arduino Mega which I'm using with the Ultimate GPS Logger shield (by Adafruit) and the 9-axis motion shield (by Arduino)
I currently need 4 interrupts to act as wheel speed sensors (tachometers). However, currently software serial seems to use up all of these, and I'm only left with the interrupt from pin 2 (INT.0) that's currently working. Is there a way I can modify software serial to allow me to use more of the interrupts on the board?
Currently the Mega is using jumper cables like so to allow for compatibility (this is because the GPS shield isn't designed to fully work with the Arduino Mega).
//GPS 8  RX --> MEGA 18 TX1
//GPS 7  TX --> MEGA 29 0RX1
//GPS 13 CLK--> MEGA 52 SCK
//GPS 12 DI --> MEGA 51 MOSI
//GPS 11 DO --> MEGA 50 MISO

The 9-axis motion sensor and GPS offer to use interrupts but I don't want to use these unless they are strictly necessary. I initially tried using the pinchangeint library, however this does not work with the SoftwareSerial library!
My code is below:
#include <SPI.h>
#include <Adafruit_GPS.h>
#include <SD.h>
#include <avr/sleep.h>
#include "NAxisMotion.h"
//Contains the bridge code between the API and the Arduino Environment (Accelerometer)
#include <Wire.h>
#include <math.h>
#include <SoftwareSerial.h>

//APPS definitions
#define APPSpin A0
double APPSvalue;

// Wheel speed definitions
#define FLpin  2 //WORKING
#define FRpin  21 //INT.1 (3) Does not work

volatile byte FLtooth;
volatile byte FRtooth;
double FLrpm;
double FRrpm;
unsigned long FLtime;
unsigned long FRtime;

// Accelerometer definitions
NAxisMotion mySensor; //Object that for the sensor
uint8_t range = 3; // 0 = 2G, 1 = 4G, 2 = 8G, 3 = 16G
uint8_t bandwidth = 3; // 0 - 7 = 7.81Hz x 2^bandwidth
uint8_t powerMode = 0; // 0 - 5 = Norm, Suspend, Low Power 1, Standby, Low Power 2, Deep Suspend
bool updateSensorData = true;
//Flag to update the sensor data. Default is true to perform the first read before the first stream

// Connect to the GPS on the hardware port
#define GPSSerial Serial1
Adafruit_GPS GPS(&GPSSerial);

// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences
#define GPSECHO true

// This keeps track of whether we're using the interrupt off by default!
boolean usingInterrupt = false;
void useInterrupt(boolean);

// Set Adafruit SD Card pin
#define chipSelect 10

File logfile;
uint32_t timer = millis();

void setup() {
  //SD Setup
  Serial.begin(115200);
  pinMode(chipSelect, OUTPUT);
  SD.begin(chipSelect, 11, 12, 13);

  //GPS Setup
  GPSSerial.begin(9600);
  // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY); //RMC (recommended minimum)
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_10HZ); // Set 1 Hz update rate (1Hz is suggested max), NOTE: This is the speed of the echo!
  GPS.sendCommand(PMTK_API_SET_FIX_CTL_5HZ); //Position fix update rate command
  GPS.sendCommand(PGCMD_ANTENNA); // Request updates on antenna status
  useInterrupt(true); //timer0 interrupt go off every 1ms and read GPS data

  char filename[15];
  strcpy(filename, "1.5_LOG00.csv");
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = '0' + i/10;
    filename[7] = '0' + i%10;
    if (! SD.exists(filename)) {
      break;
    }
  }
  logfile = SD.open(filename, FILE_WRITE);

  //APPS Setup
  APPSvalue = 0.00;

  //Wheel Speed Setup
  attachInterrupt(digitalPinToInterrupt(FLpin), FLdetect, RISING);
  //Initialize the intterrupt pin
  attachInterrupt(digitalPinToInterrupt(FRpin), FRdetect, RISING);
  FLtooth = 0;
  FRtooth = 0;
  FLrpm = 0.00;
  FRrpm = 0.00;
  FLtime = 0;
  FRtime = 0;

  //Accelerometer Setup
  I2C.begin();
  //Initialize I2C communication to the let the library communicate with the sensor.
  mySensor.initSensor();
  //The I2C Address can be changed here inside this function in the library
  mySensor.setOperationMode(OPERATION_MODE_NDOF);
  //Can be configured to other operation modes as desired
  mySensor.setPowerMode(0); //Normal = 0, Low Power = 1, Suspend = 2
  mySensor.setUpdateMode(MANUAL);
  //The default is AUTO. Changing to manual requires calling the relevant update functions prior to calling the read functions, setting to MANUAL requires lesser reads to the sensor
  mySensor.updateAccelConfig();
  updateSensorData = true;

  // Setup settings
  logfile.print("Accelerometer Range");
  logfile.print(", ");
  logfile.print(mySensor.readAccelRange());
  logfile.print(", ");
  logfile.println("2^(1+range)");
  logfile.print("Accelerometer Bandwidth");
  logfile.print(", ");
  logfile.print(mySensor.readAccelBandwidth());
  logfile.print(", ");
  logfile.println("7.81Hz x 2^bandwidth");
  logfile.print("Accelerometer Power Mode");
  logfile.print(", ");
  logfile.print(mySensor.readAccelPowerMode());
  logfile.print(", ");
  logfile.println("0 - 5 = Norm - Suspend - Low Power 1 - Standby - Low Power 2 - Deep Suspend");
  logfile.println();

  // Setup headings
  logfile.print("GPS Fix");
  logfile.print(", ");
  logfile.print("Time (5Hz)");
  logfile.print(", ");
  logfile.print("Date");
  logfile.print(", ");
  logfile.print("Latitude (5Hz)");
  logfile.print(", ");
  logfile.print("Longitude (5Hz)");
  logfile.print(", ");
  logfile.print("Throttle / %");
  logfile.print(", ");
  logfile.print("FL RPM");
  logfile.print(", ");
  logfile.print("FR RPM");
  logfile.print(", ");
  logfile.print("Acc X / m/s2");
  logfile.print(", ");
  logfile.print("Acc Y / m/s2");
  logfile.print(", ");
  logfile.print("Acc Z / m/s2");
  logfile.print(", ");
  logfile.print("LinAcc X / m/s2");
  logfile.print(", ");
  logfile.print("LinAcc Y / m/s2");
  logfile.print(", ");
  logfile.print("LinAcc Z / m/s2");
  logfile.print(", ");
  logfile.print("GracAcc X / m/s2");
  logfile.print(", ");
  logfile.print("GracAcc Y / m/s2");
  logfile.print(", ");
  logfile.print("GracAcc Z / m/s2");
  logfile.print(", ");
  logfile.print("Heading / deg");
  logfile.print(", ");
  logfile.print("Roll / deg");
  logfile.print(", ");
  logfile.print("Pitch / deg");
  logfile.print(", ");
  logfile.print("Acc Calibration");
  logfile.print(", ");
  logfile.print("Gyroscope Calibration");
  logfile.print(", ");
  logfile.print("System Calibration");
  logfile.println();
  logfile.flush(); //Waits for the transmission of outgoing serial data to complete
}

// Interrupt is called once a millisecond, looks for any new GPS data, and stores it
SIGNAL(TIMER0_COMPA_vect) {
  char c = GPS.read();
}

void useInterrupt(boolean v) {
  if (v) {
    // Timer0 is already used for millis() - we'll just interrupt somewhere
    // in the middle and call the "Compare A" function above
    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  } else {
    // do not call the interrupt function COMPA anymore
    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

double convertDegMinToDecDeg (float degMin) {
  // converts lat/long from Adafruit degree-minute (DDM) format to decimal-degrees (DD)
  double min = 0.0;
  double decDeg = 0.0;

  //get the minutes, fmod() requires double
  min = fmod((double)degMin, 100.0);

  //rebuild coordinates in decimal degrees
  degMin = (int) ( degMin / 100 );
  decDeg = degMin + ( min / 60 );
  return decDeg;
}

void FLdetect() {
  //This function is called whenever a magnet/interrupt is detected by the Arduino
   FLtooth++;
   Serial.print("teeth: ");
   Serial.println(FLtooth);
 }

void FRdetect() {
  //This function is called whenever a magnet/interrupt is detected by the Arduino
  FRtooth++;
  Serial.print("teeth: ");
  Serial.println(FLtooth);
}

void FL_RPM() {
  //Measure RPM
  if (FLtooth >= 5) {
    FLrpm = (10.0*1000/((millis() - FLtime)));
    FLtime = millis();
    FLtooth = 0;
    return FLrpm;
  }
}

void FR_RPM() {
  //Measure RPM
  if (FRtooth >= 5) {
    FRrpm = (10.0*1000/((millis() - FRtime)));
    FRtime = millis();
    FRtooth = 0;
    return FRrpm;
  }
}

void loop() {
  if (!usingInterrupt) {
    // read data from the GPS in the 'main loop'
    char c = GPS.read();
  }
  // if a sentence is received, we can check the checksum, parse it...
  if (GPS.newNMEAreceived()) {
    // a tricky thing here is if we print the NMEA sentence, or data
    // we end up not listening and catching other sentences!
    // so be very wary if using OUTPUT_ALLDATA and trytng to print out data
    Serial.println(GPS.lastNMEA());
    // this also sets the newNMEAreceived() flag to false
    if (!GPS.parse(GPS.lastNMEA()))
      // this also sets the newNMEAreceived() flag to false
      return;
      // we can fail to parse a sentence in which case we should just wait for another
  }

  if (updateSensorData) {
    //Keep the updating of data as a separate task
    mySensor.updateAccel(); //Update the Accelerometer data
    mySensor.updateLinearAccel(); //Update the Linear Acceleration data
    mySensor.updateGravAccel(); //Update the Gravity Acceleration data
    mySensor.updateEuler(); //Update the Euler data into the structure of the object
    mySensor.updateCalibStatus(); //Update the Calibration Status
    updateSensorData = false;
  }

  FL_RPM();
  FR_RPM();
  APPSvalue = map(analogRead(APPSpin), 552, 710, 0, 100) ;

  // if millis() or timer wraps around, we'll just reset it
  if (timer > millis()) timer = millis();

  // approximately every 2 seconds or so, print out the current stats
  if (millis() - timer > 100) {
    timer = millis(); // reset the timer
    logfile.print((int)GPS.fix);
    logfile.print(", ");
    logfile.print(GPS.hour, DEC); logfile.print(':');
    logfile.print(GPS.minute, DEC); logfile.print(':');
    logfile.print(GPS.seconds, DEC); logfile.print('.');
    logfile.print(GPS.milliseconds);
    logfile.print(", ");
    logfile.print(GPS.day, DEC); logfile.print('/');
    logfile.print(GPS.month, DEC); logfile.print("/20");
    logfile.print(GPS.year, DEC);
    logfile.print(", ");
    logfile.print(convertDegMinToDecDeg(GPS.latitude),6);
    logfile.print(", ");
    logfile.print(-convertDegMinToDecDeg(GPS.longitude),6);
    logfile.print(", ");
    logfile.print(APPSvalue,2);
    logfile.print(", ");
    logfile.print(FLrpm,2);
    logfile.print(", ");
    logfile.print(FRrpm,2);
    logfile.print(", ");
    logfile.print(mySensor.readAccelX()); //Accelerometer X-Axis data
    logfile.print(", ");
    logfile.print(mySensor.readAccelY()); //Accelerometer Y-Axis data
    logfile.print(", ");
    logfile.print(mySensor.readAccelZ()); //Accelerometer Z-Axis data
    logfile.print(", ");
    logfile.print(mySensor.readLinearAccelX()); //Linear Acceleration X-Axis data
    logfile.print(", ");
    logfile.print(mySensor.readLinearAccelY()); //Linear Acceleration Y-Axis data
    logfile.print(", ");
    logfile.print(mySensor.readLinearAccelZ()); //Linear Acceleration Z-Axis data
    logfile.print(", ");
    logfile.print(mySensor.readGravAccelX()); //Gravity Acceleration X-Axis data
    logfile.print(", ");
    logfile.print(mySensor.readGravAccelY()); //Gravity Acceleration Y-Axis data
    logfile.print(", ");
    logfile.print(mySensor.readGravAccelZ()); //Gravity Acceleration Z-Axis data
    logfile.print(", ");
    logfile.print(mySensor.readEulerHeading()); //Heading data
    logfile.print(", ");
    logfile.print(mySensor.readEulerRoll()); //Roll data
    logfile.print(", ");
    logfile.print(mySensor.readEulerPitch()); //Pitch data
    logfile.print(", ");
    logfile.print(mySensor.readAccelCalibStatus()); //Accelerometer Calibration Status (0 - 3)
    logfile.print(", ");
    logfile.print(mySensor.readGyroCalibStatus()); //Gyroscope Calibration Status (0 - 3)
    logfile.print(", ");
    logfile.print(mySensor.readSystemCalibStatus()); //System Calibration Status (0 - 3)
    logfile.println();
    logfile.flush();
    updateSensorData = true;
  }
}


text:
Q: Rails 6 how to check if sidekiq job is running In my Rails 6 API only app I've got FetchAllProductsWorker background job which takes around 1h30m.
module Imports
  class FetchAllProductsWorker
    include Sidekiq::Worker
    sidekiq_options queue: 'imports_fetch_all'

    def perform
      # do some things
    end
  end
end

During this time the frontend app sends requests to the endpoint on BE which checks if the job is still running. I need to send true/false of that process. According to the docs there is a scan method - https://github.com/mperham/sidekiq/wiki/API#scan but none of these works for me even when worker is up and running:
# endpoint method to check sidekiq status
def status
  ss = Sidekiq::ScheduledSet.new

  render json: ss.scan('FetchAllProductsWorker') { |job| job.present? }
end

The console shows me:
> ss.scan("\"class\":\"FetchAllProductsWorker\"") {|job| job }
=> nil
> ss.scan("FetchAllProductsWorker") { |job| job }
=> nil

How to check if particular sidekiq process is not finished?

A: Maybe this will be useful for someone. Sidekiq provides programmatic access to the current active worker using Sidekiq::Workers https://github.com/mperham/sidekiq/wiki/API#workers
So based on that we could do something like:
active_workers = Sidekiq::Workers.new.map do |_process_id, _thread_id, work|
  work
end

active_workers.select do |worker|
  worker['queue'] == 'imports_fetch_all'
end.present?


text:
Q: How to write an address search plugin? I am migrating some users from MapInfo to QGIS, and before they sign off on it, they want a very simple address search in the same way that we currently have one working in MapBasic.  I;ve been having a look around, but can;t seem to get my head around modifiying the quick find and find by attribute plugins which already exist.
Essentially they currently have the following:
A mapbasic routine which presents the user with portions of the address which they can fill in
Such as
field 1: Building name/number
field 2: Street Name
field 3: Locality
field 4: Town
field 5: Postcode

The process then queries a specific layer using like statements, returns a list of matching records which when clicked zoom to the relevant address.
They are adamant that using the QGIS query builder is going to be 'too complicated' for these users and want me to simplify the process in QGIS to a similar one to the above.
So we have a vector layer containing addresses available in the project - is it possible to mirror this MapInfo functionality - and if so, can anyone provide me with some guidance or point to a tutorial for doing this type of task.
Edit: 15:22 11/06/2013
To Clarify:
The addresses are held in a MapInfo tab file, which is loaded in to the project.  All of the fields that would be queried are of type string - there is an additional useful field called searchAddr which has field 2, 1 and 3 concatenated (split by commas).  The data also contains the coordinates as integers for each location.
So in terms of code (hopefully, if I use how it works in SQL to explain that will make it clear), we would be doing soemthing like:
Select * from <layer>
where searchAddr like '%<field1>%'
and searchAddr like'%<field2>%'
and searchAddr like '%<field3>%'
and Town like '%<field4>%'
and Postcode like '%<field5>%'

Therefore if the user puts in 42 as the House Number in field 1 and postcode AB12 3CD in field 5 the query would be
Select * from <layer>
where searchAddr like '%42%'
and searchAddr like'%%'
and searchAddr like '%%'
and Town like '%%'
and Postcode like '%AB12 3CD%'


text:
Q: Restrict keypress in wpf textbox I have TextBox in WPF where i need to fill the box only by pasting (ctrl +v) not by typing. So i need to restrict entire key press except ctrl+v. Since WPF is not having keypress event i am facing the problem to restrict the keypress

A: Do it WPF style and use ApplicationCommands.Paste and make the textbox readonly.

A: you can add this Key_Down handler to the textBox:
  private void textBox1_KeyDown(object sender, KeyEventArgs e)
   {
      if (e.Modifiers == Keys.Control && e.Key==Key.V)
       {
         //Logic here
       }
      else
        e.handled=true;
   }

A: Provided you don't allow Right Click + Paste, but only Ctrl + V, I would simply check for the Ctrl key modifier being pressed and prevent everything else.

A: So try this:
 myTextBox.KeyDown += new KeyEventHandler(myTextBox_KeyDown);

 private void myTextBox_KeyDown(object sender, KeyEventArgs e)
 {
      if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
      {
            input = myTextBox.Text;
      }
      else
      {
            input = "";
      }

  }

A: <TextBox IsReadOnly="True" Name="Policy_text">
   <TextBox.CommandBindings>
       <CommandBinding Command="ApplicationCommands.Paste" CanExecute="PasteCommand_CanExecute" Executed="PasteCommand_Executed" />
   </TextBox.CommandBindings>
</Textbox>

and in code behind
private void PasteCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = Clipboard.ContainsText();
    }

private void PasteCommand_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        Policy_text.Paste();
    }


text:
Q: how to pass IF condition in sum case when #my code
select('a.client_location_id as location_id','b.name as location_name','c.name as client_name',

    DB::raw('SUM(CASE WHEN a.type = 1 employee_qty THEN 1 ELSE 0 END) as e_qty_in'),

DB::raw('SUM(CASE WHEN a.type = 2 employee_qty  THEN 1 ELSE 0 END) as e_qty_out')
            )

i want to do IF conditioning like , if type = 1 result is SUM employee_qty AS e_qty_in and if type 2 the result is SUM employee_qty AS e_qty_out,

#table


text:
Q: Consuming a SOAP web service (Kronos SaasHR) and saving response into SQL server I have been working on a project to connect to our time reporting vendor's SOAP service and get a report weekly (REST doesn't offer function call for getting the desired report). They have only given us the WSDL which has not been helpful: https://secure.entertimeonline.com/ta/padnos.wsdl and
https://secure.saashr.com/ta/PADNOS.soap
I have added the service reference to my solution and generated the proxy class, but each time I try to fetch the data, I get errors saying "Response is not well-formed XML." and "data at the root level is invalid. Line 1, position 1."
This is my first foray into consuming a web service and I cannot find any helpful material.
private void btnGo_Click(object sender, EventArgs e)
{
    // service reference
    // runReportByName
    TSPHoursWorked.ServiceReference1.runReport_ByNameType rptName = new ServiceReference1.runReport_ByNameType();
    rptName.version = 1;
    rptName.reportCategory = "Calculated Time";
    rptName.reportName = "Calculated Time By Entry";
    rptName.reportSavedName = "DailyHoursWorked";
    rptName.outputType = TSPHoursWorked.ServiceReference1.runReport_ByNameTypeOutputType.XML;

    TSPHoursWorked.ServiceReference1.SaaSHRClient soap = new ServiceReference1.SaaSHRClient();
    soap.ClientCredentials.UserName.UserName = "username";
    soap.ClientCredentials.UserName.Password = "password";
    var requestInterceptor = new InspectorBehavior();
    soap.Endpoint.Behaviors.Add(requestInterceptor);
    soap.runReport_ByName(rptName);
    string requestXML = requestInterceptor.LastRequestXML;
    outputText.Text = requestXML;
    string responseXML = requestInterceptor.LastResponseXML;
    outputText.Text += responseXML;
}

public class InspectorBehavior : IEndpointBehavior
{
    public string LastRequestXML
    {
        get
        {
            return myMessageInspector.LastRequestXML;
        }
    }

    public string LastResponseXML
    {
        get
        {
            return myMessageInspector.LastResponseXML;
        }
    }

    private MyMessageInspector myMessageInspector = new MyMessageInspector();
    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {

    }

    public void Validate(ServiceEndpoint endpoint)
    {

    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(myMessageInspector);
    }
}

public class MyMessageInspector : IClientMessageInspector
{
    public string LastRequestXML { get; private set; }
    public string LastResponseXML { get; private set; }
    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        LastResponseXML = reply.ToString();
    }

    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
    {
        LastRequestXML = request.ToString();
        return request;
    }
}

I would just like help simply connecting to their web service, and get the report and bulk insert into SQL server. Could anyone set me on the right path?
EDIT:
I've installed SoapUI and there are no URLs listed under the soap operation "Actions" column:

A: The problem was with our middle-man vendor to Kronos not having any technical knowledge. After a few weeks and finally getting in touch with Kronos, I was informed that:

*

*a new user must be created without single sign-on

*copy the groups/reports/etc of the main admin account to the new account

*add highest security  privilege to new account

Then you will be able to call the RESTful service. I hope this helps someone because our vendor wasted 2 weeks of our time


text:
Q: Internationalizing numbers and quantities I'm not sure how to properly use NSNumberFormatter for the following case and properly keep the localization/internationalization.
Output in English:
0 bananas
1 banana
5 bananas

What should I do to properly keep internationalization/localization?

A: Internationalization of plurals is a hard problem. I'm no expert, but various languages have various schemes for plurals beyond English's simple "1 is singular, all others are plural". Some languages have different forms for 0, 1, 2, 3, and >3. Given the complexity of languages, there are probably even more complex schemes.
Nothing in Cocoa, including NSNumberFormatter, provides any help beyond just the normal string localization of NSLocalizedString and friends. So, you might use NSLocalizedString with keys like "0 bananas", "1 banana", "2 bananas", "3 bananas", and "%d bananas". Then, use a switch to load the one for the actual quantity of bananas that you wish to format.
Another approach is to punt and use a string like "bananas: %d".
Or you can combine techniques by providing localized strings for 0, 1, and >1, and suggest to translators that they switch to the punt style if those forms aren't sufficient for their language.

A: Ken answered well.
I would add this.
In first approximation, it's better to give full phrases to the translators as grammar varies a lot between languages. But this is not enough. You must be prepared to handle some requests from the translation team. Per example in French, the boat is translated to le bateau, the plane into l'avion (and not le avion). Pretty often, translators uses tricks to avoid such a situation, introducing special cases, but this isn't always possible nor desirable.
Work with the translation team to find the best solutions, and generalize the specific cases to all languages if you can so the code is kept language neutral. Several identical strings are better than language specific cases in the code.
With the time and experience, you'll get used to this. I worked more than 10 years on softwares localized in many languages (between 7 and 23 I think, not completely sure about 23 tho ;). You'll learn where things become problematic and some specifics about these languages. There's not that many problems by the way: plurals, genres, contractions are the most common. Formats are usually well handled by the system locales API. This is very interesting!

A: I just posted JJPluralForm, an adaptation for Mozilla's PluralForm.
With that, you wouldn't have to worry about doing all the if-else, switch-case code to do localizing in your code, which becomes impossible to maintain as your number of localizations grow (Russian has 3 plural rules, Arabic has 6, etc. etc.).
Something like the example you gave could be handled with:
[[JJPluralForm sharedManager] pluralStringForNumber:numberOfBananas
                                    withPluralForms:NSLocalizedString(@"N_BANANAS_PLURAL_STRING", @"")
                                    localizeNumeral:YES];

Each Localizable.strings file then localize N_BANANAS_PLURAL_STRING as a semicolon separated list of plural forms. For English, that would be "%@ banana;%@ bananas".
Check out the project for more details.


text:
Q: Is it ok to use the text on a button to determine current state? I have been using the text to determine the button state and want to know if it is generally accepted ?
I have a datagrid view with a list of items and a "Done" Button. When the user clicks the done button the cell is highlighted green to mark it is done.
I then change the button text to "Undo". So whenever the user scrolls over a "Green" Cell the button text changes to Undo.
I use that text to determine what to do when the button is clicked.
Is this ok? Or should I be using some kind of state monitor?

A: I think this is barely acceptable, but still bad.
Storing the status in a variable is not much more effort and would make the code more maintainable (dont mix processing and GUI).
When you somehow change the text of the button, you would have to adjust the checking too.
Also, this makes updating the GUI (multiple threads or the like) much easier.

A: The pattern I favor in many cases to have private fields which indicate the logical state of controls, and properties which cause the properties of the controls themselves to be updated in a reasonably-timely fashion.  If there's one point of interaction with the properties of the controls themselves, and provided that the fields always represent a valid state, then non-UI-thread code can change the state of the controls without having to synchronize itself with the UI thread; it merely has to ensure that there's a request pending to update the controls when next convenient.
Although your particular example doesn't involve any threading issues, and thus doesn't really benefit from the ease of threading afforded by separating out control state from logical state, using the same pattern for cases requiring multi-threading support as for cases that don't will reduce the number of different patterns one has to deal with.  Additionally, if you use your own fields to represent the different states the controls can have, you can ensure that they will never represent an ambiguous or invalid state.  For example, if a piece of code set the button to "UNDO" rather than "Undo", some other code might decide that "it isn't 'Undo', so it should save", some might decide that "it isn't Save, so it should undo"`, some might do nothing, and some might squawk.  Further, it may be difficult to add any additional states or indications.  For example, one might want to add to the "Undo" button an indication of what would be undone.  If one uses fields to track states, one may be able to add such functionality without disturbing the field that distinguishes between "save" and "undo"; either add another field to keep track of what specific operation should be indicated when the undo button is shown, or else have the "update button text" routine use existing fields to determine that.


text:
Q: Subscript out of bounds on a which statement in R I have data that looks like this:
> head(newdata)
          zero       one real
601 0.01273885 0.9872611    1
602 0.01273885 0.3242234    1

I want to select records where one is greater than .5
When I try this, I get "subscript out of bounds." Why am I getting this error? How do I perform this select?

newDataGoodPredict <- newdata[ which(one>0.5),]
  Error in newdata[which(one > 0.5), ] : subscript out of bounds

A: USE:
 # for matricies (or data.frames)
 newdata[newdata[, "one"] > 0.5, ]

 # for data.frame
 newdata[newdata$one > 0.5, ]

Note that you don't need which

You might have a variable in your environment named one which your statmenet is accessing.  The error is telling you that you are trying to index newdata by an invalid value


text:
Q: How are state changes to JPA entities actually tracked When I java.persistence.EntityManger.find() an @Entity the EntityManager checks the Transaction for an existing instance of its associated persistence context. If one exists, then

*

*if the entity being searched for is present in the context, then that is what is returned to the caller of EntityManager.find

*if the entity being searched for is not present in the context, then EntityManager gets it from the datasource and puts it there, and then that is what is returned to the caller of EntityManager.Find

And if the transaction does not contain an existing instance of the manager's associated persistence context, then the manage creates one, associates it with the transaction, finds the entity in the datasource, and adds it to that context for  management, and then returns that entity to the caller of find.
--> the result is the same in that the caller now has a an managed entity that exists in the persistence context. (important: the persistent context is attached to the transaction, so if the transaction has ended at the point at which the client gets hold of the 'managed' entity, well then the persistence context is no more and the entity is 'detached' an no longer managed).
Now, when I make state changes using setters or other other internal state changing methods on my @entity instance, those changes are tracked because my entity is part of persistence context that will get flushed to the datasource when the transaction finally commits. My question is HOW are the state changes tracked and by what? If I were making the changes via some intermediary object, then that intermediary object could update the persistence context accordingly, but I'm not (or am I?). I'm making the changes directly using my @entity annotated object. So how are these changes being tracked.
Perhaps there are events that are being listened for? Listened for by what? I'm reading books and articles on the subject, but I can't pin this one point down.

A: State changes are tracked by jpa vendor's internal implementation during entity's lifecycle.
Dirty checking strategy is vendor specific. Can be done by fields comparing or bytecode enhancements like posted in JPA dirty checking.
Although it's vendor specific, the PersistentContext will be aware of the state changes during state synchronization, on flush or on commit.
It's important to remember all the points where flushes can be done :

*

*Manually

*Before querying

*Before commit


text:
Q: how to extract a compressed zip file in IPYTHON? I am starting to learn IPYTHON from a book by running code hands on. As given in the book I am not able to run the code with the same output or without error, I am kind of stuck here at this line with an error.
I can find out how to extract a zip file online in a different context from other sources but I would want to troubleshoot this problem so that I know how to handle an error or troubleshoot things later as I proceed. I would want to know what is wrong here that is giving out an error while the same did not show an error to the author of the book. Am I missing any detail here? did I miss changing a file name according to the context etc. Here is the code and error in the environment I was running.
Python 2.7.8 |Anaconda 2.1.0 (64-bit)| (default, Jul  2 2014, 15:12:11) [MSC v.1
500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 2.2.0 -- An enhanced Interactive Python.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import urllib2, zipfile

In [2]: url = 'http://ipython.rossant.net/'

In [3]: filename = 'facebook.zip'

In [4]: downloaded = urllib2.urlopen(url + filename)

In [5]: folder = 'data'

In [6]: mkdir $folder
A subdirectory or file data already exists.

In [7]: mkdir $folder1

In [8]: cd $folder1
C:\Users\think\Documents\Python Scripts\$folder1

In [9]: with open(filename, 'wb') as f:
   ...:     f.write(downloaded.read())
   ...:

In [10]: with zipfile.ZipFile(filename) as zip:
   ....:     zip.extractall('.')
   ....:
 ---------------------------------------------------------------------------
BadZipfile                                Traceback (most recent call last)
<ipython-input-10-e24f3f3a7f9c> in <module>()
----> 1 with zipfile.ZipFile(filename) as zip:
      2     zip.extractall('.')
      3

C:\Users\think\Anaconda\lib\zipfile.pyc in __init__(self, file, mode, compressio
n, allowZip64)
    768         try:
    769             if key == 'r':
--> 770                 self._RealGetContents()
    771             elif key == 'w':
    772                 # set the modified flag so central directory gets writte
n

C:\Users\think\Anaconda\lib\zipfile.pyc in _RealGetContents(self)
    809             raise BadZipfile("File is not a zip file")
    810         if not endrec:
--> 811             raise BadZipfile, "File is not a zip file"
    812         if self.debug > 1:
    813             print endrec

BadZipfile: File is not a zip file

In [11]:

Any help or guidance is appreciated .

A: This is a known problem: see this link. The problem basically comes from a misconfiguration in the server that contains the file: downloading this file from Python sometimes results in a corrupted file. Easiest fix is just to download manually the file through your web browser and extract it in your working directory.

A: You simply named the file facebook.zip, that doesn't make it into a zip file (which is why you are getting that error). Just like if I create a text file hello.txt and then rename it to hello.png it would not be converted to an image.
Try reading it as a normal file:
with open(filename) as foo:
   for line in foo:
      print(line)


text:
Q: Parsing html forms input tag with Beautiful Soup Well, I need to parse html forms, from the "input" , i need to extract the ones with the type "text" and anyone that is not text.
I have this code:
from BeautifulSoup import BeautifulSoup as beatsop

html_data = open("forms.html")

def html_parser(html_data)
    html_proc = beatsop(html_data)
    #We extract the text inputs.
    txtinput = html_proc.findAll('input', {'type':'text'})
    #We extract the any kind of input that is not text.
    listform = ["radio", "checkbox", "password", "file", "image", "hidden"]
    otrimput = html_proc.findAll('input', {'type':listform})

html_parser(html_data)

I use it with local documents, but you can use urllib to request any web page with forms.
Now, the problem, I need to extract the "value" tag of the non-text input forms, and the "name" tag of the text ones.
Does anyone knows how can i do that?
Thanks!

A: To access attribute of element, use element['attribute'].
from BeautifulSoup import BeautifulSoup as beatsop

def html_parser(html_data):
    html_proc = beatsop(html_data)
    #We extract the text inputs.
    txtinput = html_proc.findAll('input', {'type':'text'})
    listform = ["radio", "checkbox", "password", "file", "image", "hidden"]
    otrimput = html_proc.findAll('input', {'type': listform})

    print('Text input names:')
    for elem in txtinput:
        print(elem['name'])

    print('Non-text input values:')
    for elem in otrimput:
        value = elem.get('value')
        if value:
            print(value)
        else
            print('{} has no value'.format(elem))

with open("forms.html") as html_data:
    html_parser(html_data)


text:
Q: Thumbnail for picasa api I am using the picasa api to do a community search and now I want to put thumbnails on the search results too. How do I do this? I want the results to have thumbnails and clicking on a thumbnail should take you to the image in web album.
<?php

require_once 'Zend/Loader.php';

Zend_Loader::loadClass('Zend_Gdata_Photos');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_Query');

$search=$_REQUEST['id'];

$serviceName = Zend_Gdata_Photos::AUTH_SERVICE_NAME;
$user = "abc@gmail.com";
$pass = "password";

$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $serviceName);

$gp = new Zend_Gdata_Photos($client, "Google-DevelopersGuide-1.0");

// Community search queries aren't currently supported through a separate
// class in the PHP client library.  However, we can use the generic
// Zend_Gdata_Query class as an alternative

// URL for a community search request
// Creates a Zend_Gdata_Query
$query = $gp->newQuery("https://picasaweb.google.com/data/feed/api/all");

// looking for photos in the response
$query->setParam("kind", "photo");

// full text search
$query->setQuery($search);

// maximum of 10 results
$query->setMaxResults("6");

// There isn't a specific class for representing a feed of community
// search results, but the Zend_Gdata_Photos_UserFeed understands
// photo entries, so we'll use that class
$userFeed = $gp->getUserFeed(null, $query);
foreach ($userFeed as $photoEntry)
{
 echo $photoEntry->getTitle()->getText() . "
 ";
// The 'alternate' link on a photo represents the link to
// the image page on Picasa Web Albums
$link=$photoEntry->getLink('alternate')->getHref();
echo "";
echo ''.$photoEntry->getLink('alternate')->getHref().'
';
echo "
\n";

}

?>

A: The algorithm:

*

*Get the URL for the photo.

*Parse the URL into its component parts (scheme, host, path, filename).

*Inject the thumbnail qualifier before the filename.

*Reassemble the component parts.

For example:
// Define thumbnail properties (w = width, 200 = pixels).
$THUMBMAIL = "w200";

// Get the "source" URL for the image.
$imgSrc  = $photoEntry->content->getSrc();

// Extract the component parts.
$url = parse_url( $imgSrc );

// Extract the path and inject the thumbnail size.
$url["path"] = dirname( $path ) . "/$THUMBNAIL/" . basename( $path );

// Reassemble the URL.
$thumbnail = build_url( $url );

You should be able to use http_build_url, but I had naming conflicts, so wrote this:
function build_url( $url ) {
  return $url["scheme"] . "://" . $url["host"] . "/" . $url["path"];
}

Read this article for more details.


text:
Q: Simple hide and show text with javascript I am a newbie when it comes to javascript as I am more custom to vba for office.
However, now I want to write several paragraphs at the same page, but only showing the first, say to or three sentences of each paragraf and add a link in the text; see more...
By clicking the link, see more..., it should show the whole paragraph and the link see more... should change to see less... at the end of the paragraf.
I would like to have a javascript function to do this, taking an argument, perhaps an ID of the html.element to show or hide. That way I could reuse code or function, for each paragraph.
Any suggestions or samples would be very appriciated.
So if I have three paragraph at the same page, it should be able to display and hide part of the paragraph for each paragraph independently of each other.
I found this code but it is hard coded:
<button onclick="myFunction()">Click Me</button>

<script>
function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

However, I want to reuse the function for any paragraph I want to. So I tried to make in a function with argument, but it does not seem to work?
    <button onclick="myFunction("myDIV")">Click Me</button>

<script>
function myFunction(EliD) {
  var x = document.getElementById(EliD);
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

Anybody that have a suggestion how to do this?


text:
Q: Swift UIPickerView defaults to last option regardless of selected option I have a UIPickerView that when tapping the done button, keeps selecting the last option of the Array. I can tap on either the UITextField or a button I'm using that assigns the UITextField as the first responder. My code is as follows:
Edit. I should also mention that I'm using Xcode 11 GM Seed if that was to make a difference. I tested a clean version of the code shown below on a separate project with nothing else and it is displaying the same behavior.
@IBOutlet weak var sortTypeTextField: UITextField!

var selectedSortOption = String()

let sortOptions = [
        USER_REVIEWS_SORT_OPTION_DATE,
        USER_REVIEWS_SORT_OPTION_LIKES,
        USER_REVIEWS_SORT_OPTION_DISLIKES
    ]

sortOptions above is an array of Strings located in a different file but for the purpose of this question I'll add here:
let USER_REVIEWS_SORT_OPTION_DATE = "Date"
let USER_REVIEWS_SORT_OPTION_LIKES = "Number of Likes"
let USER_REVIEWS_SORT_OPTION_DISLIKES = "Number of Dislikes"
let DONE_TOOLBAR_BUTTON_TITLE = "Done"

I have a function setupUI which I call in viewDidLoad along with the value for the sortTypeTextField. The value is the first String in the array when the viewController first loads.
override func viewDidLoad() {
    super.viewDidLoad()
    setupUI()
}

func setupUI() {
    sortTypeTextField.text = sortOptions[0]
    createSortPicker()
    createPickerToolbar()
}

func createSortPicker() {
    let sortPicker = UIPickerView()
    sortPicker.delegate = self
    sortTypeTextField.inputView = sortPicker
}

func createPickerToolbar() {
    let toolBar = UIToolbar()
    toolBar.sizeToFit()
    let doneButton = UIBarButtonItem(title: DONE_TOOLBAR_BUTTON_TITLE, style: .plain, target: self, action: #selector(dismissKeyboard))
    toolBar.setItems([doneButton], animated: false)
    toolBar.isUserInteractionEnabled = true
    sortTypeTextField.inputAccessoryView = toolBar
}

@objc override func dismissKeyboard() {
    view.endEditing(true)
}

I'm also using a button to display the UIPicker as shown here:
@IBAction func sortRatingsButtonWasTapped(_ sender: Any) {
    sortTypeTextField?.becomeFirstResponder()
}

As shown below, I want for the sortTypeTextField value to change to the selected option but for some reason when tapping the Done button in the toolbar, the text shown is always the third String in the array regardless if I have chosen the first, the second or the third.
extension ReviewsViewController: UIPickerViewDelegate, UIPickerViewDataSource {

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        sortOptions.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return sortOptions[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectedSortOption = sortOptions[row]
        sortTypeTextField.text = selectedSortOption
    }

}

A: It seems to be a bug in the simulator. I tested the my code above and the code provided by Abdul Karim Khan on my device and the work as they should. The label updates according to the option selected in the picker view.

A: This is how I created pickerView,
class ViewController: UIViewController {

    @IBOutlet weak var selectaday: UITextField!
    let days = ["monday","wednesday"]
    var selectedDay: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        createDayPicker()
    }

    func createDayPicker(){
        let dayPicker = UIPickerView()
        dayPicker.delegate = self
        selectaday.inputView = dayPicker
    }

}

extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource{
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return days.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return days[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectedDay = days[row]
        selectaday.text = selectedDay
    }

}


text:
Q: Is there a way to make buffer() writable without copying when the size argument is set? If an object is mutable then it's possible to get a modifiable buffer by not the specifying the second argument of buffer() (which is a built‑in function) like this :
>>> s = bytearray(1000000)   # a million zeroed bytes
>>> t = buffer(s, 1)         # slice cuts off the first byte
>>> s[1] = 5                 # set the second element in s
>>> t[0]                     # which is now also the first element in t!
'\x05'

However, in my case, I need to specify0x7fffffffas the size parameter. In that case :
>>> b = buffer(bytearray('a'), 1,0x7fffffff)

how to make b writeable without copying it's data ? In my case_ctypessupport is disabled and the program isn't launched as root.
Of course, thing like memoryview are available, but I loose the possibility to read the memory at every virtual addresses.

A: The copy is necessary. The bytearray's internal buffer simply isn't 2 GiB long; if you want a 2 GiB buffer, you will need to copy the bytearray's data into a new buffer.
If you were to somehow force Python to treat the buffer as the size you want it to be without making a copy, writing to it would corrupt your process's memory and/or cause a segfault.


text:
Q: Python str.maketrans Remove Punctuation with Empty Space I am using maketrans from string module in Python 3 to do simple text preprocessing like lowering, removing digits and punctuations. The problem is that during the punctuation removal all words are attached together with no empty space! For example, let's say I have the following text:
text='[{"Hello":"List:","Test"321:[{"Hello":"Airplane Towel for Kitchen"},{"Hello":2 " Repair massive utilities "2},{"Hello":"Some 3 appliance for our kitchen"2}'

text=text.lower()
text=text.translate(str.maketrans(' ',' ',string.digits))
Works just fine, it gives:
'[{"hello":"list:","test":[{"hello":"airplane towel for kitchen"},{"hello": " repair massives utilities "},{"hello":"some  appliance for our kitchen"}'

But once I want to remove the punctuations:
text=text.translate(str.maketrans(' ',' ',string.punctuation))

It gives me this:
'hellolisttesthelloairplane towel for kitchenhello nbsprepair massives utilitiesnbsphellosome  appliance for our kitchen'

Ideally it should yield:
'hello list test hello airplane towel for kitchen hello nbsp repair massives utilities nbsp hello some  appliance for our kitchen'

There is not specific reason I am doing it with maketrans, but I like as it is fast and easy and kind of stuck solving it. Thanks!
Disclaimer: I already know how to do it with re like the following:
import re
s = "string.]With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)

A: well... this works
txt = text.translate(str.maketrans(string.punctuation, ' ' * len(string.punctuation))).replace(' '*4, ' ').replace(' '*3, ' ').replace(' '*2, ' ').strip()


text:
Q: How to return REST data to observable and then apply logic on APP_INITIALIZER? [Angular 12] In my angular 12 app Im trying to return some api data before any of my other components load (including the app component). I want to place some returned items in local storage that will be able to reference img urls and other style attributes across the app globally.
I have implemented an APP_INITIALZER class and have called one of our endpoints to grab the mentioned style data. Since promises are being depreciated I am trying to return the items with an observable since they are now available to app initializers in v12.
Here is some of my code:
Method calling app loader in module.ts
export function serviceLoader(appLoader: AppLoaderService){
  return ()=> appLoader.init();
}

AppLoader Init Method:
init(){
return  this.styleService.getStyles()
       .subscribe(res=>{
          console.log('DATA: ', res);
          this.localStorageService.portal = {
                      color: res.portalPrimaryColour,
                      primaryImage: res.portalImageUrl,
                      logo: res.portalLogoUrl
          };
          console.log('portal: ', localStorage.getItem("portal"));
        },
        err =>{
        this.localStorageService.portal = {
                        color: 'blue',
                        primaryImage: 'assets/images/img.png',
                        logo: 'assets/images/logo.png'
            };
        });
}

My issue is that I cant figure out an elegant way set local storage values AFTER any data OR an error has come from the backend. The app intializer will not wait for the .subscribe res or err functions to come back before returning to the app (I understand this is a limit of an Observable and have also tried .map).
I can ensure data comes back by merely not subscribing to the getStyles() method and doing some logic inside it like this:
this.styleService.getStyles()

getStyles Method:
  getStyles() : Observable<any>{
   return this.http.get<any>(this.apiService.baseUrl + 'portal_style', httpOptions)
          .pipe(tap((data) =>
          {
            console.log('DATA: ', data);
            this.localStorageService.portal = {
                        color: data.portalPrimaryColour,
                        primaryImage: data.portalImageUrl,
                        logo: data.portalLogoUrl,
            };
            console.log('portal: ', localStorage.getItem("portal"));
          }
}

However, with that way of doing it I am having issues with adding error catching and custom logic to errors (such as adding hardcoded local storage values). Not to mention that the Observable must finish or the app will not bootstrap.
So I guess my question is - based off the above - does anyone know an elegant way of returning an observable to an app initializer and doing custom logic when its back (and do different logic and handle errors when they come back)?
Thanks!

A: As said in the documentation, APP_INITIALIZER can be a function which returns a Promise or an Observable. However you are not returning an observable nor a promise, you are returning the Subscription of a stream. That's why the Angular application bootstraps even when your request is not finished.

A: Sounds like a race condition between the data from the API and you initializing your work based on that data. Consider getting your data first, then piping your styleService function to remove this race condition.
// DataService.ts
@Injectable()
export class DataService {
    data: Data'

    constructor(private http: HttpClient) {}

    getDataFromServer(): Observable<Data> {
        if (this.data) {
            return of(data);
        } else {
            return this.http.get('my/api/call').pipe(
                mergeMap(response => {
                    this.data = response;
                    return of(response);
                });
        }
    }
}

// StyleService.ts
@Injectable()
export class StyleService {
    constructor(private http: HttpClient) {}

    getStyles(): Observable<Data> {
        return this.http.get("my/style/call");
    }
}

// MyComponent.ts
@Component({
    selector: 'app-mycomponent',
    templateUrl: './myComponent.component.html',
    styleUrls: ['./myComonent.component.scss'],
})
export class myComonentComponent implements OnInit {
    private data: Data;

    constructor(private dataService: DataService, private styleService: StyleService) {}

    ngOnInit() {
         this.dataService.getData().pipe(
            mergeMap((data: Data) => {
                this.data = data;
                // save to localStorage if you want. You can also do it within the getData call but this also allows you to skip saving it in the localStorage
                return this.styleService.getStyles();
            })
           .subscribe(res => {
              console.log('DATA: ', res);
              // use this.data where needed
              // no changes were made below this line

              this.localStorageService.portal = {
                          color: res.portalPrimaryColour,
                          primaryImage: res.portalImageUrl,
                          logo: res.portalLogoUrl
              };

              console.log('portal: ', localStorage.getItem("portal"));
            },
            err => {
                this.localStorageService.portal = {
                                color: 'blue',
                                primaryImage: 'assets/images/img.png',
                                logo: 'assets/images/logo.png'
                    };
            });
    }
}


text:
Q: Brian Aldiss short story about caveats of advanced military technology I'm trying to remember a short story I read many years ago about the negative side of developing and deploying advanced weapons technology in an SF setting. It was about some intergalactic power that was trying to crush an adversary by using multiple new military technologies and how each one in turn caused this power so much grief it was defeated by the adversary. I think it was also required reading for military strategists at some schools here in the US, at least at the time I read it. I think the story was written by Brian Aldiss.

A: I will suggest that this is actually the classic story "Superiority" by Arthur C. Clarke, first published in The Magazine of Fantasy and Science Fiction, August 1951.  You can read it at the Internet Archive.
The advanced civilization is menaced by a more vigorous, but in every other way inferior enemy, but at every stage they are convinced to wait for yet another advance that will fix the problems of the previous advance and make victory even more assured.  But nothing ever works well enough to make up for the delay, and ultimately the war is lost because no ship is ever available and in shape to fight.

The ultimate cause of our failure was a simple one: despite all statements to the contrary, it was not due to lack of bravery on the part of our men, or to any fault of the Fleet's. We were defeated by one thing only - by the inferior science of our enemies. I repeat - by the inferior science of our enemies.

It was Professor-General Norden who kept seducing the high command with the prospect of ever-better weapons and tactics in the future:

Norden's words left an uncomfortable impression, as he had no doubt intended. He quickly pressed home the attack.
"What we want are new weapons - weapons totally different from any that have been employed before. Such weapons can be made: it will take time, of course, but since assuming charge I have replaced some of the older scientists with young men and have directed research into several unexplored fields which show great promise. I believe, in fact, that a revolution in warfare may soon be upon us."

His "Sphere of Annihilation" destroys the projector, so it has to be turned into missiles, at great cost and expense of time.  And then there are problems with the new weapon, so it still can't be deployed.
The "Battle Analyzer" is too big, and too man-power intensive and ultimately too fragile in battle.
Finally the "Exponential Field" destroys the entire fleet; it never returns to exactly the same starting point, so after every use, everything goes out of adjustment, and parts don't even work between ships.  No standard spares are possible, and the fleet falls apart.


text:
Q: How can I prevent R6 classes to access non-existent members? R6 automatically sets to NULL anything I access on self
> x <- R6::R6Class("x", list(foo = function() { print(self$notexistent) }))
> xx <- x$new()
> xx$foo()
NULL

This means that if I make a typo in one access e.g. results instead of result it will use NULL instead of throwing an error. Is there a way to force the latter?

A: The self in an R6 function is an environment. The $ operator for environments is a primitive, and as far as I can tell it can't be overwritten. By default this operator returns NULL rather than throwing an error if the right-sided operand isn't found in the environment, and this fact has to be explicitly handled by the caller.
This isn't so different from, say, the [ operator in C++, which doesn't bounds check a vector. Unless you explicitly check your bounds, your program will crash. If you want to bounds check you need to use a different operator like .at: these will be safer, but will also slow your software down. It boils down to priorities. You either go fast or you change syntax and check.
Therefore if you would prefer bounds-checking behaviour from self, you need to write a different, safer accessor with different syntax.
`%$%` <- function(env, member) {
  member <- deparse(substitute(member))
  ls <- eval(as.call(list(quote(ls), substitute(env))),
                     envir = parent.frame())
  if(!member %in% ls) stop(member, " is not a member of this R6 class")
  eval(as.call(list(quote(`[[`), substitute(env), member)),
       envir = parent.frame())
}

x <- R6::R6Class("x", list(foo = function() print(self%$%notexistent),
                           bar = function() print(self%$%baz),
                           baz = 1))
xx <- x$new()

xx$foo()
#> Error in self %$% notexistent :
#>   notexistent is not a member of this R6 class

xx$bar()
#> [1] 1

You may not like the fact that you can't use the $ operator in this way, but that's the way R is. I think it's clear you don't like the language, and I can't change that, but until your plans to destroy it are realised, you can see it as a challenge...


text:
Q: Issue on single computer only - Conversion from string to type 'Date' is not valid I regret having to write such a vague question, but I'm not really sure what to try. I have general programming experience, but no access to the source code for this and not a lot of experience with VB/.NET
We have a custom (Read: Crappy) CRM software we use at work that was written ~2008 by someone who has long since left the company. It works on both Windows 7 and Windows 10 just fine for multiple users. I am trying help a user with an "Unexpected program error":
"frmMain - FillGridTable
Conversion from string "03/31/2016 15:23:22" to type 'Date' is not valid."
when I close the dialog box it just says "LoopX = 0"
I do not have access to the source code, and regardless, it works on every other computer.
Could this be some issue with some type of library on the computer? Is there any way to check versions between computers for .NET/Microsoft libraries?
Thanks for any ideas!

A: Chase Rocker helped me get here in the comment he left on the question.
The windows date/time format settings were displaying a date that wasn't in the correct format. Resolved this by changing it to the MM/dd/YYYY format the error was suggesting the program expected.

A: I'm glad to see that you solved the issue by changing the computer's regional settings, but to be honest this is probably overkill for what you're wanting to do. Instead, you could have used the DateTime.TryParseExact function.
Here is a quick example of utilizing the built-in method:
Dim conversion As DateTime
Dim input As String = "11/30/2017"

If DateTime.TryParseExact(input, "MM/dd/yyyy", New CultureInfo("en-US"), DateTimeStyles.None, conversion) Then
    'Converted successfully
Else
    'A true conversion error occured
End If

Fiddle: Live Demo


text:
Q: закрытие окна в java swing как закрыть окно через 60 секунд после бездействия пользователя ?
Были мысли использовать многопоточность и цикл while() но как реализовать не совсем понимаю

A: В целом я вижу здесь несколько потенциально возможных решений. Для выбор оптимального из них у меня недостаточно исходных данных, поэтому предложу то, которое ан мой взгляд в данном случае будет наиболее применимое. Если вы никогда не слышали про слушатели, то самое время прочитать об этом. Итак, пишем довольно простой класс:
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class ActivityListener {

    private final int idleTimeSeconds;
    private final AtomicReference<LocalDateTime> lastClickAt;
    private final ScheduledExecutorService scheduler;

    private ActivityListener(int idleTimeSeconds) {
        this.scheduler = Executors.newSingleThreadScheduledExecutor();
        this.lastClickAt = new AtomicReference<>(LocalDateTime.now());
        this.idleTimeSeconds = idleTimeSeconds;
    }

    public static Runnable of(int idleTimeSeconds) {
        ActivityListener activityListener = new ActivityListener(idleTimeSeconds);
        activityListener.execute();
        return () -> activityListener.activate();
    }

    private void execute() {
        long delay = Duration.between(LocalDateTime.now(), lastClickAt.get().plusSeconds(idleTimeSeconds)).getSeconds();
        if (delay <= 0) System.exit(0);
        else scheduler.schedule(() -> execute(), delay, TimeUnit.SECONDS);
    }

    public void activate() {
        lastClickAt.set(LocalDateTime.now());
    }

}

При старте вашего приложения вы должны выполнить достаточно нехитрое действие:
Runnable runnable = ActivityListener.of(60);

В данном случае 60 - это описанные вами 60 секунд, таким образом, вы можете легко менять время "ожидания" до автоматического прекращения работы вашего приложения.
Конструктор данного класса приватный, а инициализация выполняется статическим методом of(), что нарушает принцип единой ответственности SOLID, но не думаю, что в данном случае это станет проблемой.
Именно на этом этапе вам потребуется понимание, что такое слушатель. Именно слушатель "активности пользователя" вы и должны будете добавить в свое приложение, а при срабатывании этого слушателя вам необходимо вызывать метод runnable.run() у переменной типа Runnable , которую мы инициализировали выше.
Вот, собственно, и все...


text:
Q: Are there any advantages to GMP over MPIR? Both seem to be decent bignum libraries but I am not sure what the pros/cons of each are. I know this is a broad question but I am mostly after the prominent differences.

A: MPIR began as a fork of GMP so they share much code. The most obvious difference is that MPIR can be compiled by MS Visual Studio with optimized assembly language support. The latest MPIR release (2.6.0) includes a new FFT multiplication algorithm that is faster than GMP 5.0 (for the sizes I tested, YMMV). On the other hand, GMP is available on almost all Linux distributions.


text:
Q: Function in if statement: error expected expression I want to compile following file:
https://gist.github.com/bodokaiser/5382281
which does not succeed because I get following error:
  CXX(target) Release/obj.target/parser/src/parser/parser.o
In file included from ../src/parser/parser.cc:2:
../src/parser/calc_head_size.cc:67:16: error: expected expression
    if (mask || isMasking(masking)) {
               ^
1 error generated.
make: *** [Release/obj.target/parser/src/parser/parser.o] Error 1

This does not make sense to me. Can it be that there is something else wrong?
Bodo

A: You seem to have a strange character in your source code that looks like a space but isn't. In this line:
if (mask || isMasking(masking)) {
//         ^ here

try to delete the "space" and add a real space.


text:
Q: How to pass data from terminal in elixir Hello I want to execute an elixir file and passing one string in my terminal and read it in the script. Something like this:
User>elixir script.exs create

I want the word "create" to be readed by elixir.
Thank you.

A: You can access the list of arguments using System.argv/0:
$ cat a.exs
IO.inspect System.argv
$ elixir a.exs foo bar
["foo", "bar"]


text:
Q: How to build automatic divide the column value? I have some dataframe which have different ncol. I want to replace the value by the certain rule which is from the second column the value in this column should be the original one divide the value before it. For example:
df= data.frame(rep(60,3),c(40:42),c(30:32),c(1:3))
colnames(df) <- c(1,2,3,4)
> df
  1  2  3  4
1 60 40 30 1
2 60 41 31 2
3 60 42 32 3
#rule:all the first column should divide 100, the second col divide first col
#     the third col divide second col and so on.
#ideal result
  1    2      3     4
1 0.6 0.667 0.75  0.033
2 0.6 0.683 0.756 0.065
3 0.6 0.7   0.762 0.094
#the only idea I got now is that use Map and manual replace it
u1<-df$'1'/100
u2<-Map("/",df$`2`,df$`1`)
...
allu <- dataframe(u1,u2,...)

Is that any possibility to do this automatically with different ncol? Thank you in advance : )

A: We can do this by removing the first column (df[-1]) and last column (df[-ncol(df)]), divide it so that we are dividing alternate columns, and cbind with the first column divided by 100
cbind(df[1]/100, df[-1]/df[-ncol(df)])
#    1         2         3          4
#1 0.6 0.6666667 0.7500000 0.03333333
#2 0.6 0.6833333 0.7560976 0.06451613
#3 0.6 0.7000000 0.7619048 0.09375000


text:
Q: While function in echo I have some php code that looks like :
echo"

" . get_comment(${'imgmodp_data_' . $i}['primid']) . "

 ";

My get_comment function:
function get_comment($primid)
{
    $dbCon = mysqli_connect("localhost", "something", "something", "something");
    $sql = "SELECT `id_sheep`, `text` FROM `comments` WHERE `primid`='$primid'";
    $query = mysqli_query($dbCon, $sql);

    while($row = mysqli_fetch_array($query))
    {
        return = "
" . $row['text'] . "

";
    }
}

But this only returns one row each time even if they is multiple rows. If I use echo instead of return it returns all lines but at the top of my document, not in the blocks where it should be...
Any suggestions?

A: Use a variable before your loop, which you update inside your loop and return after your loop.
If you just use return, you'll stop the function, so after 1 loop.
With echo you output the string directly, but don't stop the loop.
For example:
function get_comment($primid){
$dbCon = mysqli_connect("localhost", "something", "something", "something");
$sql = "SELECT `id_sheep`, `text` FROM `comments` WHERE `primid`='$primid'";
$query = mysqli_query($dbCon, $sql);
$return = '';
while($row = mysqli_fetch_array($query)){
    $return .= "
" . $row['text'] . "

";
}
return $return;
}

A: What about this
echo "
" . $row['text'] . "

";

and place the php code where you want it to show.


text:
Q: window.open without popup blocker using AJAX and manipulating the window.location When dealing with OAuth from the server, such as Twitter and Facebook, you most likely will redirect the user to an URL asking for app permission. Usually, after clicking a link, you send the request to the server, via AJAX, and then return the authorization URL.
But when you try to use window.open when the answer is received, your browser blocks the popup, making it useless. Of course, you can just redirect the user to the new URL, but that corrupts the user experience, plus it's annoying. You can't use IFRAMES, but they are not allowed (because you can't see the location bar).
So how to do it?

A: Try adding async: false. It should be working
$('#myButton').click(function() {
$.ajax({
    type: 'POST',
    async: false,
    url: '/echo/json/',
    data: {'json': JSON.stringify({
        url:'http://google.com'})},
    success: function(data) {
        window.open(data.url,'_blank');
    }
});
});

A: The answer is quite simple, and works cross browser without any issues. When doing the AJAX call (I'll be using jQuery in this example), just do the following. Suppose we have a form with two buttons, Login with Twitter and Login with Facebook.
<button type="submit" class="login" value="facebook" name="type">Login with Facebook</button>
<button type="submit" class="login" value="twitter" name="type">Login with Twitter</button>

Then the Javascript code where the magic happens
$(function () {
    var
        $login = $('.login'),
        authWindow;

    $login.on('click', function (e) {
        e.preventDefault();
        /* We pre-open the popup in the submit, since it was generated from a "click" event, so no popup block happens */
        authWindow = window.open('about:blank', '', 'left=20,top=20,width=400,height=300,toolbar=0,resizable=1');
        /* do the AJAX call requesting for the authorize URL */

        $.ajax({
            url: '/echo/json/',
            type: "POST",
            data: {"json": JSON.stringify({"url": 'http://' + e.target.value + '.com'})}
            /*Since it's a jsfiddle, the echo is only for demo purposes */
        })
        .done(function (data) {
            /* This is where the magic happens, we simply redirec the popup to the new authorize URL that we received from the server */
            authWindow.location.replace(data.url);
        })
        .always(function () {
            /* You can poll if the window got closed here, and so a refresh on the main page, or another AJAX call for example */
        });
    });
});

Here is the POC in JSFiddle http://jsfiddle.net/CNCgG/
This is simple and effective :)


text:
Q: How can one obtain the message from state-reverting exception using ethereum clients, when self did not broadcast transaction? Suppose an ethereum smart contract has external function "foo" whose logic has state-reverting exception require(1 == 0, 'error: you broke the simulation!');.
If ethereum-client A broadcasts transaction "txA" which is a function call on foo, how can ethereum-client B access the state-reverting message corresponding to "txA"?
edit: by "how can", I mean how can a developer practically enable ethereum-client B to access this data. i.e. Can you please point me in the direction of the correct (lower-level.. not webui) api/rpc call from a particular tool?
Clearly this is possible since block explorers provide such messages for failed transactions. I read through some of the source of etherscan, but their javascript is minimized and not easily readable.
Thanks in advance!

A: See this: https://ethereum.stackexchange.com/questions/39817/are-failed-transactions-included-in-the-blockchain
Failed transactions often are included in the chain.
What you sometimes see, if you're using e.g. MetaMask, is a popup saying "this transaction will fail" that happens before the transaction is sent to the chain. This is MetaMask trying to be helpful and prevent you wasting gas. But you can force send the transaction anyway, and you'll get a failed/reverted transaction posted on-chain (like this one for this Solidity source).
So to answer the original question, if TxA was posted on-chain, then client B will process it and get the revert message itself. If TxA was not posted on-chain, then there is no record of it.