text:
Q: Damped harmonic Oscillator Lagrangian equivalence The objective is to prove that the Lagrangian:
$$L'=\frac{2\dot x+\lambda x}{2\Omega x}\tan^{-1}(\frac{2\dot x+\lambda x}{2\Omega x})-\frac{1}{2}\ln(\dot x^2+\lambda \dot{x } x + \omega^2x^2), \qquad \Omega=\sqrt{\omega^2-\lambda^2/4},$$
is equivalent to the lagrangian of the damped harmonic oscillator:
$$L=e^{\lambda t}(\frac{m}{2}\dot x^2 -\frac{m\omega^2}{2}x^2), $$
but I dont know how to show that there is a time derivative of a function that differs from one Lagrangian to the other;
(It's exercise 2.14 from Nivaldo Lemos, Analytical Mechanics, 2018.)

A: Hints:

*

*Two Lagrangians, whose difference is not a total derivative, can still yield the same EOM, cf. e.g. this & this Phys.SE posts.

*Check that both Lagrangians lead to the same EOM $\ddot{x}+\lambda \dot{x}+\omega^2x~=~0$ of the damped harmonic oscillator.


text:
Q: VB6 application requiring comdlg32.ocx, running on windows server 2008 I have a legacy vb6 application that needs to run on a server 2008 machine.
I have been unable to get comdlg32.ocx to register, which the application depends on. Any suggestions?

A: Hmm, does this link help you at all?
My only other suggestion is that often dependency walker is useful in these sorts of situations, in particular if you are running this vb6 application on a 64 bit OS then pay attention to whether or not comdlg32.ocx has all of its dependencies present as 32 bit libraries.

A: The obvious, but are you running Regsvr32 as an Admin?

A: If you do not want to bother about copying and registering the comdlg32.ocx file (for which you might need administrator rights anyway), check out following project, that shows how you can use the common dialog box (open and save) without using the ocx file and thus without need of registering it. It uses the comdlg32.dll directly with APIs, which is installed already on windows!
http://www.soft-hummingbird.com/Tutorial_VB_ComdlgAPI.php?lang=en
The File Backupper is a nice peace of software, that uses exactly this:
http://www.soft-hummingbird.com/File_Backupper.php?lang=en

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make UIImage move every hour? Hey so I'm working on a simple app and I want this image on a map to move closer hour by hour towards the user location. I can't figure out where to start, can anyone help?
Thanks!

A: Swift has a Timer class.  There are several overloads for Timer.init.  The newer block based one works like this:
    let hour = TimeInterval(60 * 60) //60 seconds per min * 60 min per hour = 360 seconds per hour
    let timer = Timer.init(timeInterval: hour, repeats: true) { timer in
        //Do hourly update stuff here
    }


text: Q: Edit the labels of tables in wave analytics I wanted to edit the labels of tables in wave analytics .I tried to edit the dataset by adding label but again it needs an xmd 2 version. can anyone suggest me a way to do it.Thanks in advance!


text:
Q: Android game collision detection i have a question about android games.I cant make a collision between 2 objects.The rectangle collision seems work perfect in java but in android is not. I am using
the intersect method to check collision.If you guys have some tips or answer to my question please feel free to tell me , i will appreciate all kind of help.Thanks in advance.

A: Collision detection never has anything to do with the platform and language. The algorithm you use should work properly if it's a good one.
Here's an article to get you started and give you a good hint as to how to proceed about it.
There are certain libraries to help your cause.I recommend you to use the Box2d library.It is a physics engine with good support for collision. You can find an example on the front page of the site as well.


text:
Q: How to remove bootstrap datepicker? In jQuery UI DatePicker, we are able to dynamically remove the datepicker from the textbox input. (Remove Datepicker Function Dynamically)
Is it possible to do so in Bootstrap datepicker?

A: Maybe this can do the trick:
showOnFocus
Boolean. Default: true

If false, the datepicker will be prevented from showing when the input field associated with it receives focus.


text:
Q: How to delete the rows corresponding to the selected `yes` input?

function removeItem(){
     var _table=document.getElementById("test");
     var len=_table.rows.length;
     for(var i=0;i<len;i++){
        tr=_table.rows[i];
         if(tr.cells[0].firstChild.checked==true){
            tr.parentNode.removeChild(tr);
            }
        }
    }

to_remove	f1	f2	f3

<input  type="radio" name="delete1">yes<input  type="radio" name="delete1">no	1	2	3

<input  type="radio" name="delete2">yes<input  type="radio" name="delete2">no	4	5	6

<input  type="radio" name="delete3">yes<input  type="radio" name="delete3">no	7	8	9

<input  type="radio" name="delete4">yes<input  type="radio" name="delete4">no	10	11	12

<input  type="radio" name="delete5">yes<input  type="radio" name="delete5">no	20	11	12

<input  type="radio" name="delete6">yes<input  type="radio" name="delete6">no	30	11	12

 <input type="button" value="remove" onclick="removeItem()">

There are some bugs in my js to delete rows.
1.For the first time ,to select two rows to delete.

2.To click remove, the selected rows was removed, an error occur after removing two rows.

3.For the second time,to select two rows to delete as the first time do.

4.To click remove, only one row was removed, same error occur after removing one row.

There are two bugs for my js code here.
bug1: Which result in the error after removing row?
Why tr is undefined?
bug2: Why only remove one row when to select two rows in my second selection?

A:

function removeItem(){
     var _table=document.getElementById("test");
     var len=_table.rows.length
     for(var i=len-1;i>=0;i--){
        tr=_table.rows[i];
         if(tr.cells[0].firstChild.checked==true){
            tr.parentNode.removeChild(tr);
            }
        }
    }

to_remove	f1	f2	f3

<input  type="radio" name="delete1">yes<input  type="radio" name="delete1">no	1	2	3

<input  type="radio" name="delete2">yes<input  type="radio" name="delete2">no	4	5	6

<input  type="radio" name="delete3">yes<input  type="radio" name="delete3">no	7	8	9

<input  type="radio" name="delete4">yes<input  type="radio" name="delete4">no	10	11	12

<input  type="radio" name="delete5">yes<input  type="radio" name="delete5">no	20	11	12

<input  type="radio" name="delete6">yes<input  type="radio" name="delete6">no	30	11	12

 <input type="button" value="remove" onclick="removeItem()">

just go in opposite direction to stay in the loop range (the length is decremented each time you are deleting the row)

A: I have updated your snippet. As you are removing the row while looping you should loop from the last element.

function removeItem(){
     var _table=document.getElementById("test");
     var len=_table.rows.length
     for(var i=len-1;i > 0;i--){
        tr=_table.rows[i];
         if(tr.cells[0].firstChild.checked==true){
            tr.parentNode.removeChild(tr);
            }
        }
    }

to_remove	f1	f2	f3

<input  type="radio" name="delete1">yes<input  type="radio" name="delete1">no	1	2	3

<input  type="radio" name="delete2">yes<input  type="radio" name="delete2">no	4	5	6

<input  type="radio" name="delete3">yes<input  type="radio" name="delete3">no	7	8	9

<input  type="radio" name="delete4">yes<input  type="radio" name="delete4">no	10	11	12

<input  type="radio" name="delete5">yes<input  type="radio" name="delete5">no	20	11	12

<input  type="radio" name="delete6">yes<input  type="radio" name="delete6">no	30	11	12

 <input type="button" value="remove" onclick="removeItem()">

A: May I suggest this rather clean alternative, using while loop?

function removeItem(){
  var table=document.getElementById("test");
  var r=table.rows.length-1;
  while(row=table.rows[r--])
  {
    if(row.cells[0].firstChild.checked==true) row.remove();
  }
}

to_remove	f1	f2	f3

<input  type="radio" name="delete1">yes<input  type="radio" name="delete1">no	1	2	3

<input  type="radio" name="delete2">yes<input  type="radio" name="delete2">no	4	5	6

<input  type="radio" name="delete3">yes<input  type="radio" name="delete3">no	7	8	9

<input  type="radio" name="delete4">yes<input  type="radio" name="delete4">no	10	11	12

<input  type="radio" name="delete5">yes<input  type="radio" name="delete5">no	20	11	12

<input  type="radio" name="delete6">yes<input  type="radio" name="delete6">no	30	11	12

 <input type="button" value="remove" onclick="removeItem()">

A: You can use below code :-
$("#test").find("td:contains('Yes')").closest('tr').remove();

Edit 1
function removeItem()
 {
     $("#test").find("td:contains('Yes')").closest('tr').remove();
 }

Edit 2
Or you can Try
function checkMatch()
{
    $("#test tr.thisRow").each(function() {
        var thisRow = $(this);
        var match = thisRow.find(".match");

        // note the `==` operator
        if(match.text() == "yes") {
            thisRow.hide();
            // OR thisRow.remove();
        }
    });
}

A: Just another solution http://jsfiddle.net/pmankar/Bnuy7/1064/
Decrease i and len value to point correctly and stay in loop.
i=i-1;
len = len - 1;


text:
Q: Is this the only way to prove that a map is smooth? This question is part of class notes  from which I am studying manifolds:

Let $f:S^2 \to \mathbb{R}^3$ be defined by $f(x,y,z)=(-y,x,0)$. (a) Prove that $f$ is a smooth map.(b) Use $f$ to define a smooth vector field on $S^2$.

The issue is following :does everytime to verify that map $f$ is smooth I have to use the following definition : We say that $f$ is smooth at $p$ if for any chart $(U,\phi)$ containing $p$ and $(V,\psi)$ containing f(p) , the map $\psi \circ f\circ \phi^{-1}: U_1 \to V_1$ is smooth.
I think going by this definition it will be a tedious task. So, is there any other result/ theorem by which smoothness can be proved easily.
Unfortunately, I need help on (b) also.
Please shed some light on it.

A: Well, for one thing the codomain is $\mathbb{R}^3$, so you don't actually need a chart on it. That is, you only need to show that $f \circ \psi^{-1}$ is smooth for any chart $\psi: U \subseteq S^2 \to \mathbb{R}^2$.
To be a bit more slick, you can observe that $f$ extends smoothly to a map defined on all of $\mathbb{R}^3$, so in reality $f$ is the composition of two smooth maps $\widetilde{f} \circ \iota$, where $\iota: S^2 \to \mathbb{R}^3$ is the inclusion map and $\widetilde{f}(x,y,z) = (-y,x,0)$ as above. Of course this requires that you already have shown that $S^2$ is a submanifold of $\mathbb{R}^n$ (from which we can conclude that the inclusion is smooth); if you don't have the ability to claim that at this point in the class the work to do so would be just as much as using the original definition in the first place.


text:
Q: Performing PCA on large sparse matrix by using sklearn I am trying to apply PCA on huge sparse matrix, in the following link it says that randomizedPCA of sklearn can handle sparse matrix of scipy sparse format.
Apply PCA on very large sparse matrix
However, I always get error. Can someone point out what I am doing wrong.
Input matrix 'X_train' contains numbers in float64:
>>>type(X_train)
<class 'scipy.sparse.csr.csr_matrix'>
>>>X_train.shape
(2365436, 1617899)
>>>X_train.ndim
2
>>>X_train[0]
<1x1617899 sparse matrix of type '<type 'numpy.float64'>'
    with 81 stored elements in Compressed Sparse Row format>

I am trying to do:
>>>from sklearn.decomposition import RandomizedPCA
>>>pca = RandomizedPCA()
>>>pca.fit(X_train)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/RT11/.pyenv/versions/2.7.9/lib/python2.7/site-packages/sklearn/decomposition/pca.py", line 567, in fit
    self._fit(check_array(X))
  File "/home/RT11/.pyenv/versions/2.7.9/lib/python2.7/site-packages/sklearn/utils/validation.py", line 334, in check_array
    copy, force_all_finite)
  File "/home/RT11/.pyenv/versions/2.7.9/lib/python2.7/site-packages/sklearn/utils/validation.py", line 239, in _ensure_sparse_format
    raise TypeError('A sparse matrix was passed, but dense '
TypeError: A sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array.

if I try to convert to dense matrix, I think I am out of memory.
>>> pca.fit(X_train.toarray())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/RT11/.pyenv/versions/2.7.9/lib/python2.7/site-packages/scipy/sparse/compressed.py", line 949, in toarray
    return self.tocoo(copy=False).toarray(order=order, out=out)
  File "/home/RT11/.pyenv/versions/2.7.9/lib/python2.7/site-packages/scipy/sparse/coo.py", line 274, in toarray
    B = self._process_toarray_args(order, out)
  File "/home/RT11/.pyenv/versions/2.7.9/lib/python2.7/site-packages/scipy/sparse/base.py", line 800, in _process_toarray_args
    return np.zeros(self.shape, dtype=self.dtype, order=order)
MemoryError

A: PCA(X) is SVD(X-mean(X)).
Even If X is a sparse matrix, X-mean(X) is always a dense matrix.
Thus, randomized SVD(TruncatedSVD) is not efficient as like randomized SVD of a sparse matrix.
However, delayed evaluation
delay(X-mean(X))
can avoid expanding the sparse matrix X  to the dense matrix X-mean(X).
The delayed evaluation enables efficient PCA of a sparse matrix using the randomized SVD.
This mechanism is implemented in my package :
https://github.com/niitsuma/delayedsparse/
You can see the code of the PCA using this mechanism :
https://github.com/niitsuma/delayedsparse/blob/master/delayedsparse/pca.py
Performance comparisons to existing methods show this mechanism drastically reduces required memory size :
https://github.com/niitsuma/delayedsparse/blob/master/demo-pca.sh
More detail description of this technique can be found in my patent :
https://patentscope2.wipo.int/search/ja/detail.jsf?docId=JP225380312

A: Due to the nature of the PCA, even if the input is an sparse matrix, the output is not. You can check it with a quick example:
>>> from sklearn.decomposition import TruncatedSVD
>>> from scipy import sparse as sp

Create a random sparse matrix with 0.01% of its data as non-zeros.
>>> X = sp.rand(1000, 1000, density=0.0001)

Apply PCA to it:
>>> clf = TruncatedSVD(100)
>>> Xpca = clf.fit_transform(X)

Now, check the results:
>>> type(X)
scipy.sparse.coo.coo_matrix
>>> type(Xpca)
numpy.ndarray
>>> print np.count_nonzero(Xpca), Xpca.size
95000, 100000

which suggests that 95000 of the entries are non-zero, however,
>>> np.isclose(Xpca, 0, atol=1e-15).sum(), Xpca.size
99481, 100000

99481 elements are close to 0 (<1e-15), but not 0.
Which means, in short, that for a PCA, even if the input is an sparse matrix, the output is not. Thus, if you try to extract 100,000,000 (1e8) components from your matrix, you will end up with a 1e8 x n_features (in your example 1e8 x 1617899) dense matrix, which of course, can't be hold in memory.
I'm not an expert statistician, but I believe there is currently no workaraound for this using scikit-learn, as is not a problem of scikit-learn's implementation, is just the mathematical definition of their Sparse PCA (by means of sparse SVD) which makes the result dense.
The only workaround that might work for you, is for you to start from a small amount of components, and increase it until you get a balance between the data that you can keep in memory, and the percentage of the data explained (which you can calculate as follows):
>>> clf.explained_variance_ratio_.sum()


text:
Q: Centered Widget in FLTK Can you center a non-resizable widget in FLTK?  The references from this stackoverflow question seem to imply the answer is no.  A centered widget would require resizable widgets on either side, but you can only have one resizable child in a group.
(Sorry for the ask and answer, but I searched all over for this and almost gave up, so I think this will be useful to others.)

A: Here's how you do it.  The trick is that a widget in FLTK can be outside its parent group's borders.
You have 4 groups A, B, C, and D.  B and C are children of A.  D is a child of C.  Not shown is the widget you actually want to have centered, called E.  E is a child of C.  A and E are the ones you want to actually see.  B, C, and D are empty with no border, so they are invisible.  A and D are resizable.  Nothing else is.  Center E in A, not overlapping with D.  E will be partially outside of C.  That's the trick.
|--------------------------------------------|
|                 A                          |
||--------------------||--------------------||
||                    ||           |-----|  ||
||          B         ||      C    |  D  |  ||
||                    ||           |-----|  ||
||--------------------||--------------------||
|--------------------------------------------|

When A is resized, B and C will be resized proportionally and equally, because there are no resizable children of A, and they are the same size.  The origin of C will remain in the center of A.  When C is resized, E will not be resized, only D.  So E will remain in the same position with respect to the origin of C, i.e. with respect to the center of A.
Caveat 1: I have implemented this in FLUID/FLTK 1.3.0, which is admittedly old.  Things may have changed since then.  I did not attempt to verify this on anything more recent.
Caveat 2: FLUID will automatically resize a group to enclose the widgets within it whenever you move any widget.  This breaks the centering behavior.  I have found I need to resize C via the FLUID dialog box to the original size, after any other layout changes, every time.

A: FLTK layout made easier with the header files here: https://fltk-layout-manager.blogspot.com
CoordinateManager()
   .set(addrSubject)
   .centerTo (void* addrBenefactor)
   .render();

You can give a point x, y or the top left and bottom right coordinates:
CoordinateManager()
   .set(addrSubject)
   .centerTo (int x, int y, int x2 = 0, int y2 = 0)
   .render();


text:
Q: casting error on binding dictionary to repeater asp.net I am trying to populate <li> items with a repeater, binding it to a Dictionary object. I have a dictionary called cart, with standard Key, Value properties.
I get a runtime error:
`System.InvalidCastException: Specified cast is not valid.`

I used this code:
<ItemTemplate>
<li id="<%# ((KeyValuePair<string,string>)Container.DataItem).Key %>_i" >
<%# ((KeyValuePair<string,string>)Container.DataItem).Key %> <%# ((KeyValuePair<string,string>)Container.DataItem).Value %>
</li></ItemTemplate>

What is wrong here?

A: Your ItemTemplate works for me when binding to a Dictionary<string, string>. Therefore, I'd suggest to check whether the Repeater is really bound to a Dictionary<string, string>.
If not, the exception makes sense and can be solved by fixing the data binding code (or changing the type that is used in the ItemTemplate so that it matches the data that is bound to the Repeater.

A: if your Dictionary is not a Dictionary<string, string> you can do something like
((System.Collections.Generic.KeyValuePair<string,byte[]>)(Container.DataItem)).Key

Or
((System.Collections.Generic.KeyValuePair<clsProduct,int>)(Container.DataItem)).Key.ProductCode


text:
Q: Is there a way to read a CSV file from Google Drive directly into R without downloading the file locally? I have been trying to use the package "googledrive" to read a csv file into R without having it downloaded locally. Is there a way to do this? The only function that seems applicable is drive_download(), which is not doing what I'm looking for. Any suggestions?

A: If you're not tied to using googledrive, you can use googlesheets::gs_read() to read it straight into R as a data frame.


text: Q: When surface tension acts parallel to the interface, then why is the pressure inside a spherical drop greater than the pressure outside it? When I was watching a Youtube video explaining why pressure inside a drop is greater than the pressure of the air outside, surface tension was drawn as acting radially inwards from the spherical surface of the liquid drop. Hence, because there is both the force due to the air pressure acting over the surface area of the drop and the surface tension of the drop acting inwards, for the drop to be at equilibrium (i.e. not contracting or expanding), the pressure of the liquid in the drop has to be greater than the pressure of the air. I have taken a screenshot of the video: https://www.youtube.com/watch?v=Us7sk1OrcUc&t=225s (at 3:45) to show this. This explanation was very intuitive to me. However, the explanation uses the fact that surface tension acts perpendicular to the surface of the liquid (and hence the force due to surface tension is radially inwards), whereas my NCERT Textbook said that surface tension acts parallel to the interface. This is confusing me, and I can't understand which is true: does the surface tension act parallel to the surface (if so, why is pressure inside a liquid drop greater than the air pressure outside) or does the surface tension act perpendicular to the surface (if so, why does my textbook and so many other sources say that it acts parallel to the surface of the liquid)? Thanks.


text:
Q: How to update selected rows with values from a CSV file in Postgres? I'm using Postgres and would like to make a big update query that would pick up from a CSV file, lets say I got a table that's got (id, banana, apple).
I'd like to run an update that changes the Bananas and not the Apples, each new Banana and their ID would be in a CSV file.
I tried looking at the Postgres site but the examples are killing me.

A: COPY the file to a temporary staging table and update the actual table from there. Like:
CREATE TEMP TABLE tmp_x (id int, apple text, banana text); -- but see below

COPY tmp_x FROM '/absolute/path/to/file' (FORMAT csv);

UPDATE tbl
SET    banana = tmp_x.banana
FROM   tmp_x
WHERE  tbl.id = tmp_x.id;

DROP TABLE tmp_x; -- else it is dropped at end of session automatically

If the imported table matches the table to be updated exactly, this may be convenient:
CREATE TEMP TABLE tmp_x AS SELECT * FROM tbl LIMIT 0;

Creates an empty temporary table matching the structure of the existing table, without constraints.
Privileges
Up to Postgres 10, SQL COPY requires superuser privileges for this.
In Postgres 11 or later, there are also some predefined roles (formerly "default roles") to allow it. The manual:

COPY naming a file or command is only allowed to database superusers
or users who are granted one of the roles pg_read_server_files,
pg_write_server_files, or pg_execute_server_program [...]

The psql meta-command \copy works for any db role. The manual:

Performs a frontend (client) copy. This is an operation that runs an
SQL COPY command, but instead of the server reading or writing the
specified file, psql reads or writes the file and routes the data
between the server and the local file system. This means that file
accessibility and privileges are those of the local user, not the
server, and no SQL superuser privileges are required.

The scope of temporary tables is limited to a single session of a single role, so the above has to be executed in the same psql session:
CREATE TEMP TABLE ...;
\copy tmp_x FROM '/absolute/path/to/file' (FORMAT csv);
UPDATE ...;

If you are scripting this in a bash command, be sure to wrap it all in a single psql call. Like:
echo 'CREATE TEMP TABLE tmp_x ...; \copy tmp_x FROM ...; UPDATE ...;' | psql

Normally, you need the meta-command \\ to switch between psql meta commands and SQL commands in psql, but \copy is an exception to this rule. The manual again:

special parsing rules apply to the \copy meta-command. Unlike most other meta-commands, the entire remainder of the line is always taken to be the arguments of \copy, and neither variable interpolation nor backquote expansion are performed in the arguments.

Big tables
If the import-table is big it may pay to increase temp_buffers temporarily for the session (first thing in the session):
SET temp_buffers = '500MB';  -- example value

Add an index to the temporary table:
CREATE INDEX tmp_x_id_idx ON tmp_x(id);

And run ANALYZE manually, since temporary tables are not covered by autovacuum / auto-analyze.
ANALYZE tmp_x;

Related answers:

*

*Best way to delete millions of rows by ID

*How can I insert common data into a temp table from disparate schemas?

*How to delete duplicate entries?

A: I was having the same problem. But in this solution I have found some difficulties. Since I was not superuser using copy gives error. So I have found an alternative solution for my problem.
I am using postgresql and pgadmin4. here is the solution I came with.

*

*Create a new table and copy the fruits table to the new table.

CREATE TABLE fruits_copy AS TABLE fruits WITH NO DATA;

*Import the CSV file data to the new table(fruits_copy). I am using pgadmin4,so here is the how to import details. (It may differ).

*Update the fruits table from fruits_copy table.

UPDATE fruits SET banana = fruits_copy.banana FROM fruits_copy WHERE fruits.id = fruits_copy.id;

*After that if you want to delete the new table, you can just drop it.

DROP TABLE fruits_copy;

A: You can try the below code written in python, the input file is the csv file whose contents you want to update into the table. Each row is split based on comma so for each row, row[0]is the value under first column, row[1] is value under second column etc.
    import csv
    import xlrd
    import os
    import psycopg2
    import django
    from yourapp import settings
    django.setup()
    from yourapp import models

    try:
       conn = psycopg2.connect("host=localhost dbname=prodmealsdb
       user=postgres password=blank")
       cur = conn.cursor()

       filepath = '/path/to/your/data_to_be_updated.csv'
       ext = os.path.splitext(filepath)[-1].lower()
       if (ext == '.csv'):
          with open(filepath) as csvfile:
          next(csvfile)
          readCSV = csv.reader(csvfile, delimiter=',')
          for row in readCSV:
              print(row[3],row[5])
              cur.execute("UPDATE your_table SET column_to_be_updated = %s where
              id = %s", (row[5], row[3]))
              conn.commit()
          conn.close()
          cur.close()

    except (Exception, psycopg2.DatabaseError) as error:
    print(error)
    finally:
    if conn is not None:
      conn.close()


text:
Q: Layout Issues Using UIContainerView I have a view for an IPad app that I just can't get to layout correctly. I'm trying to display two (possibly more in the future) static tables arranged horizontally in a ViewController. Since static tables require a TableViewController, I'm using a UIContainerView to embed each table inside the parent view. All well and good, but when I actually run my app, the first table has a sizable vertical offset while the second table lines up nicely with the top of the container. From what I can tell it seems like the nav bar is doing something with the first child of my container but I have no idea what setting I would need to modify to change this.
As an example, I whipped up a quick Hello World demo that shows the issue I'm running into. Here is the link: https://github.com/pbtura/container-view-example
Any help would be much appreciated.


text:
Q: Service 'web' failed to build with Protocol error I am trying to use postgresql in the docker container. However, i get an error

Service 'web' failed to build: The command '/bin/sh -c apk add
  --update --no-cache --virtual .tmp-build-deps gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev' returned a
  non-zero code: 4

I get other related issue like ERROR: mpfr3-3.1.5-r1: Protocol error.
Here is the screenshot of an issue as well as this might be related to each other

here is the code
Dockerfile
FROM python:3.7-alpine

ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1

# set working directory which will be inside ubuntu
WORKDIR /code

#### Install a dependency ####
# Copies new files and resources to the image's filesystems
RUN pip3 install pipenv
COPY Pipfile Pipfile.lock /code/
RUN apk add --update --no-cache postgresql-client jpeg-dev
RUN apk add --update --no-cache --virtual .tmp-build-deps \
    gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev
RUN pipenv install --system
RUN apk del .tmp-build-deps
COPY . /code/

RUN adduser -D user
USER user

docker-compose.yml
version: "3.7"

services:
  db:
    image: postgres:12-alpine
    environment:
      - POSTGRES_DB=database
      - POSTGRES_USER=admin
      - POSTGRES_PASSWORD=admin123
  web:
    build: .
    command: >
      sh -c "python /code/manage.py wait_for_db &&
             python /code/manage.py runserver 0.0.0.0:8000"
    environment:
      - DB_HOST=db
      - DB_NAME=database
      - DB_USER=admin
      - DB_PASS=admin123
    volumes:
      - .:/code
    # lets us map our port 8000 to the port 8000 in the Docker container
    ports:
      - 8000:8000
    # it says that we should run the db first before running our web services
    depends_on:
      - db

A: It sounds like it can't find the repositories. Add this line before you run your apk add commands.
RUN echo "http://dl-cdn.alpinelinux.org/alpine/v3.7/main" >> /etc/apk/repositories

Edit: Also where are you pointing at the Dockerfile above in your docker-compose.yml


text: Q: is there any way to request to server with fake server time? When I request to web server with http request, the server send the response with headers. I want to change the server time ; actually the respose header's Date value. Is it possible to change or fake the time of web server? because I want to know the answer in time advance.


text:
Q: Doctrine2 - proxy object among regular objects in getResult In my Symfony2 controller, I have two queries:
like in this example:
$object = $this->getDoctrine()->getManager()
           ->createQuery('SELECT PARTIAL o.{id,name,field1}
                          FROM SomeBundle:SomeEntity o
                          WHERE o.id = :objectId')
                    ->setParameter('objectId', $objectId)
                    ->getResult();

$objects = $this->getDoctrine()->getManager()
           ->createQuery('SELECT PARTIAL o.{id,name,field1, field2}
                          FROM SomeBundle:SomeEntity o ')
                    ->getResult();

Effect that I receive in collection $objects is collection of SomeBundle:SomeEntity objects except for the one that I received to variable $object for which I receive Proxy object.
If I output $objects collection and for each element I want to print output that includes fields: name, field1, field2, I receive null for field2 for this object. In fact if I get this $object in any other controller launched with this one together, the field2 is also null on each reference to the object.
For example, if I want to display each object as:
name field1 field2

I get following array for $objects:
nameExample field1Example field2Example
nameExample field1Example field2Example
nameExample field1Example
nameExample field1Example field2Example
nameExample field1Example field2Example

where the third row is the $object.
If I get field2 in the first query it is also visible on getResult of the second one. But that makes me control all fields received for any Entity object in whole Request.

*

*What could I made wrong?

*How can I avoid that effect? I still want to work with objects not with multidimensional arrays (as for HYDRATE_ARRAY)

*Is there a way to force doctrine to result always with entity objects not with proxies objects?

Thank you in advance.

A: This happens because Doctrine keeps an internal reference to each entity it returns. When you request an entity you've requested before, it will re-use the previous object. The reason for this is that having two different copies of the same entity would create conflicts if you try to manipulate both of them. For more details, see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/unitofwork.html#how-doctrine-keeps-track-of-objects
The one solution is to detach the entity you got first (using either $em->detach($object) or $em->clear()) before executing the second query. Be aware, any changes you've made that have not been flushed yet will be gone.
Another option is to either refresh the entity using $em->refresh($object) (this will cause it to be fully loaded) or tell Doctrine it needs to refresh all entities for the second query:
$query = $this->getDoctrine()->getManager()->createQuery('SELECT PARTIAL o.{id,name,field1, field2} FROM SomeBundle:SomeEntity o ');
$query->setHint(Query::HINT_REFRESH, true);
$objects = $query->getResult();

This will make Doctrine refresh all the entities it finds for this second query.


text:
Q: Program that reads 1 byte at a time works in the debugger, but breaks without it Here is a program that takes decimal ASCII numbers one by one and converts them into an integer. The result is stored in the EDI register:
global _start
%macro kernel 4
    mov eax, %1
    mov ebx, %2
    mov ecx, %3
    mov edx, %4
    int 80h
%endmacro
section .bss
    symbol resb 1
section .text
_start:
    mov esi, 10
    xor edi, edi
.loop:
    kernel 3, 0, symbol, 1 ; load 1 char from STDIN into symbol
    test eax, eax          ; nothing loaded - EOF
    jz .quit
    xor ebx, ebx
    mov bl, [symbol]
    sub bl, '0'
    cmp bl, 9
    jg .quit               ; not a number
    mov eax, edi           ; previously accumulated number
    mul esi                ; eax *= 10
    lea edi, [eax + ebx]
    jmp .loop

.quit:
    mov eax, 1
    mov ebx, edi
    int 80h

I  compile it:
$ nasm -g -f elf32 st3-18a.asm
$ ld -g -m elf_i386 st3-18a.o -o st3-18a
$ ./st3-18a
2[Enter]
Ctrl-d

When I run this code in gdb step by step everything is correct, and the result stored in EDI at the end is 2. But when I run without a debugger, and echo the program return value:
$ ./st3-18a
2[Enter]
Ctrl-d
$ echo $?
238

Why does it output 0xEE? What is wrong?

A: Your range-check is buggy, using a signed compare (jg) instead of unsigned (ja), so you only detect non-digit characters when c - '0' is from 10..127, not when it wraps around (i.e. becomes signed negative), missing almost half of the byte values you should be excluding.  Including control codes like newline at the low end of the ASCII range.

*

*double condition checking in assembly

*Difference between JA and JG in assembly

*NASM Assembly convert input to integer? shows a loop that does the check correctly.

So why does GDB make it work?
Your program only uses read with a size of 1, leaving a newline unread after you press return.  That's ASCII 0xa = '\n', so your next read(1, buf, 1) gets it.
Unless GDB gets it first: GDB takes over the terminal to read more commands after your read(1,buf,1), so GDB gets the leftover terminal input and discards the newline before single-stepping to the next read system call.  Or it might just be getting discarded when GDB switches the terminal from cooked to raw so it can read single keystrokes without waiting for it to be "submitted" from the kernel's canonical-mode line-editing with the EOL (newline) or EOF (ctrl-d) control characters.
That's because your program is sharing a terminal with GDB, rather than attaching GDB to your program already running in another terminal tab / window.  i.e. on a different Unix TTY.  e.g. with gdb -p $(pidof st3-18a).
You can also do that with strace, or just strace ./st3-18a since strace doesn't have interactive input.

It's common to read into a decent sized buffer and ignore later characters in toy programs that use "cooked" TTY input.  That will break if you redirect input from a file so multiple lines are ready at once, so if you want something robust you can use fgets from libc.
As long as you realize that the I/O is simplistic and not robust, though, do whatever floats your boat when playing around with asm, even if that means making assumptions about lines and tty handling and that the user pressed enter instead of control-d.
Play around with cat running in a terminal, typing a partial line and hitting control-D.  You can strace -p $(pidof cat) from another terminal to see its system calls.
See also How do I ignore line breaks in input using NASM Assembly?


text:
Q: DeserializeObject from Generic Type to Known Type after runtime I'm calling a third-party API that returns a generic result based on a boolean "Success" field. The result is a known type class based on the result response.
I'm doing a very stupid way of deserializing the class to an object type and reading the result.
After reading the result I will serialize the object to JSON again and deserialize the object back to the corresponding correct result/known data type.
The question I would like to ask is, what is the efficient or better way to achieve this.
Sample Response from third party API
if success is false
    {
        "Success": false,
        "Result":
        {
            "ErrorCode": "1",
            "ErrorMessage": "Request is unsuccessful."
        }
    }

If success is true
    {
        "Success": true,
        "Result":
        {
            "UserID": "xxxxx",
            "UserName": "yyyyy",
            "UserAge": 60
        }
    }

My Code
My Calling Method (How to improve this calling method???)
var request = new RequestModel ("user1", "password1");
var data = await CallThirdPartyAPI(request);
//At this point of time, this `data` is a `Message<object>` data type
if (data.Success)
{
    var passResult = JsonConvert.SerializeObject(data); //Serialize object type back to JSON
    var passObject = JsonConvert.DeserializeObject<Message<SuccessResponse>>(passResult); //Deserialize object back to known data type
}
else
{
    var failResult = JsonConvert.SerializeObject(data); //Serialize object type back to JSON
    var failObject = JsonConvert.DeserializeObject<Message<FailResponse>>(failResult); //Deserialize object back to known data type
}

API Method
public async Task<Message<object>> CallThirdPartyAPI(RequestModel requestModel)
{
    var requestUrl = CreateRequestUri(string.Format(System.Globalization.CultureInfo.InvariantCulture,
        "api/thirdpartyapi/"));
    var result =  await PostAsync<object, requestModel>(requestUrl, requestModel);
    return result;
}

// Common method for making POST calls
private async Task<Message<T1>> PostAsync<T1, T2>(Uri requestUrl, T2 content)
{
    var response = await _httpClient.PostAsync(requestUrl.ToString(), CreateHttpContent<T2>(content));
    response.EnsureSuccessStatusCode();
    var data = await response.Content.ReadAsStringAsync();
    var result =  JsonConvert.DeserializeObject<Message<T1>>(data);
    return result;
}

DTO
public class Message<T>
{
    [DataMember(Name = "Success")]
    public bool Success { get; set; }

    [DataMember(Name = "Result")]
    public T Result { get; set; }
}

public class FailResponse
{
    public string ErrorCode { get; set; }
    public string ErrorMessage { get; set; }
}

public class SuccessResponse
{
    public string UserId{ get; set; }
    public string UserName { get; set; }
    public int UserAge{ get; set; }
}

public class RequestModel
{
 public string UserName { get; set; }
 public string Password { get; set; }
}


text:
Q: HTMLCollection Index Change Not Reflected in Variables After .append() I have a stack of divs that I have set up in a carousel fashion. Using JQuery I .append() or .prepend() a div to the top or bottom of the stack when "next" or "previous" buttons are clicked. The top/visible div is the "active" div that corresponds to an  of a similarly named id attribute. When a div becomes "active" after clicking a next/previous button, I want my Javascript to pull the src attribute value from the corresponding  so I can use it elsewhere in my program.
The problem I'm having is that when I click the previous or next buttons, the divs reorder perfectly, but the corresponding variables do not reflect the new "active" div. For example, activeAlbumID remains discovery-sounds when it should be space-sounds after a button click.
Here's my :

Here's the Javascript:

$(window).bind("load", function() {

  var albums = document.getElementsByClassName('album');
  var playlists = document.getElementsByTagName('iframe');
  var activeAlbum = albums[albums.length - 1];
  var activeAlbumID = activeAlbum.id;
  var activeAlbumPre = activeAlbumID.split('-');
  var activePlaylist = activeAlbumPre[0] + '-widget';
  var widgetSRC = $('#' + activePlaylist).attr('src');

  $('i:nth-child(1), i:nth-child(2)').click(function(){
    //Click previous button
    if (this.id == 'prev'){
      //Pull out album from bottom of stack
      $(albums[0]).addClass('animate-album');
      //Wait for animation to finish
      $(albums[0]).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
        //Set explicit element margin
        $(albums[0]).css('margin-left', '400px');
        //Remove animation styles/margin so doesn't re-fire on append
        $(albums[0]).removeClass('animate-album');
        //Put bottom album on top
        $('#stack').append(albums[0]);
        //Force browser to calculate margin value
        $(albums[albums.length - 1]).css('margin-left');
        //Transition album back to original position
        $(albums[albums.length - 1]).css('margin-left', '0px');
      });
    }
    else{
      //Push album to bottom of stack
      $(albums[albums.length - 1]).addClass('animate-album');
      //Wait for animation to finish
      $(albums[albums.length - 1]).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
        //Set explicit element margin
        $(albums[albums.length - 1]).css('margin-left', '400px');
        //Remove animation styles/margin so doesn't re-fire on prepend
        $(albums[albums.length - 1]).removeClass('animate-album');
        //Put top album on bottom
        $('#stack').prepend($(albums[albums.length - 1]));
        //Force browser to calculate margin value
        $(albums[0]).css('margin-left');
        //Transition album back to original position
        $(albums[0]).css('margin-left', '0px');
      });
    }
  });
 });

So for instance, when I click the "previous" button, discovery-sounds gets pushed to the bottom of the stack and space-sounds to the top and becomes visible, this works great:

Printing albums to the console produces the updated and correct stack index, but all variables following produce the original "active" value:

//Expected
console.log(activeAlbum); //

console.log(activeAlbumID); //spsce-sounds

//Actual
console.log(activeAlbum); //

console.log(activeAlbumID); //discovery-sounds

A: Just before the end of the animationend handlers, just "renew" the elements collection that "move"... Due to the append/prepend in DOM.
// Renew the albums collection.
albums = document.getElementsByClassName('album');
activeAlbum = albums[albums.length - 1];
activeAlbumID = activeAlbum.id;

Updated forked CodePen


text:
Q: Limit MySQL Query with Show More button In PHP/AJAX, is there a straight forward way to display a certain number rows from a query (let's say 5) and then have a "show more" button that shows the next 5 (and so on)?

A: SELECT info FROM table LIMIT 0,5  //First 5 results
SELECT info FROM table LIMIT 5,5  //Next 5 results
SELECT info FROM table LIMIT 10,5  //Next 5 results

A: assuming you dont want to use AJAX (because you said "in PHP"): what you can do is use limit in your sql to get only the first few results. You can then generate the page and when you generate the "more" button, you add a query string to the page it has been sent to with something like ?begin=6 so your php script knows where to start.

assuming you are using AJAX: You can use jQuery's $.ajax() function (or any other library, or "raw" javascript, if you like pain) to get the results back with the same url scheme. then replace the content of the container with whatever results you get back.


text:
Q: Get Spotify access token with spotipy on Django and Python I'm new to Django and I'm trying to link Spotify to my webapp. I'm using Spotify to do it and it correctly access to Spotify.
To do it I have a button that opens the view below
views.py
@authenticated_user
def spotify_login(request):

    sp_auth = SpotifyOAuth(client_id=str(os.getenv('SPOTIPY_CLIENT_ID')),
                           client_secret=str(os.getenv('SPOTIPY_CLIENT_SECRET')),
                           redirect_uri="http://127.0.0.1:8000/",
                           scope="user-library-read")
    redirect_url = sp_auth.get_authorize_url()
    auth_token = sp_auth.get_access_token()
    print(auth_token)
    print("----- this is the AUTH_TOKEN url -------", auth_token)
    return HttpResponseRedirect(redirect_url)

If I don't use auth_token = sp_auth.get_access_token() everything works fine and I got redirected to the correct. Unfortunately, if I add that line of code to access the access token, instead of staying on the same page, it opens another tab on the browser with the Spotify auth_code and lets the original page load forever.
Is there a way to retrieve the access token in the background without making my view reload or open another tab in the browser?

A: You are being redirected to exactly where you are telling django to go.
redirect_url is just a spotify api redirect containing a code, which is captured and used to get the access token.
Set your expected response as return value.
By the way, keep in mind:

*

*redirect_uri="http://127.0.0.1:8000/", should be added in spotify app (usually as http://127.0.0.1:8000/callback",)

*auth_token is a json, you can find token in auth_token['access_token']

A: The solution was to create a new view to access the URL
views.py
from .utils import is_user_already_auth_spotify, spotify_oauth2

@authenticated_user
def spotify_login(request):

    if is_user_already_auth_spotify(request.user.username):
        messages.error(request, "You have already linked your Spotify account")
        return HttpResponseRedirect('account/' + str(request.user.username))

    sp_auth = spotify_oauth2()
    redirect_url = sp_auth.get_authorize_url()
    return HttpResponseRedirect(redirect_url)

@authenticated_user
def spotify_callback(request):
    full_path = request.get_full_path()
    parsed_url = urlparse(full_path)
    spotify_code = parse_qs(parsed_url.query)['code'][0]

    sp_auth = spotify_oauth2()
    token = sp_auth.get_access_token(spotify_code)

    data = {
        str(request.user.username): token
    }
    with open('spotify_auth.json', 'w') as f:
        json.dump(data, f)

    messages.success(request, "You have correctly linked your Spotify account")

    return HttpResponseRedirect('account/' + str(request.user.username))

urls.py
urlpatterns = [
    path('account/<str:username>/', views.account_user, name="account"),
    path('spotify_login', views.spotify_login, name="spotify_login"),
    path('spotify_callback', views.spotify_callback, name="spotify_callback"),
]

utils.py
import json
from spotipy import oauth2
import os

def is_user_already_auth_spotify(username):
    my_loaded_dict = {}
    with open('spotify_auth.json', 'r') as f:
        try:
            my_loaded_dict = json.load(f)
        except:
            # file vuoto
            pass
    if str(username) in my_loaded_dict:
        # controllare scadenza token ed in caso rinnovarlo
        return True
    else:
        return False

def spotify_oauth2():
    sp_auth = oauth2.SpotifyOAuth(client_id=str(os.getenv('SPOTIPY_CLIENT_ID')),
                                  client_secret=str(os.getenv('SPOTIPY_CLIENT_SECRET')),
                                  redirect_uri="http://127.0.0.1:8000/members/spotify_callback",
                                  scope="user-library-read")
    return sp_auth

The code also saves the token in a JSON and search for it if it has already been saved


text:
Q: Generic type argument in java generics Is there a way that I can pass a generic type to a generic class like
interface Wrapper<T, R> {}

interface Result<T, Wrapper<T, R>> {
    R getResult();
}

Here Result takes Wrapper one of the type with type arguments T and R. getResult method in Result interface returns R.
What I did is below,
interface Result<T, W> {
    <K> K getResult();
}

Is there a better way to do this in java.

A: You need a separate type argument for a Result interface. Something like this:
interface Result<T, R, W extends Wrapper<T, R>> {
    R getResult();
}

Now you can use W inside the result to represent the Wrapper or T and R to represent wrapper components. It's possible though that W is completely unnecessary for you and having T and R is enough.


text:
Q:  change color when it is correct I have a problem with <input>. I want to check whether the user has filled it out or not.
By default, the input border will be gray. When the user did not fill in the fields it will have a red border otherwise green.
I added two CSS codes:
input:not(:focus):not(:placeholder-shown):invalid {
  border-color: red;
}

input:not(:focus):not(:placeholder-shown):valid {
  border-color: green;
}

In <input> where I added required, the border is red, and here where I don't have required, the border is green. Can I change it somehow?
These are default fields that are not required.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"/>

<form name="companies" method="post" class="default_ajax was-validated" enctype="multipart/form-data">

        <input type="text" placeholder="Place #1" id="company_name" name="company_name" class="enable_character_count form-control" required>
        Input 1

        <input type="text" placeholder="Place #2" id="company_service_name_1" name="company_service_name_1" class="enable_character_count form-control"/>
        Input 2

</form>


text:
Q: BankAccount not working My code gives a junitframeworkComparisonFailure: expected chequing2 but was null. I'm using a unit test to check my code and I have that below as well. Thank you very much. It also has other errors but this is the one I want to solve the most. I'm sorry if my problem is painfully obvious, I've just started recently.
public class BankAccount {
private String accountNumber;
private double balance;
private double withdrawalFee;
private double annualInterestRate;
private String BankAccount;

public BankAccount(String account_Number) {
     account_Number = accountNumber ;

}
public BankAccount(String account_Number,double iNITIAL_BALANCE)
{

    account_Number = accountNumber ;
    iNITIAL_BALANCE = balance;
}

public BankAccount(String account_Number, double iNITIAL_BALANCE, double wITHDRAWAL_FEE,
        double aNNUAL_INTEREST_RATE) {
    account_Number = accountNumber ;
    iNITIAL_BALANCE = balance;
    aNNUAL_INTEREST_RATE = annualInterestRate ;
    wITHDRAWAL_FEE = withdrawalFee;

}

public void deposit(double amount)
{
    double newBalance = balance + amount;
    balance = newBalance;
}
public void withdraw(double amount)
{
    double newBalance = balance - amount;
    balance = newBalance;
}

public double getAnnualInterestRate(){
    return (annualInterestRate);
}
public String getAccountNumber()
{
    return accountNumber ;
}
public void getannualInterestRate(double rate) {
    if (rate >= 0.00) {
        annualInterestRate = rate ;}
}
public double getBalance()
{
    return balance;
}
public void setAnnualInterestRate(double annualInterestRate) {
    this.annualInterestRate = annualInterestRate;

}
public double getWithdrawalFee() {
    return withdrawalFee;
}
public void setWithdrawalFee(double withdrawalFee)    {
    this.withdrawalFee = withdrawalFee;
}
public boolean isOverDrawn(){
    if (0 > balance){
        return true;
    } else {
        return false;
    }
}

public String toString(){
return (" BankAccount" +" "accountNumber" +":"+balance);
}
}

The test:
import static org.junit.Assert.assertEquals;

public class BankAccountTest extends junit.framework.TestCase
{

final double INITIAL_BALANCE = 100;
final double WITHDRAWAL_FEE = 2.0;
final double ANNUAL_INTEREST_RATE = 5.0;

BankAccount chequing1;
BankAccount chequing2;
BankAccount chequing3;

protected void setUp()
{

    System.out.println("setup");
    chequing1 = new BankAccount("chequing1");
    chequing2 = new BankAccount("chequing2", INITIAL_BALANCE);
    chequing3 = new BankAccount("chequing3", INITIAL_BALANCE, WITHDRAWAL_FEE, ANNUAL_INTEREST_RATE);
    assertEquals(3,3);
}

public void testAccessors()
{
    assertEquals("chequing2",  chequing2.getAccountNumber());
    assertEquals(INITIAL_BALANCE,  chequing2.getBalance(), 0);
    assertEquals(ANNUAL_INTEREST_RATE,  chequing3.getAnnualInterestRate(), 0);
    assertEquals(WITHDRAWAL_FEE,  chequing3.getWithdrawalFee(), 0);
}

public void testMutators()
{
    //test for setters
    chequing1.setWithdrawalFee(3.0);
    chequing1.setAnnualInterestRate(4.0);
    assertEquals(3.0,  chequing1.getWithdrawalFee(), 0);
    assertEquals(4.0,  chequing1.getAnnualInterestRate(), 0);
    //spac
}

public void testDeposits()
{
    //test various deposits and withdrawals
    chequing1.setWithdrawalFee(3.0);

    chequing1.deposit(500);
    assertEquals(500.0,  chequing1.getBalance(), 0);

    chequing1.withdraw(200);
    assertEquals(297.0,  chequing1.getBalance(), 0);
    assertEquals(false,  chequing1.isOverDrawn());

    chequing1.withdraw(300);
    assertEquals(-6.0,  chequing1.getBalance(), 0);
    assertEquals(true,  chequing1.isOverDrawn());

    chequing2.deposit(0.42);
    assertEquals(100.42,  chequing2.getBalance(), 0.00);
    chequing2.deposit(0.001);
    assertEquals(100.421,  chequing2.getBalance(), 0.001);
}

public void testToString() {

    assertEquals("BankAccount chequing1: $0.00",  chequing1.toString());
    assertEquals("BankAccount chequing2: $100.00",  chequing2.toString());

    chequing2.deposit(0.42);
    assertEquals("BankAccount chequing2: $100.42",  chequing2.toString());

    chequing2.deposit(0.001);
    assertEquals("BankAccount chequing2: $100.42",  chequing2.toString());

    BankAccount chequing4 = new BankAccount("chequing4", -100);
    assertEquals("BankAccount chequing4: ($100.00)",  chequing4.toString());
    assertEquals("BankAccount chequing4: ($100.00)",  chequing4.toString());
}

}

A: The assignments in your constructors are backwards:
public BankAccount(String account_Number) {
  this.accountNumber= account_Number ;
}

public BankAccount(String account_Number,double iNITIAL_BALANCE)
{

  this.accountNumber = account_Number ;
  this.balance = iNITIAL_BALANCE;
}

public BankAccount(String account_Number, double iNITIAL_BALANCE, double
    wITHDRAWAL_FEE,
    double aNNUAL_INTEREST_RATE) {
  this.accountNumber= account_Number ;
  this.balance= iNITIAL_BALANCE ;
  this.annualInterestRate= aNNUAL_INTEREST_RATE ;
  this.withdrawalFee= wITHDRAWAL_FEE ;
}


text:
Q: how to find out the user touch move direction in js i'm making touch slider but i m able to do it only one direction when touch move to positive x-axis. i want to show previous slide when user move touch in negative x-axis.
how can i know the direction in which user move the touch
i m a beginner and first time i'm trying touch event and i stuck in this problem and i also did google but i didn't get any idea
here is my code
js
const testimonialTextContainer = document.querySelector(".testimonialTextContainer")
let testimonialTextContainerWidth = testimonialTextContainer.offsetWidth;
const testimonialSlider = document.querySelector(".testimonialSlider");
const testimonialDot = document.querySelectorAll(".testimonialDot");
window.addEventListener('resize', function () {
    testimonialTextContainerWidth = testimonialTextContainer.offsetWidth;
});
// initialize varibale
let testimonialSlide = 0;
let moveSlide = true;
let isTestimonialTouchMove;

const nexSlide = () => {
    // if testimonialSlide less than testimonialSlider.children.length and dashboardImagesSlider.children.length
    if (testimonialSlide < (testimonialSlider.children.length)) {
        testimonialSlider.style.left = -testimonialTextContainerWidth * testimonialSlide + "px";
        testimonialDot[testimonialSlide].classList.add("opacity");
    }
    // make slide move on Touch and do isTestimonialTouchMove = false
    testimonialSlider.addEventListener("touchstart", (e) => {
        e.preventDefault();
        isTestimonialTouchMove = false;
    });
    testimonialSlider.addEventListener("touchmove", (e) => {
        // when touch is move then do move slide false and isTestimonialTouchMove = true;
        console.log(e.target.identifier)
        moveSlide = false;
        isTestimonialTouchMove = true;
        e.preventDefault();
        if (testimonialSlide < testimonialSlider.children.length - 1) {
            testimonialSlider.style.left = -testimonialTextContainerWidth * (testimonialSlide + 1) + "px";
            testimonialDot[testimonialSlide+1].classList.add("opacity");
            testimonialDot[testimonialSlide].classList.remove("opacity");
            setTimeout(() => {
                moveSlide = true
            }, 8000);
        }
    });
    testimonialSlider.addEventListener("touchend", (e) => {
        // if slide is move then make current testimonialSlide = testimonialSlide + 1
        e.preventDefault();
        if (isTestimonialTouchMove) {
            testimonialSlide = testimonialSlide + 1
        }
    })

    if (testimonialSlide == testimonialSlider.children.length) {
        testimonialSlide = 0;
        testimonialSlider.style.left = 0 + "px"
        testimonialDot[testimonialSlide].classList.add("opacity");
    }
}
const mainTestimonialFunction = () => {
    // remove class opacity from last dot and call nextslide function
    if (testimonialSlide > 0 && testimonialSlide <= testimonialSlider.children.length) {
        testimonialDot[testimonialSlide - 1].classList.remove("opacity");

    }
    nexSlide();
}
setInterval(() => {
    if (moveSlide) {
        testimonialSlide++
        mainTestimonialFunction();
    }
}, 4000);

mainTestimonialFunction();

html

                                "Good Meeting Today has improved my meeting planning, execution and preparation and in
                                turn
                                increased my meeting productivity notably. The platform is simple and easy to use and
                                provides
                                you with accountability for your meetings. I have gotten addicted to improving my
                                meeting
                                score!",

Mimi

Junior Project Manager,London

                                "After being forced to move twice within five years, our customers had a hard time
                                finding us
                                and our sales plummeted. The Lorem Ipsum Co. not only revitalized our brand, but saved
                                our
                                nearly 100-year-old family business from the brink of ruin by optimizing our website for
                                search
                                and creating our Google My Business listing.",

Mike Brashears

Owner, Brashears Insurance

 "I was skeptical of SEO and
                                content
                                marketing at first, but the Lorem Ipsum Company not only proved itself financially
                                speaking, but
                                the response I have received from customers is incredible. The work is top-notch and I
                                consistently outrank all my competitors on Google."

Rob Joor

Owner, Joors Welding and Metal Service


text:
Q: Exchange 2010 Pop/Smtp Connection I am serving hosted Exchange 2010 to my clients. One of my client came with how to use Outlook Express and Windows 7 Mail with Exchange.
I have made researches, read http://technet.microsoft.com/en-us/library/bb124107(v=exchg.141).aspx article and configured my server.
Unfortunatelly POP connection doesn't work. testexchangeconnectivity.com tool errors on ceritificate but nothing should be wrong with certificate or configuration.
Do you see a mistake?
I defined Client Access server as POP and Imap server and Hub Transport server for SMTP.
Pop settings instructions on OWA (4th Edit)

EMS pop settings details (5th Edit)

testexchangeconnectivity.com result  (4th Edit)

get-exchangecertificate (1st Post)

get-exchangecertificate | fl after UC/SAN certificate installed (5th Edit)

get-exchangecertificate | fl after new certificate for pop service installed (4th Edit)

get-exchangecertificate | fl before new certificate for pop service installed (1st Post)

A: I see the issue...the status for the POP3 cert is INVALID.

Apparently according to Comodo this is a known issue with Exchange 2010 using their "EssentialSSL" cert.
See here: http://forums.comodo.com/ssl-certificate/certificate-is-invalid-for-exchange-server-usage-t86252.0.html

Exchange 2010 does not like the EssentialSSL hierarchy for some reason
  whereas Exchange 2007 had no issue with it. We recommend that for
  Exchange 2010 that customers use the Unified Communications
  certificate from our InstantSSL.com page.

A: I finally found the solution after weeks.
If you try to connect Exchange Pop service with a third party you should change LoginType @ PopSettings
Set-Popsettings -LoginType plaintextlogin

Don't forget to restart the pop3 service
Thanks busbar@experts-exchange


text:
Q: Quitar sombras en el margen del código Hola a todos y antes de nada, gracias por leerme
El caso es que en visual studio code me sale una sombra en el código y no se como quitarla, en la foto que mando es la de color verde oscuro, es la franja vertical, he estado buscando pero no lo encuentro, gracias y un saludo

A: Edición
Extensiones como indent-rainbow son las que colorean las indentaciones como lo que muestras en la figura.
Es muy probable que la tengas instalada u otra similar.
Deberías desinstalarla o desactivarla accediendo al panel izquierdo de Extensiones Ctrl+Shift+X

Respuesta inicial dejada por si sea de utilidad para otros casos
Al parecer es la manera en que el editor te muestra los espacios en blanco.
En la configuración hay una propiedad Render Whitespace que controla esto. La opción por defecto es selection pero en tu caso parece que tiene el valor boundary.
Prueba cambiando estos valores a ver si encuentras el que te satisfaga.


text:
Q: How to plot pies or histograms around points (GeoPandas) containing different level values indicators? This is my code (a simple sample of df). I'd like to have around each point on a map, an histogram or pie showing the mechanical bikes out of the total.
import pandas as pd

pd.DataFrame(
    {'station_code' : ['13014', '13011' , '13012'],
     'numbikesavailable' : ['25', '15', '20'],
     'mechanical' : ['10', '5' , '8'],
     'geometry' :
         ['POINT (2.36404 48.84252)',
          'POINT (2.35822 48.83541)' ,
          'POINT (2.40932 48.8691)']
    }
  )

How can I do this?


text:
Q: jquery ajax call messes up the sendt text, when there are at least two questionmarks side by side I have a simple message system on my webpage.
Sometimes, vary rarely (so I can not reproduce the error), jquery is messing up the message text.
This is one of the rare text examples, where the error occures:

*wirklich? sehr cool :) und wie organisiert du das dann immer? schon alles geplant oder wie es dir grad
  einfälltjQuery172010423805089564042_1347537302675 und wie lange bist
  du da dann immer unterwegs?*

This string should not be in the text -> jQuery172010423805089564042_1347537302675
The error must occure somewhere between setting the message history -> extracting the text from the textarea -> sending the text via ajax to the server...
Someone has an idea?
// The part where I set the text history.
$('#msgwriter_text').val($("<div/>").html('\n' + '\n' + '\n' + old_date + '\n' + old_text).text());

// the part where the new text gets extracted from the textarea.
var text = $('#msgwriter_text').val();

// text will be stored in the database via ajax call
$.ajax ({
    type: "POST",
    url: "ajax/ajax_special_functions.php",
    data: data_string,
    dataType: "json",
    success: function(recive_obj) {

        // Some more code...
    }
});

finally I discouvered whats causing the error!
This strange string is added, when there are at least 2 questionmarks together in the text -> ??
now my next question is, how to solve that problem!?
oviously I cant solve the problem by editing the settings of the ajax function - it does not matter, if cache is false or true...
I think the best solution would be, a str.replace with regex, that ensures that there are no ? side by side...

A: try checking at the values for old_date and old_text
Also, you need not do it in 2 lines of code, if you just want to get the data, you can get that in 1 line of code.
var text = '\n' + '\n' + '\n' + old_date + '\n' + old_text;


text:
Q: Domain class hasMany fails to add entry I'm a Grails noob so please excuse my noob question.
I've created a domain classes User and Device. User hasMany devices:Device, and Device belongsTo user:User.
It is important that only 1 device will never belong to two users so my UserController code looks like this:
class UserController {

static allowedMethods = [create: 'POST']

def index() { }

def create() {
    def user = User.findByUsername(request.JSON?.username)
    def device = Device.findById(request.JSON?.deviceId)
    if (device) {
        device.user.devices.remove(device)
    }
    // device can only be owned by 1 person
    def new_device = new Device(id: request.JSON?.deviceId, type: request.JSON?.deviceType)

    if ( !user ) {
        user = new User(
                username: request.JSON?.username
        )
        user.devices = new HashSet() // without this I get null on the add in next line
        user.devices.add(new_device)
        user.save()

        if(user.hasErrors()){
            println user.errors
        }
        render "user.create " + request.JSON?.username + " devices.size " + user.devices.size()
    } else {
        user.devices.add( new_device )
        user.save()
        if(user.hasErrors()){
            println user.errors
        }

        render "user.create exists, new token: " + user.token + " devices.size " + user.devices.size()
    }
}

}

But now I get a strange server error:
null id in Device entry (don't flush the Session after an exception occurs)
What am I missing here??
Thanks a lot!

A: First of all, there are special methods to add to and remove from. Do not operate straight on hasMany collections. Maybe this is problematic.


text:
Q: image not showing after saving in WPF i am trying to save project icon and after saving i need to show on the next page, but it doesn't show . Each time i need to include that image in project first, then rebuild the project then it become visible.
i am using following code.please tell me where i am doing wrong and i want image that i newly saved will be automatically included in the project
string imagename = imagebind1.Source.ToString();
int indxofslash = imagename.LastIndexOf('/');
string substribgimgname = imagename.Substring(indxofslash + 1).ToString();
string imagename1 = "/img/icons/" + System.IO.Path.GetFileName(imagename);
String appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
string folderpath = System.IO.Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\img\\icons\\";
if (!Directory.Exists(folderpath))
{
    Directory.CreateDirectory(folderpath);
}
string filePath = folderpath + substribgimgname;
string localPath = new Uri(imagename).LocalPath;

System.IO.File.Copy(localPath, filePath, true);


text:
Q: Thoughts on improving the following XslCompiledTransform class usage I would really appreciate input on the following implementation. Goals are: produce an XElement, avoid file system reads/writes as much as possble.
private XElement ProduceApiXml(KeyValuePair<string, ConfigScriptOutput> kvp)
{
    XElement returnValue = null;
    // load xsl file
    XslCompiledTransform ct = new XslCompiledTransform();
    string xslFile = Path.Combine(_assemblyDir, ConfigurationManager.AppSettings["ConfigOutputXslFile"]);
    ct.Load(xslFile);
    XmlReader xmlToTransform = XmlReader.Create(new StringReader(kvp.Value.ScriptStdOut));
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    XmlWriter xmlTransformed = new XmlTextWriter(sw);
    ct.Transform(xmlToTransform, xmlTransformed);

    returnValue = XElement.Parse(sb.ToString());
    return returnValue;
}

This is the first time I have used this XslCompiledTransform class, and I am thinking I could imporve on it. My real concern is should I be using something other than the StringBuilder -> StringWriter -> XmlWriter constructs to get to where I want to be? Seems like a lot of objects built up to do the task at hand - which does work. Right now, working wins, but I want to make it better.
I'd really appreciate those of you with the experience commenting constructively on what I have done here. A code review, if you will?
Thanks in advance for your time.

A: If you want to populate an XElement then use
XDocument result = new XDocument();
using (XmlWriter xw = result.CreateWriter())
{
  ct.Transform(xmlToTransform, xw);
}
returnValue = result.Root;

there is no need to use a StringWriter and no need to use the legacy XmlTextWriter, the transformation can directly populate an XContainer.
I would also wrap the use of XmlReader and StringReader into using blocks.


text:
Q: Does Warnings in Azure Devops pipeline affects the build time Would like to know if a lot of warning can increase the website build time using 'task: VSBuild@1' and 'msbuildArgs' as input

A:
Would like to know if a lot of warning can increase the website build time using 'task: VSBuild@1' and 'msbuildArgs' as input

Agree with KrzysztofMadej. A large number of warnings will increase the compiler's compilation time. When the compiler encounters a warning, it needs to do some simple actions and warning positioning and analysis, so that it can give a meaningful warning prompt in the log.
For a scenario we often encounter, when compiling the project to reference the assembly, the correct compilation will directly find the matching assembly, but if the assembly is not found, the compiler will try to go to some msbuild/extension, framework folder to search for the required dll files. These additional operations will undoubtedly increase the time of the compiler.

Is there any property for 'msbuildArgs' through which we can suppress
them?

You could use msbuildArgs /p:WarningLevel=X  supress the warning level for those C# warnings (e.g. CS0618):
Warning
Level    Meaning
-------- -------------------------------------------
      0  Turns off emission of all warning messages.

      1  Displays severe warning messages

      2  Displays level 1 warnings plus certain, less-severe warnings, such
         as warnings about hiding class members

      3  Displays level 2 warnings plus certain, less-severe warnings, such
         as warnings about expressions that always evaluate to true or false

      4  (the default) Displays all level 3 warnings plus informational warnings

For those MSBuild warnings, it can't be suppressed.
You could check this thread for some more details.


text:
Q: ¿Cómo hago para que me funcione palindromo en un string? En Java Buenas tengo que usar el método reverse() para que el string "anita lava la tina" se puede leer del mismo modo si lo doy vuelta.
Por el momento hice esto:
String frase = "anita lava la tina";
StringBuilder builder = new StringBuilder(frase);
String palindromoAlReves = builder.reverse().toString();
System.out.println(palindromoAlReves);

Y como salida sale esto:
anit al aval atina
Cuando tendría que salir así:
anita lava la tina
¿Cómo puedo hacer que funcione de forma correcta?

A: Me parece que hay un pequeño malentendido, la definición de una frase o palabra palíndroma es:

palíndroma es una palabra, o frase que se lee igual adelante que
  atrás

Por lo tanto a partir de la frase:
anita lava la tina

si "normalizamos" quitando espacios y la invertimos obtenemos
anitalavalatina

se lee similar a la frase original, esto indica que es una frase palíndroma.

En realidad no tiene mucho sentido tener una frase:
anita lava la tina

y obtener como salida la misma frase:
 anita lava la tina

Lo que necesitas es una forma para determinar si la frase o palabra es o no palíndroma y esto lo puedes realizar de esta forma:
String myPhrase = "anita lava la tina";
//Normaliza palabra
myPhrase = myPhrase.toLowerCase().replace(" ", "").replace(",","");
int counter = 0, longWord = myPhrase.length()-1;
boolean isError = false;

while ((counter<longWord) && (!isError)){
    if (myPhrase.charAt(counter) == myPhrase.charAt(longWord)){
        counter++;
        longWord--;
    } else {
        isError = true;
    }
}
if (!isError){
    System.out.println(myPhrase + " : es un PALÍNDROMO :-)");
}else{
    System.out.println(myPhrase + " : NO es un PALÍNDROMO :-(");
}


text:
Q: My asp.net MVC Program looks not right when i open it on debug https://drive.google.com/drive/folders/1cPRh5JsWG3wBjTyZhyYIppfZBA0nrFpB?usp=sharing
In the above pictures, in the right side is my project when i open it with Ctrl+F5 and on the left side is my project when i open it on debug, using F5, in two different pages.
I noticed a small diffrence in the html code when i inspected it, as you can see in the second picture i uploaded(In the left side there are "::before" and "::after" missing).
other then that there is no diffrence i can point on in the html.
Please help me fix this problem.

A: Finally, I found an answer.
Everything worked just fine after i have upgraded to bootstrap 4.
Note that when moving from Bootstrap 3 to 4, the default layout that you get with the asp.net application will no longer behave properly, Bootstrap 3 and 4 are quite different and things that worked in the 3th version may not work in the 4th.


text:
Q: A normal to a plane I have been doing one example and there is something unclear. It goes like this:
A plane quadratic net B can be fixed between the points $ (0, 1, 0), (1, 1, 0), (1, 1, −1), (0, 1, −1)$
Now, in the solutions, based on this information it says that: The net B is the subset of the plane y=1 on which 0 ≤ x ≤ 1 and −1 ≤ z ≤ 0. Thus, the constant vector field $\hat N_B$ = (0, 1, 0) is a unit normal field for B.
The thing that I do not understand is: if y=1 is the plane, how is $\hat N_B$ = (0, 1, 0) the normal field to it?
Thanks

A: In the context of planes in $\mathbb R^3$ the equation $y=1$ refers to the plane
$$
P=\{(x,y,z)\in\mathbb R^3~:~y=1\}.
$$
This is a plane, as you can see here:
$$
P=\{(x,1,z)~:~x,z\in\mathbb R\}=\left\{x\begin{pmatrix}1\\0\\0\end{pmatrix}+z\begin{pmatrix}0\\0\\1\end{pmatrix}+\begin{pmatrix}0\\1\\0\end{pmatrix}~:~x,z\in\mathbb R\right\}\\=\begin{pmatrix}0\\1\\0\end{pmatrix}+span\left\{\begin{pmatrix}1\\0\\0\end{pmatrix},~\begin{pmatrix}0\\0\\1\end{pmatrix}\right\}
$$
A normal field is normal to the plane at each point. For a plane, the normal field is constant and is a normed vector $\hat N_B$ such that it is othogonal to the two vectors which span the subspace of the plane. Here is it
$$
\hat N_B \bot\begin{pmatrix}1\\0\\0\end{pmatrix}\text{ and }\hat N_B\bot\begin{pmatrix}0\\0\\1\end{pmatrix}.
$$
You can directly see that
$$
\text{either }\hat N_B=\begin{pmatrix}0\\1\\0\end{pmatrix}\text{ or }\hat N_B=\begin{pmatrix}0\\-1\\0\end{pmatrix}.
$$
Both are possible.

A: Rewrite the equation of the plane in vector form as $(x,y,z)\cdot(0,1,0)=0$. This equation says that every point on the plane is orthogonal to $(0,1,0)$, i.e., that $(0,1,0)$ is normal to the plane.


text:
Q: How to make a condition saying that df1$datetime has to be within 30 minutes (before and after) from df2$datetime df1 summarises different moments over time in the format "%Y-%m-%d %H:%M:%S". df2 summarises different temperatures at intervals of one hour (format = "%Y-%m-%d %H"). I want to add a column T in df1 but considering that each df2$DateTime is representative of half an hour before and half an hour later. As an example:
df1<- data.frame(DateTime=c("2016-08-01 08:01:17","2016-08-01 09:17:14","2016-08-01 10:29:31","2016-08-01 11:35:02","2016-08-01 12:22:45","2016-08-01 13:19:27","2016-08-01 14:58:17","2016-08-01 15:30:10"))
df1$DateTime<- as.POSIXct(df1$DateTime, format = "%Y-%m-%d %H:%M:%S", tz= "UTC")

df2<- data.frame(DateTime=c("2016-08-01 06:00:00","2016-08-01 07:00:00","2016-08-01 08:00:00","2016-08-01 09:00:00","2016-08-01 10:00:00","2016-08-01 11:00:00","2016-08-01 12:00:00","2016-08-01 13:00:00","2016-08-01 14:00:00","2016-08-01 15:00:00","2016-08-01 16:00:00"),T = c(21.00, 25.20, 27.0, 27.5, 27.1, 27.0, 26.8, 26.3, 26.0, 26.3, 29.15))
df2$DateTime<- as.POSIXct(df2$DateTime, format = "%Y-%m-%d %H", tz= "UTC")

df1
             DateTime
1 2016-08-01 08:01:17
2 2016-08-01 09:17:14
3 2016-08-01 10:29:31
4 2016-08-01 11:35:02
5 2016-08-01 12:22:45
6 2016-08-01 13:19:27
7 2016-08-01 14:58:17
8 2016-08-01 15:30:10

df2
              DateTime     T
1  2016-08-01 06:00:00 21.00 # This values encompass between 05:30 and 06:30
2  2016-08-01 07:00:00 25.20 # This values encompass between 06:30 and 07:30
3  2016-08-01 08:00:00 27.00 # This values encompass between 07:30 and 08:30
4  2016-08-01 09:00:00 27.50 # This values encompass between 08:30 and 09:30
5  2016-08-01 10:00:00 27.10 # This values encompass between 09:30 and 10:30
6  2016-08-01 11:00:00 27.00 # This values encompass between 10:30 and 11:30
7  2016-08-01 12:00:00 26.80 # This values encompass between 11:30 and 12:30
8  2016-08-01 13:00:00 26.30 # This values encompass between 12:30 and 13:30
9  2016-08-01 14:00:00 26.00 # This values encompass between 13:30 and 16:30
10 2016-08-01 15:00:00 26.30 # This values encompass between 14:30 and 15:30
11 2016-08-01 16:00:00 29.15 # This values encompass between 15:30 and 16:30

I would like to get this:
df1
             DateTime     T
1 2016-08-01 08:01:17 27.00 # Represented by row 3 in df2
2 2016-08-01 09:17:14 27.50 # Represented by row 4 in df2
3 2016-08-01 10:29:31 27.10 # Represented by row 5 in df2
4 2016-08-01 11:35:02 26.80 # Represented by row 7 in df2
5 2016-08-01 12:22:45 26.80 # Represented by row 7 in df2
6 2016-08-01 13:19:27 26.30 # Represented by row 8 in df2
7 2016-08-01 14:58:17 26.30 # Represented by row 10 in df2
8 2016-08-01 15:30:10 29.15 # Represented by row 11 in df2

A: First round df1's datetime to it's nearest hour, then use merge or inner_join to get the corresponding temperature from df2:
library('dplyr')
library('lubridate')
df1 %>%
  mutate(round_datetime = round_date(DateTime, unit = 'hour')) %>%
  merge(df2, by.x = 'round_datetime', by.y = 'DateTime') %>%
  select(-round_datetime)

A: df1$T <- sapply(df1$DateTime, function(x) {df2$T[df2$DateTime==round(x, "hours")]})
#27.00 27.50 27.10 26.80 26.80 26.30 26.30 29.15

#In case ther is more than one match, take the first one
df1$T <- sapply(df1$DateTime, function(x) {df2$T[df2$DateTime==round(x, "hours")][1]})

#Do it with merge (will break if there are multiple matches)
df1$T <- merge(data.frame(DateTime=round(df1$DateTime, "hours")), df2, all.x=T, sort=F)[2]


text:
Q: Message Content to String Exception I'mworking on an E- Mail Client for my Android Phone using the JavaMail API. If I try to get the Content of an E- Mail, I get the following text in the logCat:

FROM: XXXXXXXXXXXXXXXXXXXXXXXXXX
TO: AG Blasorchester
SUBJECT: BITTE DENKT AN DIE SCHWARZE MAPPE / RINGORDNER
SendDate: Wed Feb 27 21:30:49 MEZ 2013
CONTENT-TYPE: TEXT/PLAIN; charset=iso-8859-1
Message Content:
Fehler: java.lang.ClassCastException:
  com.sun.mail.util.QPDecoderStream cannot be cast to java.lang.String

This is the thrown exception: java.lang.ClassCastException: com.sun.mail.util.QPDecoderStream cannot be cast to java.lang.String
I use the following code to get the Content:
public static void dumpPart(Part p) throws Exception {
    Log.i("Gestartet", "dumpPart Gestartet");
    if (p instanceof Message)
        dumpEnvelope((Message)p);

    /** Dump input stream ..

    InputStream is = p.getInputStream();
    // If "is" is not already buffered, wrap a BufferedInputStream
    // around it.
    if (!(is instanceof BufferedInputStream))
        is = new BufferedInputStream(is);
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);

    **/

    String ct = p.getContentType();
    try {
        pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
        pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null)
        pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids
     * fetching the actual content data until we need it.
     */
    try{
    if (p.isMimeType("text/plain")) {
        pr("This is plain text");
        pr("---------------------------");
        if (!showStructure && !saveAttachments)
        System.out.println((String)p.getContent());
    } else if (p.isMimeType("multipart/*")) {
        pr("This is a Multipart");
        pr("---------------------------");
        Multipart mp = (Multipart)p.getContent();
        level++;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
        dumpPart(mp.getBodyPart(i));
        level--;
    } else if (p.isMimeType("message/rfc822")) {
        pr("This is a Nested Message");
        pr("---------------------------");
        level++;
        dumpPart((Part)p.getContent());
        level--;
    } else {
        if (!showStructure && !saveAttachments) {
        /*
         * If we actually want to see the data, and it's not a
         * MIME type we know, fetch it and check its Java type.
         */
        Object o = p.getContent();
        if (o instanceof String) {
            pr("This is a string");
            pr("---------------------------");
            System.out.println((String)o);
        } else if (o instanceof InputStream) {
            pr("This is just an input stream");
            pr("---------------------------");
            InputStream is = (InputStream)o;
            int c;
            while ((c = is.read()) != -1)
            System.out.write(c);
        } else {
            pr("This is an unknown type");
            pr("---------------------------");
            pr(o.toString());
        }
        } else {
        // just a separator
        pr("---------------------------");
        }

        }
    }catch(Exception e){
        Log.i("Fehler", "Fehler: " + e);
    }
}

Can I get the Message Content as a String without an exception?

A: Are there any German special characters in the From: XXXX-part in you sample or anywhere else in the headers? The email is RFC 2047 encoded, which happens when email headers contain non-US ASCII characters.
This code might work. Completely untested as I haven't got the environment set up, but might be a starting point.
if (p.isMimeType("text/plain")) {
  pr("This is plain text");
  pr("---------------------------");
  if (!showStructure && !saveAttachments) {
    if (p.getContent instanceof String) {
      System.out.println((String)p.getContent());
    } else if (p.getContent() instanceof QPDecoderStream) {
      BufferedInputStream bis = new BufferedInputStream(p.getContent());
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      while (true) {
        int c = bis.read();
        if (c == -1) {
          break;
        }
        baos.write(c);
      }
      System.out.println(new String(baos.toByteArray()));
    } else {
       //Handle different content types
    }
  }
}


text:
Q: Calling function variable/name info int a(int p){

return ++p;
};

int main(){
a(???);
return 0;
};

what do you write inside the parentheses? well....an example??? what's the purpose of putting a new name when calling?
(I am not sure how to explain exactly what I mean it is quite a general question..?) an explanation would be nice. I know I can write in "time","price" for example, but why cant I just use p?

A: You can't use p because p is not in scope at the point you call the function - in your code, p is local to a().
You could use p if you did something like:
int a(int p){
    return ++p;
};

int main(void) {
    int p = 4;
    int p_plus_one = a(p);
    return 0;
};

because they're both local to their own scopes, and don't collide.

A: there is nothing like you need to use a new name for passing the parameters into the function
you can pass any integer variable of your choice into the function a()
Example:
if you have a variable p declared this way , you can pass it also :
int main(){
int p = 50 ; //some integer value (it's necessary that the variable should be assigned a value)
a(p);
return 0;
};

or else if you have a variable time declared this way , you can pass it also :
int main(){
int time = 60 ; //some integer value (it's necessary that the variable should be assigned a value)
a(time);
return 0;
};


text:
Q: Display an image in JTextArea I am trying to write a chat client(multi-threaded) which should be capable of displaying images(sent by server) in the main chat window(JTextArea in my case)? Is there any way to do this directly or do I have to encode and parse back my image. For example Facebook chat lets you directly drag and drop images and displays them in main chat window. If we cannot do this in Java, please suggest some other Environment in which this is doable.

A: I think a JTextPane would suit your needs better: http://docs.oracle.com/javase/tutorial/uiswing/components/editorpane.html

A: It works:
JTextPane t = new JTextPane();
t.setContentType("text/html");
t.setText("");


text:
Q: Zoho forms featured without Subscription im create zoho form its working good but limited feature.
i want to use more zoho forms feature without subscription please guide me about this or tell me alernative solution for Form.


text:
Q: Print out an object with a for/in loop I am trying to print out a list of people and all of the people and information are in the object, I am trying to figure out how to use a for/in loop to print out the object.
Thank you!
Here's my code.
http://pastebin.com/TyUXF7Tf

A: var friends = {
  "bill" : {
    "firstName" : "Bill" ,
    "lastName" : "Bob" ,
    "number" : "(111) 111-1111" ,
    "address" : ['1111 1 Road','1 City','1 Province','11111']
  } , {
  "steve" : {
    "firstName" : "Steve" ,
    "lastName" : "G. Jones" ,
    "number" : "(123) 456-7891" ,
    "address" : ['1234 Steve Road','Seattle','WA','12345']
  }
}

var listLoop = function(friends) {
  for(var person in friends) {
    console.log("Whole Person: " , person);
    console.log("First Name: " , person.firstName);
    console.log("Last Name: " , person.lastName);
    console.log("Number: " , person.number);
    console.log("Address: ", person.address);
  }
};


text:
Q: react-bootstrap form getting "Row is not defined" error I'm using react-bootstrap in my React project and following their documented examples to create a form. If I understand correctly, I only need to import form to get all the Form functionality:
import Form from 'react-bootstrap/Form'

Specifically, I'm following this pretty simple example:
<Form>
  <Form.Group as={Row} controlId="formPlaintextEmail">
    <Form.Label column sm="2">
      Email
    </Form.Label>
    <Col sm="10">
      <Form.Control plaintext readOnly defaultValue="email@example.com" />
    </Col>
  </Form.Group>

  <Form.Group as={Row} controlId="formPlaintextPassword">
    <Form.Label column sm="2">
      Password
    </Form.Label>
    <Col sm="10">
      <Form.Control type="password" placeholder="Password" />
    </Col>
  </Form.Group>
</Form>

However, I get the following error in Chrome DevTools:
MyComponent.jsx:430 Uncaught ReferenceError: Row is not defined

I tried importing row, but that doesn't resolve the error. Any ideas what's missing?
Seems to me either their documented example is incomplete or broken, or there's some additional import I need to add to use react-bootstrap.
Update 2022: I updated the above link to the example, which had changed. Interestingly, the examples still only mentions importing Form (import Form from 'react-bootstrap/Form') and leave out the surprising need to also import Row and Col.

A: You should import Row, Col and Form from react-bootstrap. Refer this MDN link for more about JavaScript imports.
import React from "react";
import ReactDOM from "react-dom";
import { Col, Row, Form } from "react-bootstrap";

function App() {
  return (
    <Form>
      <Form.Group as={Row} controlId="formPlaintextEmail">
        <Form.Label column sm="2">
          Email
        </Form.Label>
        <Col sm="10">
          <Form.Control plaintext readOnly defaultValue="email@example.com" />
        </Col>
      </Form.Group>

      <Form.Group as={Row} controlId="formPlaintextPassword">
        <Form.Label column sm="2">
          Password
        </Form.Label>
        <Col sm="10">
          <Form.Control type="password" placeholder="Password" />
        </Col>
      </Form.Group>
    </Form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Here is the working link.


text:
Q: How to change a table cell from $ to € in Pages? I'm using Pages' Invoice templates, and it's been grand so far. Now I need to send an invoice to Europe, and the sums need to be in euros rather than dollars. How can I change the currency type in the table?

A: Use the inspector to change the table cell formatting symbol.


text:
Q: How do I keep children of certain parent menus expanded by default on a sidebar? We are using advanced sidebar pages menu:
https://wordpress.org/plugins/advanced-sidebar-menu/
to expand / collapse children menus on a sidebar.
By default, the parent sidebar menu is expanded, represented by UP arrow and the children of the parent sidebar are collapsed, represented by DOWN arrow.
If a user wishes to see the contents of each children menu, s/he clicks to expand this.

This works well.
The issue we are currently having is that we would like to get some of those children menus expanded by default just like the parents.
To do this, I created a script file called customp-scrpt.js and used the following custom script:
(function ($) {
    $( function() {
        setTimeout(function () {
            $('page-id-2110 .child-sidebar-menu .has_children.closed span').click();
               }, 500);
    });
})(jQuery);

Credit: Mat Lipe, author of the plugin from the link above.
I added this file into the theme js file.
Then I used the following script to register the above script file:
function wptuts_scripts_with_jquery()
{
    // I can register the script it for a theme:
    wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery' ) );

    // Enqueue the script:
    wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_jquery' );

I added this script to the functions.php file inside wp_includes folder.
So far, this script is not doing what it is intended to do.
All the children of parent menus have all stayed closed, especially the ones we are  interested in keeping expanded by default.
Any ideas what could be missing or what I am doing wrong?


text:
Q: Convert Postgis table to SQL Server 2008 Is there a simple way to do that?

A: Perhaps just export to shapefile or kml and then reimport to SQL Server using one of these standard tools.  For example:
SELECT  ST_AsKML(the_geom) FROM the_spatial_table WHERE ....
This outputs kml, which you can then reimport to SQL Server (I assume, not SQL server guy, but it is a common format.)  Here: http://www.postgis.org/documentation/manual-1.4/ch07.html#Geometry_Outputs are the other geometry output formats for Postgis.


text:
Q: Changes to CSS in inspector stylesheet apply but those same changes will not apply in my CSS file Bit of a strange occurrence with my web page, currently trying to resize the font of a facebook like button I have on my website.
Currently the HTML I'm targeting is:
2.1k people like this. Be the first of your friends.

In the google chrome console adding either of the following will change the font
1.
#u_0_3 { font-size: 14px }
2.
span#u_0_3 { font-size: 14px }
but adding either of these lines of code to my web pages stylesheet has absolutely no effect. No clue how to proceed from here as it works in one stylesheet and not the other?

A: The reason the styles aren't updating when adding the code to your stylesheet as opposed to in the browser is because you're trying to a stylesheet on an iframe, which isn't possible. You can however add the styles using jQuery or something along those lines.
Try this...
$("iframe#idhere").contents().find("span#u_0_3").css('font-size', '14px');

A: Ensure that you have added CSS file reference in your HTML.
Also, clear browser cache and load the page.


text:
Q: How can change format date in a text field? I want change format date in a textfield in my form, but show this error
undefined method `strftime' for :fecha:Symbol

This is my code
<%= f.text_field :fecha.strftime("%d/%m/%Y") %>

any suggestion?

A: try this
<%= f.text_field :fecha, :value => @object.facha.strftime("%d/%m/%Y") %>

@object will be the object for which you are creating a form
for eg
<%= form_for @object %>


text: Q: How to make MenuStrip on the same level as closing/minimising buttons using WinForms? I wonder if this can be done witout disabling FormBorderStyle, if not, then how to add exactly the same buttons as in Win 10 default closing buttons. Or how to make this design(MenuStrip on the same row with closing/minimizing buttons as in VS 2019) using Windows Forms?


text:
Q: Inherited interface causes a cycle in the interface hierarchy I get the following error

Inherited interface 'ConsoleApplicationTest.Program.B' causes a cycle
  in the interface hierarchy of 'ConsoleApplicationTest.Program.IB'

when I try to compile this code :
public interface IA<T>
{
}

public abstract class A<T> : IA<T>
{
}

public interface IB : IA<B.C>
{
}

public class B : A<B.C>, IB
{
    public class C
    {
    }
}

This is easily fixed by :

*

*extracting class C of class B.

OR

*

*modifying interface IB<T> : IA<T> and class B : A<B.C>, IB<B.C> (but that leads to modify every use of interface IB in the code)

But this does not explain why I get this compilation error. Any idea ?


text:
Q: The app build failed to produce artifact folder Angular Azure Static Web App Deployment Issue When i try to build angular app using azure devops and deploy to azure static web app i'm receiving below error

The app build failed to produce artifact folder: 'dist/harmony-front'. Please
ensure this property is configured correctly in your deployment
configuration file.

I tried by changing output_location to / , dist, /dist , dist/harmony-front,
nothing seems to work
here's the yaml code for the deployment section
- task: AzureStaticWebApp@0
  inputs:
      app_location: "/"
      api_location: "api"
      output_location: "./dist/harmony-front"
      app_build_command: 'npm run build:prod'
      skip_api_build: true
      verbose: true

  env:
      continueOnError: true
      CUSTOM_BUILD_COMMAND: "npm install --force"
      azure_static_web_apps_api_token: $(deployment_token)

What was the mistake i made
Thanks

A: I have tried to repro the same and got positive results after following the below steps.
Step 1: Create a simple angular project and build the project on a local machine and inspect the dist folder.

Step 2: Push the code to Azure Repos.
Step 3: Create azure pipeline as shown below.
trigger: none
pool:
  vmImage: ubuntu-latest
steps:
- task: NodeTool@0
  inputs:
    versionSpec: '18.x'
  displayName: 'Install Node.js'
- script: |
    npm install -g @angular/cli
  displayName: 'install angular cli'
- task: Npm@1
  inputs:
    command: 'install'
  displayName: 'npm install'
- task: Npm@1
  inputs:
    command: 'custom'
    customCommand: 'run build'
  displayName: 'npm build'
- task: Bash@3
  inputs:
    targetType: 'inline'
    script: |
      pwd
      ls -l
      ls -l dist/
- task: AzureStaticWebApp@0
  displayName: 'Deploy Azure static webapp'
  inputs:
    app_location: '/'
    output_location: 'dist/my-app'
  env:
    azure_static_web_apps_api_token: $(static-webapp-token)

Step 4: Verify the result.

If you are still facing that issue, verify the AzureStaticWebApp@0
output location path in angular.json file as below. Both paths must be exact.

A: Actually I found the issue and will post for future reference. if someone had  the same issue.
issue start when you override build command using CUSTOM_BUILD_COMMAND will overwrite the RUN_BUILD_COMMAND so based on the comment of the issue posted on Github instead of npm install --force command combined with build like npm install --force && npm run build  works like charm


text:
Q: Android Sync data from Web server to SQLite Local DB I'm trying to syncing the data from SQL web server into Android SQLite database, using Android SQLiteAssetHelper I can find and get the data from web server successfully but the application is crashed when I try to insert the result (data) into SQLite DB.
This is the source code of inserting data into local SQLitedatabase
    public long syncDB(String id, String kr_wd, String my_wd) {

    String KEY_ID = "_id";
    String KEY_KR = "kr_word";
    String KEY_MYN = "myn_word";
    String KEY_SYNC = "sync_db";

SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, id);
values.put(KEY_KR, kr_wd);
values.put(KEY_MYN, my_wd);
values.put(KEY_SYNC, 1);

return db.insert("words",null, values);
//db.close();

}

And here's the process which attempt to insert results into SQLite DB.
    for (int i = 0; i < jArray.length(); i++) {
                        json_data = jArray.getJSONObject(i);

                        String word_id =json_data.getString("id");
                        String k_words = json_data.getString("kr_word");
                        String m_words =json_data.getString("myn_word");

                        al.add(word_id);  //id
                        al1.add(k_words); //korea
                        al2.add(m_words);  //myanmar

                        db.syncDB(word_id, k_words, m_words);

                    }