text:
Q: Eliminate $\theta$ from $4x=5\cos\theta -\cos 5\theta$ and $4y=5\sin\theta -\sin 5\theta$ Eliminate $\theta$ from the equations.
$$4x=5\cos\theta -\cos 5\theta$$
$$4y=5\sin\theta -\sin 5\theta$$
Alternative forms are
$$x=5\cos^3\theta-4\cos^5\theta$$
$$y=5\sin^3\theta-4\sin^5\theta$$
and $$x=\cos^3\theta(3-2\cos2\theta)$$
$$y=\sin^3\theta(3+2\cos2\theta)$$

A: These are the parametric equations of an epicycloid, where the large circle has radius $R=1$, and the smaller exterior rolling circle has radius $r=\frac{1}{4}$.
A possible simplification is writing
$$4a=4(x+i y) = 5 z - z^ 5\\
4b=4(x-i y) = \frac{5}{z} - \frac{1}{z^5}$$
where $z = \cos \theta + i \sin \theta$
and get a relation between $a$, $b$, that implies a relation between $x$ and $y$, see link. Or, we can just give the result provided by WA :
$$-81 - 45 x^2 + 365 x^4 - 15 x^6 - 480 x^8 + 256 x^{10} - 45 y^2 - 2395 x^2 y^2 - 45 x^4 y^2 - 1920 x^6 y^2 + 1280 x^8 y^2 + 365 y^4 - 45 x^2 y^4 - 2880 x^4 y^4 + 2560 x^6 y^4 - 15 y^6 - 1920 x^2 y^6 + 2560 x^4 y^6 - 480 y^8 + 1280 x^2 y^8 + 256 y^{10}=0$$
a curve of degree $10$
$4$ leaves" />
We can simplify the defining polynomial by writing it as a polynomial in $x^2 + y^2$ and $x^2 y^2$.
$\bf{Added:}$ Following the solution of @ACB: we have the polar representation ($x = r \cos \phi$, $y=r \sin \phi$)
$$\cos^2 2 \phi = \frac{(9 - 4 r^2)(16 r^4+ 3 r^2 + 6)^2}{3125 r^4}= f(r)$$
The function in $r>0$ on RHS is strictly decreasing on $(0, \infty)$. Indeed, we have
$$f'(r) = -24\, \frac{(-1 + r^2)^2 (9 + 16 r^2) (6 + 3 r^2 + 16 r^4)}{3125\, r^5}$$
Now, $f(1) = 1$, and $f(\frac{3}{2})=0$. We see that our curve is situated between the circles of radius $1$, and $\frac{3}{2} = 1 + 2\cdot \frac{1}{4}$, as it should.
So now we can write the curve in polar coordinates
$$r = f^{-1}(\cos^2 2\phi)$$
where $f^{-1}\colon [0,1]\to [1, \frac{3}{2}]$ is the inverse function of $f$.

A: Let $c=\cos2\theta$.
$$4x=5\cos\theta -\cos 5\theta\tag1$$
$$4y=5\sin\theta -\sin 5\theta\tag2$$
Squaring and adding ,$$16(x^2+y^2)=25+1-10\cos4\theta$$ $$8(x^2+y^2)=13-5(2c^2-1)$$ $$5c^2=9-4(x^2+y^2)=k$$
Squaring and subtracting, $$16(x^2-y^2)=25\cos2\theta+\cos10\theta-10\cos6\theta$$ $$16(x^2-y^2)=25c+(16c^5-20c^3+5c)-10(4c^3-3c)$$ $$4(x^2-y^2)=c(4c^4-15c^2+15)$$
Substituting $k$,
$$100(x^2-y^2)=c(4k^2-75k+375)$$
Further simplifying leads to, $$25(x^2-y^2)=c(16\lambda^2+3\lambda+6)$$ where $\lambda=(x^2+y^2)$.
Squaring again and replacing all values finally we get, $$3125(x^2-y^2)^2=[9-4(x^2+y^2)][16(x^2+y^2)^2+3(x^2+y^2)+6]^2$$
And this is that epicycloid, as being described in @orangeskid's answer!


text:
Q: What algorithm does GeoPandas use for calculating distances between polygons? I'm using ArcGIS Pro and GeoPandas for spatial analysis operations. I noticed that the distance operations in ArcGIS and the GeoPandas don't align. I wonder which algorithm GeoPandas uses for its distance calculations (function distance).
In my example I selected polygons within a distance of 10 km from another polygon. One polygon is selected in ArcGIS but not in GeoPandas as the distance there is > 10 km. The data is projected to the same crs in both cases.
It's not surprising that different distance algorithms are used, I just can't find any information on which algorithm GeoPandas uses. I already checked the documentation and the code in Git.
ArcGIS uses vertex distances for polygons (ArcGIS documentation here).
Has anyone background information on the GeoPandas distance tool algorithm?
Help is greatly appreciated!

A: There are a lot of dependencies geopandas relies on. For the distance computation that involves point to point object, it uses shapely Euclidean distance as can be traced to this link:- https://github.com/Toblerity/Shapely/blob/master/shapely/geometry/base.py
If you have a geodataframe df5 like this
   a  b                 geometry
0  0  1  POINT (0.00000 0.00000)
1  0  2  POINT (1.00000 0.00000)
2  1  3  POINT (0.00000 2.00000)
3  5  4  POINT (1.00000 1.00000)

You can do computation check with
df5.geometry.values[0].distance( df5.geometry.values[3] )

The result will be 1.4142135623730951, which is the Euclidean distance.

A: There is no exact explanation for this in the shapely documentation. However, it can be estimated that
https://shapely.readthedocs.io/en/latest/manual.html#shapely.ops.nearest_points is likely to be used.
So I think it will represent the minimum distance between two polygons.
However, this is just my opinion, and I think you will have to test it yourself in the end. In my experience shapely doesn't produce the closest points other than the points shown on the polygon. (You can see this in an example where shapely calculates the minimum distance between a point and a line. The minimum distance is not the distance along the vertical tangent, but the closest point to the line's vertices.)
Since it is based only on points that already exist in polygons, I think that there may be a difference between the two values if ARCGIS finds and calculates the contact point with the minimum distance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery Datatables in a portlet I have a portlet and one of its JSP pages contains a table populated with java objects:
 Here is a sample code:
<% {%>

From	To	Time

        <c:forEach var="message" items="${messages}">

                <c:out value="${message.sender}"/>
                <c:out value="${message.receiver}"/>
                <c:out value="${message.timestamp}"/>

        </c:forEach>

<% } %>

I would like to make this table a DataTable using JQuery DataTables plugin. I put the downloaded libraries in docroot/js folder in my Liferay portlet and set the path to it in Liferay-portlet.xml conf like this (as instructed in the tutorial I referenced):
/js/DataTables/media/js/jquery.js
/js/DataTables/media/js/jquery.dataTables.js

Now the magic part comes - how do I actually init the dataTable from my example?
I thought, that inserting the following script udner the table in my JSP (according to the tutorial) would do, but it does nothing:

What did I do wrong? Perhaps I did something wrong with specifying the path to my JQuery libraries... or am using it wrong? Should I call this function somewhere else? I am a newbie when it comes to JS and Jquery (sorry for dummy question), I just need to get this one thing working...
EDIT: SOLVED by replacing  with

A: You must point dataTable to your data.
If your messages variable is a list of objects encoded as JSON string received ie. from @RenderMapping method, you can use this code:

From	To	Time


text:
Q: Subalgebra condition in Engel's theorem An equivalent version of Engel's theorem says that

Let $L$ be a subalgebra of $\mathfrak{gl}(V)$, $V$ finite dimensional. If $L$ consists of nilpotent endomorphisms and $V\ne 0$, then there exists a nonzero $v\in V$ for which $L v = 0$.

Why do we need this condition that $\rho:L\hookrightarrow \mathfrak{gl}(V)$? If this representation is not faithful can't we quotient out the kernel $\overline{\rho}:L/\ker\rho\to \mathfrak{gl}(V)$ and conclude that $(L/\ker\rho)\cdot v = 0$ and therefore $L\cdot v = 0$?

A: You're completely right, maybe it's a matter of taste.
One benefit of the formulation you quote is that it is very elementary: it doesn't speak about abstract representations of Lie algebras, but only about spaces of nilpotent matrices closed under commutator - pure linear algebra, if you want. However, as far as I remember, for the usual inductive proof one needs to change both ${\mathfrak g}$ and $V$ and consider representations which are not necessarily faithful, so your version of the theorem fits that induction better than the quoted one, and I'd therefore would prefer it, too.
It's similar for Lie's Theorem: Before proving the representation theoretic version, one shows that solvable subalgebras of matrices admit common eigenvectors (over an algebraically closed field) and deduces the other formulations afterwards.


text:
Q: sorting rows in a pandas dataframe in a way which is not alphabetical I have some dataframes (df) with categorical data starting with: a, b, c and a category for "remaining categories".
I would like to sort the month column in the dataframe ascending=true, but then have the category column sorted so that they are in the following order:
c

a

b

"remaining category"
Is this possible? --> Basically I want a custom sort order for a specific column, but then have the month column sorted in order of date.

A: docs are here
In [8]: df = DataFrame({'A' : [1,1,1,2,2,3], 'B' : list('bbcdae') })

In [9]: df.dtypes
Out[9]:
A     int64
B    object
dtype: object

In [10]: df['B'] = pd.Categorical(df['B'],categories=list('ghbaedfc'))

In [11]: df
Out[11]:
   A  B
0  1  b
1  1  b
2  1  c
3  2  d
4  2  a
5  3  e

In [12]: df.dtypes
Out[12]:
A       int64
B    category
dtype: object

In [13]: df.sort(['B','A'])
Out[13]:
   A  B
0  1  b
1  1  b
4  2  a
5  3  e
3  2  d
2  1  c

A: You can do it with a dict and adding a new 'sort' column to your dataframe.  Check out this similar question  Custom sorting with Pandas

A: Pandas sort() was deprecated and removed from Pandas with release 0.20 (2017-05-05).
Pandas sort_values() and sort_index() are now used instead of sort(). To get a df in categorical order use pd.Categorical()
df = pd.DataFrame({'Panel':['Left', 'Right', 'Top', 'Bottom','Left'],
         Value':[70, 50, 30, 40, 60]})
df['Panel'] = pd.Categorical(df['Panel'],
        categories=['Top','Bottom','Left','Right'],ordered=True)

results
    Panel   Value
2   Top     30
3   Bottom  40
0   Left    70
4   Left    60
1   Right   50


text:
Q: Why are those definitions not legal in C? I'm reading a book about C and I don't understand this concept:

Another common misconception is thinking of a const qualified variable as a constant expression. In C, const means "read-only", not "compile time constant". So, global definitions like const int SIZE = 10; int global_arr[SIZE]; and const int SIZE = 10; int global_var = SIZE; are not legal in C.

I also don't understand very good the diference between const variable and constant expression. All const variables are constant expressions, right? I have readed other questions about this topic but I still without understantig. Thanks.

A: suppose you have
int a = 42;
const int *b = &a;

now *b is const ie read-only. You are not allowed to change *b without casting the const away (thanks Eric Postpischil)
// *b = -1; // not allowed
a = -1;
printf("%d\n", *b); // print -1

The point is: the value of a const qualified object may change. A constant value never changes.

A: What they basically mean is, In C it is illegal to use a const qualified variable to initialize another variable or determine the size of an array with it at global scope, like for example:
const int SIZE = 5;
int a = SIZE;              // This is not allowed.
int b[SIZE];               // This is also not allowed.

int main(void)
{
   ...
}

This is because variables and arrays at global scope need to be determinate at compilation time. A const qualified variable is still a variable and the values of variables are computed/evaluated at run-time.
A macro constant, which is a "compile time constant" could be used for this like f.e.:
#define SIZE 15

int a[SIZE];             // This is ok.
int b = SIZE;            // This is ok, too.

I also don't understand very good the difference between const variable and constant expression. All const variables are constant expressions, right?

No.
Quote from ISO:IEC 9899/2018 (C18), Section 6.6/2:

"A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be."

A constant expression is a literal expression which always get evaluated to the same value - the evaluated value is constant. Therefore it can be evaluated at compile time.
F.e.:
5 + 4

is always 9 and can therefore be evaluated at compilation time.
Whereas a const variable:
const int SIZE = 5;

or
(const int SIZE 5;)

5 + 9 + SIZE;

is not a constant expression as it implies a variable. Although the variable SIZE is qualified by const (which means that it can´t be modified after initialization), it is not a constant expression, because a variable, does not matter if it const or not, is computed/evaluated at run-time.
A const qualified variable is not nor can be a part of a constant expression.


text:
Q: How to increase the size of the int I'm looking for a way so that I can get big numbers.
I want to calculate 38^n for n>4000
So is there any way to do this?
Kindly help me.

A: Look for a BigInt library like this one if the unsigned long long (64-bit integer) does not fit your needs.

A: Since 38^4000 =
[encoded data, 6320 characters]
You definitely need some kind of big int library. You can find one quite easily on Google or even (if you plan only specific operations), write one on your own. For instance, the above result comes from my own calculator, which supports big integer evaluations.


text:
Q: Tidy rendered HTML output in Chrome's View Source? More often than not when using things like CMS'es and static site generators, HTML output looks like rubbish (wrong indendation being the most annoying flaw).
Is there any solution for having rendered output in Chrome's "View Source" tidied / prettified?
In my case I'm using a static site generator. Everything looks perfect in the editor but code gets screwed when previewing in the browser.
(I know I can probably add a build task (e.g. Grunt) to handle HTML-prettifying. But in many cases, such as when using live-reload tools (I'm using Mixture.io) where you actually preview an internal version of the site, that's not an optimal solution.)

A: I recommend Quick Source Viewer.
It can show you the source of the current page formatted and colour coded.
It's pretty powerful, showing all 'sources' of the page, be it css, js or html. Even things like inline css/js can be viewed individually (with injected code highlighted). And the best part is it prettifies all of them, even the css (which chrome's dev tools still refuses to do).

A: I usually just Ctrl+Shift+I for Inspect. The Elements tab has all the html, with clor coding and hide-unhide for sections.


text:
Q: How to get the segments of a path geometry in Direct2D? The following picture show a path geometry in Direct2D, it contains 5 segments, each segment is a straight line, my request is that, given such a hill, i want to get all the 5 lines.

but it seems there is no related API can get the segments of a path geometry in Direct2D, I see the ID2D1PathGeometry interface provide a method GetSegmentCount, if we can not get the segments, why Microsoft provide this method?

A: You can do this with ID2D1PathGeometry::Stream(). You will have to write a class that implements ID2D1GeometrySink. You may find it useful to implement this in a generalized sense such that instead of looking for the exact data that you need now, it can pump out an object tree. If you need an example for what type of object model to use, look no further than WPF's System.Windows.Media.Geometry ( http://msdn.microsoft.com/en-us/library/system.windows.media.geometry.aspx ).
You can also easily convert from those classes back to ID2D1PathGeometry, and use whichever is most comfortable or appropriate for any situation. I've written both conversions and found it to be pretty straightforward once I realized they were using the same "language." I especially found that it helped to organize my understanding as to the difference between "figures" and "segments."

A: If you have a PathGeometry, then using PathGeometry::Stream() is good.
However, if you have a basic Geometry and you want to accomplish the same, then you can do the following:

*

*Implement your own GeometrySink to "catch" the geometry components

*Create an empty PathGeometry

*Use Geometry::Combine to combine (union) your geometry with the empty geometry.

The results will be deposited in your GeometrySink.

A: implement a class named SpecializedSink that inherits from the ID2D1SimplifiedGeometrySink interface, the extended AddLines method called by ID2D1Geometry::Simplify to retrieves the geometry data.
suggest you read the [example for retrieve data from geometry] http://msdn.microsoft.com/en-us/library/windows/desktop/ee453682%28v=vs.85%29.aspx by extending ID2D1SimplifiedGeometrySink.


text:
Q: How to add Required Field Validator to checked ListBox? I'm using a checked list-box inside a div tag and I want to validate the checked list-box. How can I achieve this?

A: You can use javascript to validate the checkboxlist. please find the below code to get an idea:
<script type = "text/javascript">
var minOccurance= 1
function Validate()
{
   var yourCheckboxList= document.getElementById("<%=CheckBoxList1.ClientID%>");
   var checkbox = yourCheckboxList.getElementsByTagName("input");
   var counter=0;
   for (var i=0;i<checkbox.length;i++)
   {
       if (checkbox[i].checked)
              counter++;
   }

   if(minOccurance>counter)
   {
       alert("Please select atleast " + minOccurance +  " item(s)");
       return false;
   }
   return true;
}
</script>

Hope this will you to solve the issue.


text:
Q: Getting max amplitude for an audio file per second I know there are some similar questions here, but most of them are concerning generating waveform images, which is not what I want.
My goal is to generate a waveform visualization for an audio file, similar to SoundCloud, but not an image. I'd like to have the max amplitude data for each second (or half second) of an audio clip in an array. I could then use this data to create a CSS-based visualization.
Ideally I'd like to get an array that has all the amplitude values for each second as a percentage of the maximum amplitude of the entire audio file. Here's an example:
[
    0.0,  # Relative max amplitude of first second of audio clip (0%)
    0.04,  # Relative max amplitude of second second of audio clip (4%)
    0.15,  # Relative max amplitude of third second of audio clip (15%)
    # Some more
    1.0,  # The highest amplitude of the whole audio clip will be 1.0 (100%)
]

I assume I'll have to use at least numpy and Python's wave module, but I'm not sure how to get the data I want. I'd like to use Python but I'm not completely against using some kind of command-line tool.

A: If you allow gstreamer, here is a little script that could do the trick. It accept any audio file that gstreamer can handle.

*

*Construct a gstreamer pipeline, use audioconvert to reduce the channels to 1, and use level module to get peaks

*Run the pipeline until EOS is hit

*Normalize the peaks from the min/max found.

Snippet:
import os, sys, pygst
pygst.require('0.10')
import gst, gobject
gobject.threads_init()

def get_peaks(filename):
    global do_run

    pipeline_txt = (
        'filesrc location="%s" ! decodebin ! audioconvert ! '
        'audio/x-raw-int,channels=1,rate=44100,endianness=1234,'
        'width=32,depth=32,signed=(bool)True !'
        'level name=level interval=1000000000 !'
        'fakesink' % filename)
    pipeline = gst.parse_launch(pipeline_txt)

    level = pipeline.get_by_name('level')
    bus = pipeline.get_bus()
    bus.add_signal_watch()

    peaks = []
    do_run = True

    def show_peak(bus, message):
        global do_run
        if message.type == gst.MESSAGE_EOS:
            pipeline.set_state(gst.STATE_NULL)
            do_run = False
            return
        # filter only on level messages
        if message.src is not level or \
           not message.structure.has_key('peak'):
            return
        peaks.append(message.structure['peak'][0])

    # connect the callback
    bus.connect('message', show_peak)

    # run the pipeline until we got eos
    pipeline.set_state(gst.STATE_PLAYING)
    ctx = gobject.gobject.main_context_default()
    while ctx and do_run:
        ctx.iteration()

    return peaks

def normalize(peaks):
    _min = min(peaks)
    _max = max(peaks)
    d = _max - _min
    return [(x - _min) / d for x in peaks]

if __name__ == '__main__':
    filename = os.path.realpath(sys.argv[1])
    peaks = get_peaks(filename)

    print 'Sample is %d seconds' % len(peaks)
    print 'Minimum is', min(peaks)
    print 'Maximum is', max(peaks)

    peaks = normalize(peaks)
    print peaks

And one output example:
$ python gstreamerpeak.py 01\ Tron\ Legacy\ Track\ 1.mp3
Sample is 182 seconds
Minimum is -349.999999922
Maximum is -2.10678956719
[0.0, 0.0, 0.9274581631597019, 0.9528318436488018, 0.9492396611762614,
0.9523404330322813, 0.9471685835966183, 0.9537281219301242, 0.9473486577135167,
0.9479292126411365, 0.9538221105563514, 0.9483845795252251, 0.9536790832823281,
0.9477264933378022, 0.9480077366961968, ...


text:
Q: Dumping Collection to YAML file with PyYaml I am writing a python application. I am trying to dump my python object into yaml using PyYaml. I am using Python 2.6 and running Ubuntu Lucid 10.04. I am using the PyYAML package in Ubuntu Package: http://packages.ubuntu.com/lucid/python/python-yaml
My object has 3 text variables and a list of objects. Roughly it is something like this:
ClassToDump:

   #3 text variables
   text_variable_1
   text_variable_2
   text_variable_3
   #a list of AnotherObjectsClass instances
   list_of_another_objects = [object1,object2,object3]

AnotherObjectsClass:
   text_variable_1
   text_variable_2
   text_variable_3

The class that I want to dump contains a list of AnotherObjectClass instances. This class has a few text variables.
PyYaml somehow does not dump the collections in AnotherObjectClass  instance. PyYAML does dump  text_variable_1, text_variable_2, and text_variable_3.
I am using the following pyYaml API to dump ClassToDump instance:
classToDump = ClassToDump();
yaml.dump(ClassToDump,yaml_file_to_dump)

Does any one has any experience with dumping a list of objects into YAML ?
Here is the actual full code snippet:
def write_config(file_path,class_to_dump):
    config_file = open(file_path,'w');
    yaml.dump(class_to_dump,config_file);

def dump_objects():

rule = Miranda.Rule();
rule.rule_condition = Miranda.ALL
rule.rule_setting = ruleSetting
rule.rule_subjects.append(rule1)
rule.rule_subjects.append(rule2)
rule.rule_verb = ruleVerb

write_config(rule ,'./config.yaml');

This is the output :
!!python/object:Miranda.Rule
rule_condition: ALL
rule_setting: !!python/object:Miranda.RuleSetting {confirm_action: true, description: My
    Configuration, enabled: true, recursive: true, source_folder: source_folder}
rule_verb: !!python/object:Miranda.RuleVerb {compression: true, dest_folder: /home/zainul/Downloads,
  type: Move File}

A: The PyYaml module takes care of the details for you, hopefully the following snippet will help
import sys
import yaml

class AnotherClass:
    def __init__(self):
        pass

class MyClass:
    def __init__(self):
        self.text_variable_1 = 'hello'
        self.text_variable_2 = 'world'
        self.text_variable_3 = 'foobar'
        self.list_of_another_objects = [
            AnotherClass(),
            AnotherClass(),
            AnotherClass()
        ]

obj = MyClass()
yaml.dump(obj, sys.stdout)

The output of that code is:
!!python/object:__main__.MyClass
list_of_another_objects:
- !!python/object:__main__.AnotherClass {}
- !!python/object:__main__.AnotherClass {}
- !!python/object:__main__.AnotherClass {}
text_variable_1: hello
text_variable_2: world
text_variable_3: foobar


text:
Q: How to display an image using a different filename than the physical filename? In my image hosting webapp I created a hackish way for image de-duplication to save on storage space by having an image.rb model with paperclip to store physical images and a second model imagelink.rb to store image names which link to the physical image. So in my imagelink model I use "belongs_to: image" and add an index on the imagelink to image_id of the image. The naming of the image and imagelink is simply an encoded version of the ActiveRecord ID.
When uploading the image I simply check it's md5sum to see if the image already exists if it does exist then I create a new imagelink ID and use the image ID of the original image. Otherwise I save the image and create a new image ID. This allows me to have a physical image like "vb56.jpg" and an encoded imagelink like "vb56.jpg" as well as a second imagelink like "4gb7.jpg" which also uses the physical image "vb56.jpg"
So naturally now I want to display the original physical image "vb56.jpg" but using the name "4gb7.jpg" when being accessed from the "4gb7.jpg" imagelink. I can achieve this by making another request for each imagelink which would look something like this:
images_controller.rb
before_action :set_image, only: [:show, :show_direct]

def show_direct
  path = @image.image.image.url
  url = Rails.root.join('uploads' + path)
  send_file url, type: @image.image.image_content_type, disposition: 'inline'
end

def set_image
  @image = ImageLink.decode(params[:id])
  raise 'image not found' if @image.nil?
end

image_view.html.erb
<%
  id = @image.encoded_id
  ext = @image.image.extension
%>
<img src="<%= MYAPP::DOMAIN %><%= id %>.<%= ext %>" class="image-display" />

So two problems doing it this way is 1) This is probably going to create slowness as well as tons of requests to the rails server for each image displayed on a page. 2) This is messing up the way I store session[:previous_url] for logging in with devise which is "session[:previous_url] = request.fullpath" since each image is a request it's storing the last requested image as the previous_url instead of the actual page the user is on.
Is there a way I can display the image without making tons of requests like currently doing? Doing the proper way with <%= image_tag(@image.image.image.url) %> to display the physical image will show the image as the original filename but I'd like it to show the filename as the imagelink name so that to the user the physical image name will always match the imagelink name.
Also am I doing session[:previous_url] wrong? Is there a better way to do it to capture the page URL rather than the URL of other requests coming from within the page?


text:
Q: How to use SpaceBar button inside an application to invoke quick look i had displayed some images in collectionview. now i want to select the image and press space button. If i pressed Space button , the image should quicklook in a seperate window. any idea?

A: On your view, do this:
- (void)keyDown:(NSEvent *)event
{
  unichar firstChar = 0;
  if ([[event charactersIgnoringModifiers] length] > 0)
    firstChar = [[event charactersIgnoringModifiers] characterAtIndex:0];

  if (firstChar == ' ')
  {
    if ([QLPreviewPanel sharedPreviewPanelExists]
        && [[QLPreviewPanel sharedPreviewPanel] isVisible])
    {
      [[QLPreviewPanel sharedPreviewPanel] orderOut:nil];
    }
    else
    {
      [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
      [[NSApp mainWindow] makeKeyWindow];
    }
  }
  else if (firstChar == NSRightArrowFunctionKey)
  {
    if ([QLPreviewPanel sharedPreviewPanelExists]
        && [[QLPreviewPanel sharedPreviewPanel] isVisible])
    {
      [[QLPreviewPanel sharedPreviewPanel] selectNextItem];
      return;
    }
  }
  else if (firstChar == NSLeftArrowFunctionKey)
  {
    if ([QLPreviewPanel sharedPreviewPanelExists]
        && [[QLPreviewPanel sharedPreviewPanel] isVisible])
    {
      [[QLPreviewPanel sharedPreviewPanel] selectPreviousItem];
      return;
    }
  }
  else
    [super keyDown:event];
}

Then, I do this in my app's delegate (AppDelegate.m):
- (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel *)panel
{
  //note that this methods indeed gets called because NSApp's
  //delegate is in the responder chain.
  return YES;
}

- (void)beginPreviewPanelControl:(QLPreviewPanel *)panel
{
  previewPanel = panel; //set an ivar
  [panel setDataSource:self];
}

- (void)endPreviewPanelControl:(QLPreviewPanel *)panel
{
  previewPanel = nil;
}

- (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel *)panel
{
  //return a number of your choice (depends on your own app)
}

- (id <QLPreviewItem>)previewPanel:(QLPreviewPanel *)panel
                previewItemAtIndex:(NSInteger)index
{
  //return an object of your choice (depends on your app)
}

- (void)handleCurrentFileItemsSelectionChange:(NSNotification *)note
{
  [previewPanel reloadData]; //referring to the ivar
}

A: i finally got. i just replaced imageViewes and put NSButton and setted spacebutton as keyequivalent as
- (BOOL)isOneOfMyKeyEquivs:(NSString *)keyChar
{
    if (([keyChar isEqualToString:@" "])||([keyChar isEqualToString:@"\r"])) {
        return YES;
    } else {
        return NO;
    }
}
- (BOOL)performKeyEquivalent:(NSEvent *)theEvent
{

        //NSLog(@"OK");
        NSString* keyChar = [theEvent characters];
        if ([self isOneOfMyKeyEquivs:keyChar])
        {
            [[self cell] setKeyEquivalent:keyChar];
        }
        return [super performKeyEquivalent:theEvent];

    return NO;
}

and performed button action.


text:
Q: Is this the correct way to remove items from localStorage array? When the pushFrontBtn is clicked an emoji add to the front of the localStorage array, and when pushBackbtn is clicked an emoji is added to the back of the localStorage array. This aspect of the app is working as it should.
The focus of my question is on removeFront() function which removes the index item from the array shift(), and removeEnd() function which removes the last item from array. Both functions are working, but is the syntax used ideal when managing - updating the state and removing items from localStorage?

import {React, useState} from 'react';

function App() {

  const [, setEmjoiArr] = useState([])
  const [inputValue, setInputValue] = useState({ value: ""})

 // set localStorage key
  const LOCAL_VALUE = "emojis";

  //getLocal() is a utility function which retrieves from localStorage
  // or returns the default array if nothing is in localStorage, and parse the JSON
  const getLocal = (key) => {
     return JSON.parse(localStorage.getItem(key) || "[]");
  }

  // setLocal() is a utility function that passes a key and value which the key can later be used to
  // to retrieve value(s) from localStorage
  const setLocal = (key, value) => {
     localStorage.setItem(key, JSON.stringify(value));
  }

  // EmjoiValues retrieves localStorage using the key declared above "LOCAL_VALUE"
  const EmjoiValues = getLocal(LOCAL_VALUE)

  // passes all EmjoiValues items from localStorage and includes new value from input field
  // then assigns to updateEmjoiArr
  let updateEmjoiArr = []

  // console.log(EmjoiValues)

  const pushFrontBtn = () => {
    setEmjoiArr((prev) => [inputValue.value, ...prev])

    //updateEmjoiArr so that new items will be add at beginning of array
    updateEmjoiArr = [inputValue.value, ...EmjoiValues]
    setLocal(LOCAL_VALUE, updateEmjoiArr)

    setInputValue({value: ""})
  }

  const pushBackBtn = () => {
    setEmjoiArr((prev) => [...prev, inputValue.value])

    //updateEmjoiArr so that new items will be add at end of array
    updateEmjoiArr = [...EmjoiValues, inputValue.value]
    setLocal(LOCAL_VALUE, updateEmjoiArr)

    setInputValue({ value: "" })
  }

  const removeFront = () => {
//IS THIS SNYTAX CORRECT FOR REMOVING FIRST ITEM FROM ARRAY LOCALSTORAGE?
   let [first,...rest] = EmjoiValues

   setEmjoiArr((prev) => [...prev, rest])
   setLocal(LOCAL_VALUE, rest)
  }

  const removeEnd = () => {
   //IS THIS SNYTAX CORRECT FOR REMOVING LAST ITEM FROM ARRAY LOCALSTORAGE?
   EmjoiValues.splice(-1, 1)

   setEmjoiArr((prev) => [...prev, EmjoiValues])
   updateEmjoiArr = [EmjoiValues]
  setLocal(LOCAL_VALUE, updateEmjoiArr)

  }

  const handleChange = event => {
    const {name, value} = event.target;
    setInputValue(prev => {
      return {
        ...prev,
        [name]: value
      }
    })
  }

   const emojiItems = EmjoiValues.map((emoji) => {
     return
{emoji}

   })

  return (

{emojiItems}

      <input
        className="emjoi-input"
        name="value"
        type="text"
        value={inputValue.value}
        onChange={handleChange}
      />

        <button className="push-front-btn" onClick={pushFrontBtn}>
          Add Emoji to Front
        </button>
        <button className="push-back-btn" onClick={pushBackBtn}>
          Add Emoji to End
        </button>

        <button className="shift-btn" onClick={removeFront}>
          Remove Front Emoji
        </button>
        <button className="pop-btn" onClick={removeEnd}>
          Remove End Emoji
        </button>

  )
}

export default App;```

A: sorry, I missundertand your question:

  const removeFront = () => {
   let [first,...rest] = EmjoiValues
   setEmjoiArr(rest)
   setLocal(LOCAL_VALUE, rest)
  }

  const removeEnd = () => {
   EmjoiValues.splice(-1, 1)
   setEmjoiArr(EmjoiValues)
   setLocal(LOCAL_VALUE, EmjoiValues)
  }

A: setLocal is setting an empty value in the case that you are trying to remove.
and that key will live cross sessions, if you want to remove it use
localStorage.removeItem('name');


text:
Q: Broken graphics after upgrading to 20.04 I have just upgraded to Ubuntu MATE 20.04 (from version 18) and my graphics are broken. I think it might be the composer's fault, since I saw Compton was uninstalled. How could I fix this?
Screenshot of my desktop after upgrading:

The output of lspci -k | grep -EA3 'VGA|3D|Display' is the following:
02:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/-ATI] Picasso (rev c4)
Subsystem: ASUSTeK Computer Inc. Picasso
Kernel driver in use: amdgpu
Kernel modules: amdgpu

A: As I was suspecting, the compositing windows manager was the culprit. I disabled it in Window Preferences> General and everything now works flawlessly.


text:
Q: What am I doing wrong that I can't get JQuery to read my xml file into a DDL? Trying to load data into a drop down list when a user selects one of two radio buttons. the bookGenres.xml file is in the same directory as my script. I'm out of ideas.
XML:
<?xml version="1.0" encoding="utf-8" ?>
<Genres>
  <Fiction>
    <book>Sci-Fi</book>
    <book>Fantasy</book>
    <book>Horror</book>
    <book>Romance</book>
    <book>Detective</book>
  </Fiction>
  <NonFiction>
    <book>Autobiography</book>
    <book>Philosophy</book>
    <book>Cooking</book>
    <book>Historic</book>
    <book>Teaching</book>
  </NonFiction>
</Genres>

JQuery:
$('#rblGenre').click( function() {
        $('#ddlSpecificGenre > option').remove();

        $.ajax({
            type: 'GET',
            url: 'bookGenres.xml',
            dataType: 'xml',
            success: function( xml ) {
                $(xml).find( $(this).val() ).each( function() {
                    var subgenre = $(this).find('book').text();
                    $('#ddlSpecificGenre').append( "<option>" + subgenre + "</option>" );
                });
            },
            error: function() { alert( "WTF" ); }
        });
    });

A: Justen,
The most likely issue is that the bookgenres.xml might be in the same folder as the script, but is it in the same folder that the html page is that the jQuery is getting renered on?


text:
Q: For Loop outputting duplicate XML value I am writing new xml data from the xml file I am reading via simple_load_function(). My outputted 'submitterId' and 'pid' values are being duplicated. 'Headline' value is OK.
I think the problem lies within the loop. Can someone explain/assist why this is happening? Here is a working demo where you can see the output.
XML FILE: stack-test.xml
<?xml version="1.0" encoding="utf-8"?>
<ContentEnvelope>
  <ContentBody>

    <Review>
      <Headline>Great product</Headline>
      <ReviewedBy>
         <UniqueId>der_11111111</UniqueId>
      </ReviewedBy>
      <ReviewedKey>
         <Key>cover_creme</Key>
      </ReviewedKey>
    </Review>

    <Review>
      <Headline>Worst product</Headline>
      <ReviewedBy>
         <UniqueId>der_88888888</UniqueId>
      </ReviewedBy>
      <ReviewedKey>
         <Key>setting_powder</Key>
      </ReviewedKey>
    </Review>

  </ContentBody>
</ContentEnvelope>

CODE:
error_reporting(0);

$devices = array();
$xml = simplexml_load_file('stack-test.xml');

//// Loops through xml to <Headline> tag ////

foreach($xml->ContentBody->Review as $item){
   $device = array();

   foreach($item as $key => $value){
     $device[(string)$key] = (string)$value;
   }
   $devices[] = $device;
}
$devices2 = array();

//// Loops through xml to <ReviewedBy> tag ////

foreach($xml->ContentBody->Review->ReviewedBy as $item2) {
    $device2 = array();

    foreach($item2[1] as $key2 => $value2){
        $device2[(string)$key2] = (string)$value2;
    }
    $devices2[] = $device2;
}
$devices3 = array();

//// Loop through xml to <ReviewedKey> tag ////

foreach($xml->ContentBody->Review->ReviewedKey as $item3) {
    $device3 = array();

    foreach($item3 as $key3 => $value3){
        $device3[(string)$key3] = (string)$value3;
    }
   $devices3[] = $device3;
}

//HEADLINE
foreach($devices as $key => $val){
    $headline = $val[Headline];

    //UNIQUE ID
    foreach($devices2 as $key => $val){
        $uniqueId = $val[UniqueId];
    }

    //KEY
    foreach($devices3 as $key => $val){
        $reviewedKey = $val[Key];
    }

    //// Writes Headline DATA /////

    $location_xml=new XMLWriter();
    $location_xml->openMemory();

    $location_xml->startElement("object-attribute");
    $location_xml->writeAttribute("attribute-id", "headline");
    $location_xml->text($headline);
    $location_xml->endElement();
    echo $location_xml->outputMemory(true);

    //// Writes Unique ID DATA ////

    $uniqueId_xml=new XMLWriter();
    $uniqueId_xml->openMemory();

    $uniqueId_xml->startElement("object-attribute");
    $uniqueId_xml->writeAttribute("attribute-id", "submitterId");
    $uniqueId_xml->text($uniqueId);
    $uniqueId_xml->endElement();
    echo $uniqueId_xml->outputMemory(true);

    //// Writes Key DATA ////

    $reviewedKey_xml=new XMLWriter();
    $reviewedKey_xml->openMemory();

    $reviewedKey_xml->startElement("object-attribute");
    $reviewedKey_xml->writeAttribute("attribute-id", "pid");
    $reviewedKey_xml->text($reviewedKey);
    $reviewedKey_xml->endElement();
    echo $reviewedKey_xml->outputMemory(true);
 }//// Closes loop ////

//// OUTPUT: submitterId and pid values are duplicated!!!! ////
<object-attribute attribute-id="headline">Great product</object-attribute>
<object-attribute attribute-id="submitterId">der_11111111</object-attribute
<object-attribute attribute-id="pid">cover_creme</object-attribute>

<object-attribute attribute-id="headline">Worst product</object-attribute>
<object-attribute attribute-id="submitterId">der_11111111</object-attribute>
<object-attribute attribute-id="pid">cover_creme</object-attribute>

A: Finally figured this one out. After picking apart my loops I realized that I was not correctly generating the XML because the code that writes the XML were not in the correct loops. This is the solution below. Here is a working demo.
foreach($xml->ContentBody->Review as $item){
    foreach($item->Headline as $item2){

        ///////// Writes Headline DATA //////////
        $location_xml=new XMLWriter();
        $location_xml->openMemory();
        $location_xml->startElement("object-attribute");
        $location_xml->writeAttribute("attribute-id", "headline");
        $location_xml->text($item2);
        $location_xml->endElement();
        echo $location_xml->outputMemory(true);
    }

    foreach($item->ReviewedBy as $item2) {
        foreach($item2 as $key2 => $value2){
            if($key2=='UniqueId'){

                ///////// Writes Submitter ID DATA //////////
                $uniqueId_xml=new XMLWriter();
                $uniqueId_xml->openMemory();
                $uniqueId_xml->startElement("object-attribute");
                $uniqueId_xml->writeAttribute("attribute-id", "submitterId");
                $uniqueId_xml->text($value2);
                $uniqueId_xml->endElement();
                echo $uniqueId_xml->outputMemory(true);
            }
        }
    }

    foreach($item->ReviewedKey as $pid) {
        foreach($pid as $key2 => $value3){
            if($key2=='Key'){

                ///////// Writes Product ID DATA //////////
                $reviewedKey_xml=new XMLWriter();
                $reviewedKey_xml->openMemory();
                $reviewedKey_xml->startElement("object-attribute");
                $reviewedKey_xml->writeAttribute("attribute-id", "pid");
                $reviewedKey_xml->text($value3);
                $reviewedKey_xml->endElement();
                echo $reviewedKey_xml->outputMemory(true);
            }
        }
    }
}


text:
Q: JSON Token won't load the value after being verified Once I get to the verify_token function it keeps executing the except statement instead of returning the value in 'id_user' and I'm not sure why. I am using these libraries. flask-login, sqlalchemy, itsdangerous for jsonwebserializer, and wtforms.
Functions
def get_reset_token(user):
    serial = Serializer(app.config['SECRET_KEY'], expires_in=900) # 15 mins in seconds
    return serial.dumps({'id_user':user.id}).decode('utf-8')

def verify_token(token):
    serial = Serializer(app.config['SECRET_KEY'])
    try:
        user_id = serial.load(token)['id_user']
    except:
        return None
    return Users.query.get('id_user')

def send_mail(user):
    token = get_reset_token(user)
    message = Message('Password Reset Request', recipients = [user.email], sender='noreply@gmail.com')
    message.body= f'''
To Reset your password, click the following link:

{url_for('reset_token', token = token, _external = True)}

If you did not send this email, please ignore this message.
'''
    mail.send(message)

ROUTES
@app.route('/password_reset', methods = ['GET', 'POST'])
def password_reset():
    form = Password_request()
    if request.method == "POST":
        if form.validate_on_submit:
            user = Users.query.filter_by(email = form.email.data).first()
            send_mail(user)
            flash('Check your email. Password change request has been sent')
            return redirect(url_for('login'))
        else:
            flash('Your email was not linked to an account')
    return render_template('password_reset.html', form = form)

@app.route('/password_reset/<token>', methods = ['GET', 'POST'])
def reset_token(token):
    user = verify_token(token)
    if user == None:
        flash('The token is invalid or expired')
        return redirect(url_for('password_reset'))

    form = Password_success()
    if form.validate_on_submit:
        hashed_password=generate_password_hash(form.password.data, method = 'sha256')
        user.password = hashed_password
        db.session.commit()
        flash('Your password has been updated!')
    return redirect(url_for('signup'))

A: def verify_token(token):
    serial = Serializer(app.config['SECRET_KEY'])
    try:
        user_id = serial.load(token)['id_user']
    except:
        return None
    return Users.query.get('id_user') # this looks wrong

Shouldn't the last line of verify_token be return Users.query.get(user_id)? You're assigning the value of the token to that variable , then ignoring it and telling SQLAlchemy to find a record with the ID of the string value 'id_user' which I doubt is what you're intending to do.
def verify_token(token):
    serial = Serializer(app.config['SECRET_KEY'])
    try:
        user_id = serial.load(token)['id_user']
    except:
        return None
    return Users.query.get(user_id) # What happens when you change this?


text:
Q: Pegar os dados de uma coluna em uma view e inserir em uma tabela boa noite, estou com um problema, quero pegar os dados de uma coluna em uma View que criei e colocar esses dados em uma coluna de uma tabela, segue a baixo o código que usei para criar a View, já estou a duas semanas tentando resolver isso mas não tem jeito.
create view bolsa
as
select
nome as nome,
case
when LEFT(nome,1) = '*' then
'bolsa'
when RIGHT(nome,2) = '**' then
'inclusao'
end as class
from tbl_user
estou usando o mysql workbench 6.3

A: Vou exemplificar com base somente nas informações que você colocou na pergunta. Vamos lá:
Para fazer o que você deseja, se não tiver faltando nenhuma informação, é teoricamente simples. Segue um exemplo de como fazer:
INSERT INTO nome_da_tabela (nome_da_coluna)
SELECT nome_do_campo_da_view FROM nome_da_view;

Observe que na primeira linha está um insert para a coluna da referida tabela. Na segunda linha, também de forma simples, está um select buscando o nome da coluna da View a qual você quer inserir na tabela.
Caso você queira, pode colocar alguma condição no Select com o objetivo de filtrar o resultado e inserir somente o que lhe interessa na tabela.
Como disse anteriormente, seria interessante você colocar mais informações, como por exemplo, a SQL das tabelas e views envolvidas na questão.
Se ainda ficar alguma dúvida é só dizer que respondo logo em seguida.
Grande abraço.


text:
Q: Too many FTP connections, can't accept more I got the following error message:

Warning: ftp_login(): I can't accept more than 6 connections as the same user in C:\xampp\htdocs\test\ftp_sync.php on line 58

My code which causes the error:
function newStream($i){
        $conId = ftp_connect($this->ftpServer);

        // login with username and password
        $login_result = ftp_login($conId, $this->ftpUsername, $this->ftpPassword);//line 58
        // /home/content/61/10367861/html/

        // turn passive mode on
        ftp_pasv($conId, true);

        $this->conIds[$i]=$conId;
        $this->localFiles[$i]='';
        $this->conStats[$i]=FTP_FAILED;//initial value
    }

Does anyone probably know what this error message means?

A: This error is thrown because your server restricts the maximum number of connections per user / IP address. The errors the most people encounter look mostly like this:

421 I can't accept more than [0-9]+ connections as the same user

421 Too many connections ([0-9]+) from this IP

The FTP error code which is mostly used for this kind of error is 421. Which is defined in RFC 959 (FTP) as:

421 Service not available, closing control connection. This may be a
reply to any command if the service knows it must shut down.

You have now exactly two possible solutions to solve this problem:

*

*Reduce the amount of connections made by your program.

*Increase the amount of allowed FTP connections to your server.

If the allowed maximum is beneath 3, then you should first try to change the config file on your server, because the most programs need at least 3, sometimes 2.

*

*Reducing the amount of connections

When facing the problem within a program: Some FTP clients allow the user to change the amount of used connections in the settings. They are mostly using about 3 connections at the same time, 2 to increase the performance, 1 to enable browsing while the user is performing other tasks. You can decrease the amount without losing any important functionality to 2 or even to 1, if you don't bother about browsing while performing other tasks. (FileZilla for example allow this.)
When facing the problem within your own code: Reduce the amount of tasks which are performed concurrently. Check also if your code is closing the connections the right way, also when errors are thrown. It should always be closed, no matter what happens. In PHP you could use try-catch-blocks, inside a class you could put the code for closing the connection into the __destruct method.

*Increase the amount of allowed connections

This depends on what kind of FTP server you are using. In PureFTP (used by the most UNIX systems) you need to change the MaxClientsPerIP setting in /etc/pure-ftpd.conf. The default amount set by the default configuration file or by the most administrators at hosting companies is somewhere about 5-15. Increase the value until it fits your needs. Be aware that theoretically a proxy server which is somewhere between the most users and the FTP server could cause trouble, because the most connection will then use the same IP address.

In your special case: As Mave mentioned, you aren't closing the connections in your code. This could easily cause multiple connections being active, especially if you are running the code in a short period of time multiple times. So, in your specific case would adding ftp_close($conId); fix the problem. (Use also a try-catch-block.)


text:
Q: Place bibliography before Appendix when using natbib I have the following document.
---
title: "What comes after the bibliography?"
bibliography: refs.bib
header-includes:
  - \usepackage{natbib}
  - \setcitestyle{numbers}
  - \setcitestyle{square}
output:
  pdf_document:
    citation_package: natbib
    latex_engine: lualatex
    keep_tex: yes
---

# A

This document may use knitr[@pKnitr].

# References

# Appendix

`1+1` evaluates in R to `r 1+1` (for more information, see [@pRmarkdown])

I used citation() to create the bibtex references in refs.bib.
@InCollection{pKnitr,
  booktitle = {{Implementing Reproducible Computational Research}},
  editor = {Victoria Stodden and Friedrich Leisch and Roger D. Peng},
  title = {knitr: A Comprehensive Tool for Reproducible Research in {R}},
  author = {Yihui Xie},
  publisher = {Chapman and Hall/CRC},
  year = {2014},
  note = {ISBN 978-1466561595},
  url = {http://www.crcpress.com/product/isbn/9781466561595}
}

@Book{pRmarkdown,
  title = {{R Markdown Cookbook}},
  author = {Yihui Xie and Christophe Dervieux and Emily Riederer},
  publisher = {Chapman and Hall/CRC},
  address = {Boca Raton, Florida},
  year = {2020},
  note = {ISBN 9780367563837},
  url = {https://bookdown.org/yihui/rmarkdown-cookbook}
}

I want to place my bibliography before the Appendix. So far I've tried the following, unfortunately with no luck.

*

*Add

 (see example above)

*Using \AtEndDocument{} - its contents won't transpile to LaTeX

*\printbibliography does not work with natbib

*\bibliography{refs} kinda works, but I have to manually delete the bibliography macro created by md / Rmd

For the last point, if I have the following in my Rmd file...

# References

\bibliography{refs}

# Appendix

`1+1` evaluates in R to `r 1+1` (for more information, see [@pRmarkdown])

... it produces the following LaTeX file.
% ...
\section{A}\label{a}}

This document may use knitr\citep{pKnitr}.

\hypertarget{references}{%
\section{References}\label{references}}

\bibliography{refs.bib}

\hypertarget{appendix}{%
\section{Appendix}\label{appendix}}

\texttt{1+1} evaluates in R to 2 (for more information, see
\citep{pRmarkdown})

  \bibliography{refs.bib}

\end{document}

So \bibliography{refs.bib} is now added twice, causing a Citations multiply defined error.
How can I add the bibliography before my Appendix using natbib?

A: If you use remove all the interference from markdown, you are more flexible with the placement of the bibliography:
---
title: "What comes after the bibliography?"
header-includes:
  - \usepackage{natbib}
  - \bibliographystyle{plainnat}
  - \setcitestyle{numbers}
  - \setcitestyle{square}
output:
  pdf_document:
    latex_engine: lualatex
    keep_tex: yes
---

# A

This document may use knitr \cite{pKnitr}.

\bibliography{refs}

# Appendix

`1+1` evaluates in R to `r 1+1` (for more information, see \cite{pRmarkdown})


text:
Q: How to format columns in laravel excel if i don't know the column letter We are exporting an excel from a blade, the problem is that we perform a foreach cycle that renders a subtraction between two numbers. However when exporting they are as if they were string. All the examples that I find on the internet, involve knowing the column to be formatted, but as it is a range of dates it is impossible for me to know it beforehand.

A: **Create headings in your file export**
public function headings(): array
    {
        return [
            'Id',
            'Name',
            'Unit',
            'Status',
            'Price',
            'Date'
        ];
   }

**Documentation:**
https://docs.laravel-excel.com/3.1/exports/column-formatting.html


text:
Q: Determinar todos los múltiplos de un número en Python Empiezo en la programación con Python hace solo unos días y pues quiero desarrollar un programa para un problema sencillo. Básicamente debo leer un número de tres dígitos y determinar qué dígitos son múltiplos de otros dígitos, actualmente tengo desarrollado ya un programa y realiza todo como se le ordena, pero solo puede mostrar si uno de los dígitos es múltiplo de otro, pero no todos los dígitos múltiplos de otros.
Así, por ejemplo, si ingreso el 248 según el código me dirá que el 8 es múltiplo de 4 y finalizará, pero el 8 también es múltiplo de 2 y esto no lo imprimirá. ¿Hay algún modo de poder imprimir todos los posibles múltiplos que los dígitos puedan tener?
Otra cosa es que en el ejercicio no se me permite usar estructuras de ciclos o listas, si se puede realizar sin utilizar estas estructuras estaría agradecido, pero igual no hay problema si es necesario utilizarlas.

from math import log10
from math import ceil
Num=abs(int(input('Digite un número entero de tres dígitos')))
if Num==0 or Num==1:
    print('El número ingresado no tiene tres dígitos \a')
else:
    Num_Dig=ceil(log10(Num))
    if Num_Dig!=3:
        print('El número ingresado no tiene tres dígitos \a')
    else:
        Dig_1=Num%10
        Dig_2=(Num%100)//10
        Dig_3=(Num//100)
        if Dig_1%Dig_2==0:
            print(f'El dígito {Dig_1} es multiplo de {Dig_2}')
        elif Dig_1%Dig_3==0:
            print(f'El dígito {Dig_1} es multiplo de {Dig_3}')
        elif Dig_2%Dig_1==0:
            print(f'El dígito {Dig_2} es multiplo de {Dig_1}')
        elif Dig_2%Dig_3==0:
            print(f'El dígito {Dig_2} es multiplo de {Dig_3}')
        elif Dig_3%Dig_1==0:
            print(f'El dígito {Dig_3} es multiplo de {Dig_1}')
        else:
            print(f'Ningún dígito en el número {Num} es multiplo de otro')

A: Tienes un problema en la lógica de tu código, ya que estas realizando comprobaciones excluyentes,es decir, al utiliza elif si alguna de las comprobaciones es cierta no realizará las demás. Lo que debes hacer es realizar todas las comprobaciones una tras otra ya que no puedes usar bucles ni listas.
Te dejo un ejemplo funcionando:
from math import log10
from math import ceil
Num=abs(int(input('Digite un número entero de tres dígitos')))
if Num==0 or Num==1:
    print('El número ingresado no tiene tres dígitos \a')
else:
    Num_Dig=ceil(log10(Num))
    if Num_Dig!=3:
        print('El número ingresado no tiene tres dígitos \a')
    else:
        Dig_1=Num%10
        Dig_2=(Num%100)//10
        Dig_3=(Num//100)
        ninguno = True
        if Dig_1%Dig_2==0:
            print(f'El dígito {Dig_1} es multiplo de {Dig_2}')
            ninguno = False
        if Dig_1%Dig_3==0:
            print(f'El dígito {Dig_1} es multiplo de {Dig_3}')
            ninguno = False
        if Dig_2%Dig_1==0:
            print(f'El dígito {Dig_2} es multiplo de {Dig_1}')
            ninguno = False
        if Dig_2%Dig_3==0:
            print(f'El dígito {Dig_2} es multiplo de {Dig_3}')
            ninguno = False
        if Dig_3%Dig_1==0:
            print(f'El dígito {Dig_3} es multiplo de {Dig_1}')
            ninguno = False
        if ninguno:
            print(f'Ningún dígito en el número {Num} es multiplo de otro')

Espero que te sirva, cualquier duda pregunta en los comentarios.
Un saludo


text:
Q: how to convert sql to linq using ef4
iam trying to convert this sql to linq but could not
select s.IdSimcard ,s.Imei from dbo.SimCard s
where s.Imei  not in (select distinct d.Imei  from dbo.SimCard d  inner join dbo.Configuracion c
on c.SinCard_IdSincard = d.IdSimcard
where c.Estado = 'Activo' )

So far I have this with the help of linqpad, I cant use linquer anymore for the activation code
(from s in SimCard where  s.Imei.Contains( (from c in Configuracion
                             join d in SimCard on c.SinCard_IdSincard equals d.IdSimcard
                             where c.Estado == "Activo"
                             select new { d.Imei }).Distinct())
                             select new {  s.IdSimcard, s.Imei })

I have read "Not in" dont supported in EF4, what woul be the equivalent?
i get this error in linqpad
'string.Contains(string)'
  - Argument 1: cant convert de 'System.Linq.IQueryable' to 'string'

A: If I understand your question, you can use the Except(...) Extension method (in the System.Linq namespace) instead of Not Contains(...).


text:
Q: Light illumination method for video camera and CV detection My control application implements human face detection and recognition with using of CV library. My device uses usual VGA USB video camera.
Problem:

*

*Good and uniform light illumination allows detect and recognize face successfully.

*Poor and uniform light (semidarkness), also allows detect and recognize face successfully.

*Side lighting makes it difficult for detection

I've tried to create  haar cascade xml of half-lit faces and even use haar cascade of human face profile, but in both cases I have same result, detection can not manage this data correctly. The first way provides multiple extra detection of similar shadow relief, because half-lit face is too amorphous when moving and it is very difficult to determine appropriate data for it. Profile of the human face does not gives any results, except of detection of profile, for what it is intended, also with good illumination, but of course can not be detected as a half-lit face.
Recognition process itself not involved in the problem, because with detection I can process any object if it is matches example. In this question, I need to solve the problem of facilitating the camera to get a good quality video image with uniform light for successful detection.
I'm not sure, how it work with other devices or methods, but my phone with Android, Windows phone and iPhone all has a same problem with detection of half-lit face.
I've tried attache some kind of light source to my device to provide good direct light, but two problems arise, first, even if it is soft, not a very bright light, it is still directed to the eyes, what causes discomfort, and also getting of external light into the field of view causes overexposure, what affects detection even more than the lack of light.
Any advice about proper approach to this problem, for example, some suitable device, method, light source, maybe possibility of infrared light with CV etc., would be very helpful


text:
Q: how to extract 2 characters from a string am in a confusion of extracting sub string  fro a given string according to the following algorithm,
Algorithm
every input string is of the format: 3nm , 4gn , 77jk so on..(ie., a string followed by a number)
now what i need is that extract the alphabet from the string..
example
input: 77nm
output : nm
my contribution:
Private Function getbyte(s As String, ByVal place As Integer) As String
   If place < Len(s) Then
      place = place + 1
      getbyte = Mid(s, place, 1)
   Else
      getbyte = ""
   End If
End Function

but it will not solve my problem as it returns number as well as digits

A: You can use LINQ to extract only letters:
Dim input As String = "3nm , 4gn , 77jk"
Dim output As String = New String((From c As Char In input Select c Where Char.IsLetter(c)).ToArray())

Result:

nmgnjk

You can also encapsulate the LINQ into an extension method.
<Extension()>
Public Module Extensions

    <Extension()>
    Public Function Extract(input As String, predicate As Predicate(Of Char)) As String
        Return New String((From c As Char In input Select c Where predicate.Invoke(c)).ToArray())
    End Function

End Module

Usage
output = input.Extract(Function(c As Char) Char.IsLetter(c))


text:
Q: Visual studio 2010 database explorer sql query clears table I've created a database in visual studio 2010 in the following way: Data->Add new datasource->Database->Entity Data Model.
Now, in my wpf app I can load and save data successfully, when closing the
app and opening again the data will still be there, but as soon as I try
retrieve the table data in Visual Studio's Database explorer it returns
an empty table, and running the application after that also returns no data.
It is as if using database explore to query data clears it.
Any help would be greatly appreciated.

A: Tim Anderson seem to explain what is going on, here:
http://www.itwriting.com/blog/689-where-is-your-sql-server-ce-database.html


text:
Q: Struts2 i18n java properties, how to show special character? If any body else have solution on this please replay.
I'm using Struts2 and getText method to fill i18n and text tags.
For example I use:
free.text.search.label=&#269eské On-line Hledat

&#269 is a HTML code for special character č (Czech Republic). I want to use in properties file.
But in my JSP, I get : &#269eské On-line Hledat instead of české On-line Hledat
I use this to display text on my JSP:
<s:label for="searchInput" value="%{getText('free.text.search.label')}" />

So what's the error? Actually this problem i am facing for label as well for button.

A: Use \u010D instead of &#269
.properties
free.text.search.label=\u010Deské On-line Hledat

.jsp
<s:label key="free.text.search.label" />

Output
české On-line Hledat

How I solved it?
    Just paste české On-line Hledat into .properties file in my IDE (Eclipse).
Or

See
Unicode Character 'LATIN SMALL LETTER C WITH CARON'
(Encodings > C/C++/Java source code)
A to Z Index of Unicode Characters
Unicode Character Search

A: Well i am not able to understand your issue properly
but few points i would like to mention here
<s:label for="searchInput" value="%{getText('free.text.search.label')}" />

use key in place of this to make this more easy to read and maintain
like
<s:label for="searchInput" key="free.text.search.label" />

also since meta tags are no longer applicable to struts2 so you can try using this
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

May be this will help you to display special characters correctly


text:
Q: Uncaught ReferenceError: '' is not defined Using: VS'12, asp.net MVC4 Internet Application, MVC, EF Code First + Kendo UI
Error
Uncaught ReferenceError: filterCountys is not defined
(anonymous function)

However It is defined ... ???

I'm unsure if it makes a difference but this code is in a PartialView called from an Ajax Script

A: Try putting the scripts back to the main View, they must be on your Index View( the Main View ) not the Partial View. This is why there not showing up correctly.
I'm not certain for the reason but if i'd guess. Your partial either isn't loading in the scripts or they must be available from the Main / Index View.


text:
Q: Why $dz\wedge d\bar{z} = d|z|\wedge d\phi$ for $z \in \mathbb{C}$? Let $z \in \mathbb{C}$ and $\bar{z}$ its complex conjugate. Then, a Kahler form can be written as $k = dz \wedge d\bar{z}$. If we re-write $z=|z|e^{i\phi}$ how do we get that
$$dz\wedge d\bar{z} = d|z|\wedge d\phi$$
or what is the correct answer? I have some handwritten notes here but I cannot understand why this is.

A: There are three (standard?) coordinate on $\mathbb C$, the complex one ($z$), the real one $z = x+iy$ and the polar one $(r, \phi)$,
The standard Kahler form is $dx\wedge dy$. Which is the same as $\frac{i}{2} dz \wedge d\bar z$ as
\begin{equation}
\begin{split}
\frac{i}{2} dz\wedge d\bar z &= \frac i2 d(x+ i y) \wedge d(x - iy)\\
&= \frac i2 (dx + idy) \wedge (dx - idy) \\
&= \frac i2 (-idx \wedge dy + i dy \wedge dx) \\
&= \frac 12 (dx \wedge dy + dx \wedge dy)\\
&= dx \wedge dy.
\end{split}
\end{equation}
On the other hand, if we use polar coordinate $(r, \phi)$, then $r^2 =x^2 + y^2 $ and $\phi = \tan^{-1}\frac yx$.
Thus
\begin{equation}
\begin{split}
rdr \wedge d\phi &= \frac 12 d(r^2) \wedge d \left(\tan^{-1}\frac yx\right) \\
&=\frac 12 d(x^2 + y^2) \wedge d \left(\tan^{-1}\frac yx\right) \\
&= \frac 12 (2xdx + 2ydy)  \wedge \left( \frac{-y dx}{x^2+ y^2} +\frac{x dy}{x^2+ y^2}\right)\\
&= dx \wedge dy.
\end{split}
\end{equation}


text:
Q: bracket's not in the right place? i can't get the brackets right it is driving me crazy,
j = a variable i tried some but I cannot get it working I searched on the internet for it aswell. but there's is not a good tutorial on how to do those "" and ''.
kalender += "" + j;

A: kalender += ""+j;

If you are having a hard time figuring out how to concatenate strings with variables, I would first type the string without the variables. Then place the variables in after.
kalender += "";

then
kalender += ""+j;


text:
Q: Неблокирующий обработчик в node.js Я знаю что на эту тему не однократно создавались статьи и туториалы. И все же. Почему этот код может обрабатывать запросы только последовательно не смотря на то, что он построен с использованием setImmediate:
var http = require('http'),
replicate,
fileServer;

replicate = function (symbol, count) {
    var str = "",
        i;

    for (i = 0; i <= count; i += 1) {
        str += symbol;
    }

    return str;
};

fileServer = function (response) {
    var Klength = 1024, i = 0;

    response.writeHead(200, {
        'Content-Type': 'text/plain',
        'Content-Length': 1024 * Klength
    });

    setImmediate(function f() {
        for (; i < Klength; i += 1) {
            response.write(replicate('A', 5));
            setImmediate(f);
            return;
        }

        response.end();
    });
};

http.createServer(function (request, response) {
    if (request.url === '/favicon.ico') {
         response.writeHead(404);
         response.end();
         return;
    }

    fileServer(response);
}).listen(8000);

Та же проблема и при такой реализации:
fileServer = function (response) {
    var Klength = 1024 * 1024,
        i = 0,
        emiter;

    response.writeHead(200, {
        'Content-Type': 'text/plain',
        'Content-Length': Klength
    });

    emiter = new events.EventEmitter();

    emiter.addListener('continue', function () {
        if (i <= Klength) {
            response.write('A');
            i += 1;

            setImmediate(function () { emiter.emit('continue'); });
            return;
        }

        response.end();
    });

    emiter.emit('continue');
};

A: Длинные вычисления надо выносить в отдельный процесс. если у вас выполняется js-код без обращения к I/O, то будет блокировка. т.е. функция должна завершить свое выполнение, а у вас просто вызов друг из друга происходит. setImmediate просто модифицирует очередь вызовов, но на i/o она не прерывается и должна выполниться вся.


text:
Q: Probability, tunnelling and transmission ratio This question is about tunnelling. It is from Physics for the IB diploma book.
The question introduces this graphWhere it is said the graph does not take reflected electrons into account and that the values on the vertical axis are arbitrary.
The author asks about the width of the barrier then asks about the ratio of the kinetic energy of electrons after tunnelling to the kinetic energy before tunnelling. Those are found to be respectively w=1.5 X 10^-10 m. However, the ratio is 1 since the deBroglie wavelength is the same before and after.
After this the author asks about the fraction of the incident electrons that tunnel through the barrier. The way I thought about this is use probability of transmitted electrons to those incident. That would be then p=1.3^2/2^2. But the author got (3/20)^2. Can someone explain the author's result? Thank you.

A: The vertical axis is simply mislabeled.  The numbers from top to bottom should read 2, 1, -1, -2 (with 0 implied at the thicker horizontal line), instead of 2, 2, -1, -2.  So the peak of the wave on the right-hand side is only at 0.3, instead of 1.3.
You surely know that $0.3/2.0 = 3/20$, but I wonder if the author decided that counting the boxes on the graph paper would be easier.  The smaller peak is 3 boxes above the horizontal axis, while the larger peaks are 20 boxes above it.  Anyway, the result is the same.


text:
Q: is volatile of no use on x86 processors I read somewhere that x86 processors have cache coherency and can sync the value of fields across multiple cores anyway on each write.
Does that mean that we can code without using the 'volatile' keywoard in java if we plan on running only on x86 processors?
Update:
Ok assuming that we leave out the issue of instruction reordering, can we assume that the issue of an assignment to a non-volatile field not being visible across cores is not present on x86 processors?

A: No -- the volatile keyword has more implications than just cache coherency; it also places restrictions on what the runtime can and can't do, like delaying constructor calls.

A: About your update: No we can't. Other threads could just read stale values without the variable being updated. And another problem: The JVM is allowed to optimize code as long as it can guarantuee that the single threaded behavior is correct.
That means that something like:
public boolean var = true;
private void test() {
    while (var) {
       // do something without changing var
    }
}

can be optimized by the JIT to while(true) if it wants to!

A: There is a big difference between can sync the value of fields and always syncs the value of fields. x86 can sync fields if you have volatile, otherwise it doesn't and shouldn't.
Note: volatile access can be 10-30x slower than non-volatile access which is a key reason it is not done all the time.
BTW: Do you know of any multi-core, plain x86 processors. I would have thought most were x64 with x86 support.

A: There are very exact specifications on how the JVM should behave for volatile and if it choose to do that using cpu-specific instructions then good for you.
The only place where you should say "we know that on this platform the cpu behaves like.." is when linking in native code where it needs to conform to the cpu.  In all other cases write to the specification.
Note that the volatile keyword is very important for writing robust code running on multiple cpu's each with their own cache, as it tells the JVM to disregard local cache and get the official value instead of a cached value from 5 minutes ago.  You generally want that.

A: a write in bytecode doesn't even have to cause a write in machine code. unless it's a volatile write.

A: I can vouch for volatile having some use. I've been in the situation where one thread has 'null' for a variable and another has the proper value for the variable that was set in that thread. It's not fun to debug. Use volatile for all shared fields :)


text:
Q: Nested recycler view, best approach of list inside list I have the following mock-up:

I spent some time thinking of a solution how should I implements this. As you can see there should be a scrollable list through the dates and every date should contain a grid of the items.
I think one recycler view should be enough, I don't really know how should I achieve the grid exactly but I will figure it out, the problem I don't know and don't understand is if I should use addView dynamically in onBindViewHolder or there is another better way, adding them in onBindViewHolder I don't think it's ok.
Thank you, any advice from people who made something similar is more than welcome.


text:
Q: What is the difference between view and view_as in PyTorch? I am building neural networks in Pytorch, I see view and view_as used interchangeably in various implementation what is the difference between them?

A: view and view_as are very similar with a slight difference. In view() the shape of the desired output tensor is to be passed in as the parameter, whereas in view_as() a tensor whose shape is to be mimicked is passed.
tensor.view_as(other) is equivalent to tensor.view(other.size())


text:
Q: Manually converting a string to an integer in Java I'm having string consisting of a sequence of digits (e.g. "1234").  How to return the String as an int without using Java's library functions like Integer.parseInt?
public class StringToInteger {
  public static void main(String [] args){
    int i = myStringToInteger("123");
    System.out.println("String decoded to number " + i);
  }

  public int myStringToInteger(String str){
      /* ... */
  }
}

A: If the standard libraries are disallowed, there are many approaches to solving this problem.  One way to think about this is as a recursive function:

*

*If n is less than 10, just convert it to the one-character string holding its digit.  For example, 3 becomes "3".

*If n is greater than 10, then use division and modulus to get the last digit of n and the number formed by excluding the last digit.  Recursively get a string for the first digits, then append the appropriate character for the last digit.  For example, if n is 137, you'd recursively compute "13" and tack on "7" to get "137".

You will need logic to special-case 0 and negative numbers, but otherwise this can be done fairly simply.
Since I suspect that this may be homework (and know for a fact that at some schools it is), I'll leave the actual conversion as an exercise to the reader. :-)
Hope this helps!

A: Use long instead of int in this case.
You need to check for overflows.
public static int StringtoNumber(String s) throws Exception{
    if (s == null || s.length() == 0)
        return 0;
    while(s.charAt(0) == ' '){
        s = s.substring(1);
    }
    boolean isNegative = s.charAt(0) == '-';
    if (s.charAt(0) == '-' || (s.charAt(0) == '+')){
        s = s.substring(1);
    }

    long result = 0l;
    for (int i = 0; i < s.length(); i++){
        int value = s.charAt(i) - '0';
        if (value >= 0 && value <= 9){
            if (!isNegative && 10 * result + value > Integer.MAX_VALUE ){
                throw new Exception();
            }else if (isNegative && -1 * 10 * result - value < Integer.MIN_VALUE){
                throw new Exception();
            }
            result = 10 * result + value;
        }else if (s.charAt(i) != ' '){
            return (int)result;
        }
    }
    return isNegative ? -1 * (int)result : (int)result;
}

A: And what is wrong with this?
int i = Integer.parseInt(str);

EDIT :
If you really need to do the conversion by hand, try this:
public static int myStringToInteger(String str) {
    int answer = 0, factor = 1;
    for (int i = str.length()-1; i >= 0; i--) {
        answer += (str.charAt(i) - '0') * factor;
        factor *= 10;
    }
    return answer;
}

The above will work fine for positive integers, if the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.

A: Alternate approach to the answer already posted here. You can traverse the string from the front and build the number
 public static void stringtoint(String s){
    boolean isNegative=false;
    int number =0;
    if (s.charAt(0)=='-') {
        isNegative=true;
    }else{
        number = number* 10 + s.charAt(0)-'0';
    }

    for (int i = 1; i < s.length(); i++) {

        number = number*10 + s.charAt(i)-'0';
    }
    if(isNegative){
        number = 0-number;
    }
    System.out.println(number);
}

A: Given the right hint, I think most people with a high school education can solve this own their own. Every one knows 134 = 100x1 + 10x3 + 1x4
The key part most people miss, is that if you do something like this in Java
 System.out.println('0'*1);//48

it will pick the decimal representation of character 0 in ascii chart and multiply it by 1.
In ascii table character 0 has a decimal representation of 48. So the above line will print 48. So if you do something like '1'-'0' That is same as 49-48. Since in ascii chart, characters 0-9 are continuous, so you can take any char from 0 to 9 and subtract 0 to get its integer value. Once you have the integer value for a character, then converting the whole string to int is straight forward.
Here is another one solution to the problem
String a = "-12512";
char[] chars = a.toCharArray();
boolean isNegative = (chars[0] == '-');
if (isNegative) {
    chars[0] = '0';
}

int multiplier = 1;
int total = 0;

for (int i = chars.length - 1; i >= 0; i--) {
    total = total + ((chars[i] - '0') * multiplier);
    multiplier = multiplier * 10;
}

if (isNegative) {
    total = total * -1;
}

A: Use this:
static int parseInt(String str) {
    char[] ch = str.trim().toCharArray();
    int len = ch.length;
    int value = 0;
    for (int i=0, j=(len-1); i<len; i++,j--) {
        int c = ch[i];
        if (c < 48 || c > 57) {
            throw new NumberFormatException("Not a number: "+str);
        }
        int n = c - 48;
        n *= Math.pow(10, j);
        value += n;
    }
    return value;
}

And by the way, you can handle the special case of negative integers, otherwise it will throw exception NumberFormatException.

A: You can do like this: from the string, create an array of characters for each element, keep the index saved, and multiply its ASCII value by the power of the actual reverse index. Sum the partial factors and you get it.
There is only a small cast to use Math.pow (since it returns a double), but you can avoid it by creating your own power function.
public static int StringToInt(String str){
    int res = 0;
    char [] chars = str.toCharArray();
    System.out.println(str.length());
    for (int i = str.length()-1, j=0; i>=0; i--, j++){
        int temp = chars[j]-48;
        int power = (int) Math.pow(10, i);
        res += temp*power;
        System.out.println(res);
    }
    return res;
}

A: Using Java 8 you can do the following:
public static int convert(String strNum)
{
   int result =strNum.chars().reduce(0, (a, b)->10*a +b-'0');
}

*

*Convert srtNum to char

*for each char (represented as 'b') -> 'b' -'0' will give the relative number

*sum all in a (initial value is 0)
(each time we perform an opertaion on a char do -> a=a*10

A: Make use of the fact that Java uses char and int in the same way. Basically, do char - '0' to get the int value of the char.
public class StringToInteger {
    public static void main(String[] args) {
        int i = myStringToInteger("123");
        System.out.println("String decoded to number " + i);
    }

    public static int myStringToInteger(String str) {
        int sum = 0;
        char[] array = str.toCharArray();
        int j = 0;
        for(int i = str.length() - 1 ; i >= 0 ; i--){
            sum += Math.pow(10, j)*(array[i]-'0');
            j++;
        }
        return sum;
    }
}

A: public int myStringToInteger(String str) throws NumberFormatException
{
    int decimalRadix = 10; //10 is the radix of the decimal system

    if (str == null) {
        throw new NumberFormatException("null");
    }

    int finalResult = 0;
    boolean isNegative = false;
    int index = 0, strLength = str.length();

    if (strLength > 0) {
        if (str.charAt(0) == '-') {
            isNegative = true;
            index++;
        }

        while (index < strLength) {

            if((Character.digit(str.charAt(index), decimalRadix)) != -1){
                finalResult *= decimalRadix;
                finalResult += (str.charAt(index) - '0');
            } else throw new NumberFormatException("for input string " + str);

            index++;
        }

    } else {
        throw new NumberFormatException("Empty numeric string");
    }

    if(isNegative){
        if(index > 1)
            return -finalResult;
        else
            throw new NumberFormatException("Only got -");
    }

    return finalResult;
}

Outcome:
1) For the input "34567" the final result would be: 34567
2) For the input "-4567" the final result would be: -4567
3) For the input "-" the final result would be: java.lang.NumberFormatException: Only got -
4) For the input "12ab45" the final result would be: java.lang.NumberFormatException: for input string 12ab45

A: public static int convertToInt(String input){
        char[] ch=input.toCharArray();
        int result=0;
        for(char c : ch){
            result=(result*10)+((int)c-(int)'0');
        }
        return result;
    }

A: Maybe this way will be a little bit faster:
public static int convertStringToInt(String num) {
     int result = 0;

     for (char c: num.toCharArray()) {
        c -= 48;
        if (c <= 9) {
            result = (result << 3) + (result << 1) + c;
        } else return -1;
    }
    return result;
}

A: This is the Complete program with all conditions positive, negative without using library
import java.util.Scanner;
public class StringToInt {
 public static void main(String args[]) {
  String inputString;
  Scanner s = new Scanner(System.in);
  inputString = s.nextLine();

  if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
   System.out.println("error!!!");
  } else {
   Double result2 = getNumber(inputString);
   System.out.println("result = " + result2);
  }

 }
 public static Double getNumber(String number) {
  Double result = 0.0;
  Double beforeDecimal = 0.0;
  Double afterDecimal = 0.0;
  Double afterDecimalCount = 0.0;
  int signBit = 1;
  boolean flag = false;

  int count = number.length();
  if (number.charAt(0) == '-') {
   signBit = -1;
   flag = true;
  } else if (number.charAt(0) == '+') {
   flag = true;
  }
  for (int i = 0; i < count; i++) {
   if (flag && i == 0) {
    continue;

   }
   if (afterDecimalCount == 0.0) {
    if (number.charAt(i) - '.' == 0) {
     afterDecimalCount++;
    } else {
     beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
    }

   } else {
    afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
    afterDecimalCount = afterDecimalCount * 10;
   }
  }
  if (afterDecimalCount != 0.0) {
   afterDecimal = afterDecimal / afterDecimalCount;
   result = beforeDecimal + afterDecimal;
  } else {
   result = beforeDecimal;
  }

  return result * signBit;
 }
}

A: Works for Positive and Negative String Using TDD

//Solution

public int convert(String string) {
    int number = 0;
    boolean isNegative = false;
    int i = 0;
    if (string.charAt(0) == '-') {
        isNegative = true;
        i++;
    }

    for (int j = i; j < string.length(); j++) {
        int value = string.charAt(j) - '0';
        number *= 10;
        number += value;
    }
    if (isNegative) {
        number = -number;
    }

    return number;
}

//Testcases
public class StringtoIntTest {
private StringtoInt stringtoInt;

@Before
public void setUp() throws Exception {
stringtoInt = new StringtoInt();
}

@Test
public void testStringtoInt() {
    int excepted = stringtoInt.convert("123456");
    assertEquals(123456,excepted);
}

@Test
public void testStringtoIntWithNegative() {
    int excepted = stringtoInt.convert("-123456");
    assertEquals(-123456,excepted);
}

}

A:     //Take one positive or negative number
    String str="-90997865";

    //Conver String into Character Array
    char arr[]=str.toCharArray();

    int no=0,asci=0,res=0;

    for(int i=0;i<arr.length;i++)
    {
       //If First Character == negative then skip iteration and i++
       if(arr[i]=='-' && i==0)
       {
           i++;
       }

           asci=(int)arr[i]; //Find Ascii value of each Character
           no=asci-48; //Now Substract the Ascii value of 0 i.e 48  from asci
           res=res*10+no; //Conversion for final number
    }

    //If first Character is negative then result also negative
    if(arr[0]=='-')
    {
        res=-res;
    }

    System.out.println(res);

A: public class ConvertInteger {

public static int convertToInt(String numString){
    int answer = 0, factor = 1;

    for (int i = numString.length()-1; i >= 0; i--) {
        answer += (numString.charAt(i) - '0') *factor;
        factor *=10;
    }
    return answer;
}

public static void main(String[] args) {

    System.out.println(convertToInt("789"));
}

}


text:
Q: How to change tint color of the UNSELECTED pictures in a tabBar
If I do     self.tabBar.tintColor = [UIColor whiteColor];
I manage to get the image of the selected tab bar white.
How do I get the image of the unselected tab bar black, or dark grey or red?

A: You can use something like this. The clue of this line of code is UIImageRenderingModeAlwaysOriginal. That means that the code is showing the original image. If your image is red, the icon will be red and if your image is blue, your icon will be blue.
Add this code in the first ViewController for every TabBarItem
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tabBarItem.image = [[UIImage imageNamed:@"yourImage.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"yourImage.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    ...
{

Now, you don't need your self.tabBar.tintColor = [UIColor whiteColor]; any more.
Rendering Modes by Apple Documentation:
UIImageRenderingModeAutomatic,          // Use the default rendering mode for the context where the image is used
UIImageRenderingModeAlwaysOriginal,     // Always draw the original image, without treating it as a template
UIImageRenderingModeAlwaysTemplate,     // Always draw the image as a template image, ignoring its color information

Check this answer: stackoverflow.com/a/22766669/1381708


text:
Q: Html5 Chunk Upload not working in Chrome 25? I have the following code to upload an image in chunk using Html5.
<!DOCTYPE html>
<form>

    #bytes/chunk:
    <input id="numChunks" value="1048576" />
    <input id="files" class="button" type="file" />

        Num of chunks:

</form>

This is working in all the browsers but its not working in my Chrome. In Chrome I don't receive the request on Server. In the chrome network tracking it always show the request as Pending.
UPDATE: I am not able to upload a big file (more than 1mb). It does not matter I chunk it or not or the size of the chunk. If the image size is more than 1mb it does not upload.
Please see the attached screenshot of the error

A: Try this
function(){
            var blobs = [];

/*
 * function that uploads a fragment of the file
 */
        function uploadChunk(blob, fileName, fileType){

            var xhr = new XMLHttpRequest();

            xhr.open('POST', 'upload_chunks.cfm', false);

            xhr.onload = function(e){
                document.getElementById("messages").innerHTML += "Chunk of size " + blob.size + " uploaded successfully.
";
            }

            xhr.setRequestHeader('X_FILE_NAME', fileName);
            xhr.setRequestHeader('Content-Type', fileType)
            document.getElementById("messages").innerHTML += "Uploading chunk of size " + blob.size + ".
";
            xhr.send(blob);
        }

/*
 * Invoke this function when the file is selected.
 */
        document.querySelector('#userfile').addEventListener('change', function(){
            var file = this.files[0];
            var bytes_per_chunk = 1024 * 1024;
            var start = 0;
            var end = bytes_per_chunk;
            var size = file.size;

            while (start < size) {
    //push the fragments to an array
                blobs.push(file.slice(start, end));
                start = end;
                end = start + bytes_per_chunk;
            }

    //upload the fragment to the server
            while (blob = blobs.shift()) {
    uploadChunk(blob, file.name, file.type);
            }
        })
    })();

From http://www.sagarganatra.com/

A: Here is another possible solution
https://github.com/tbela99/uploadManager/tree/master/Source
Credit goes to Thierry Bela


text:
Q: SVN: Committing Changes Made to Trunk to a Branch I have made a checkout from Trunk, made changes and committed the changes back to the trunk.  Now, I want apply those changes to a branch as well.  Can I switch my working copy to that branch and then commit those files that have changed to the branch?  I do have the list of the files that I have changed, and thus I know which files to commit.  But I want to see if switching my local copy to that branch is the way to go.

A: You need to merge your trunk changes into the branch.
This is a very common use case and I urge you to read the whole chapter in the SVN manual regarding branching and merging so you understand what you need to do here and why.

A: As long as your branch was made off of trunk (or a branch off of trunk), you can merge the changes up into your branch. More info here.


text:
Q: How to center table with long notes? I would like to ask how could I center a Table in the page that contains a lot of notes. I define notes as part of the Table. The code I applied is the following, but the outcome doesn't look nice.
\documentclass{article}
\usepackage{graphicx}
\usepackage{threeparttablex}
\usepackage{lscape}
\usepackage{booktabs}
\usepackage{tabularx}
\pagenumbering{gobble}
\begin{document}

\begin{table}
\begin{center}
\resizebox{1.\textwidth}{!}{
 \begin{threeparttable}
     \begin{tabular}{lrrrrrrrr}
 \multicolumn{9}{l}{Table 2: Results}         \\ \hline

%   &   MEAN    &   STD &   SKEW    &   KURT    &   JBpval  &   AC(1)   \\ \hline
 \multicolumn{9}{l}{Panel A: A}         \\ \hline

A   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
B   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
C   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
D   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
E   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
F   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
G   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
H   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
I   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
J   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
K   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
L   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
M   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
N   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
O   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
Q   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\

 \hline

\multicolumn{9}{l}{Panel B: B}         \\ \hline

A   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
B   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
C   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
D   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
E   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
F   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
G   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
H   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
I   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
J   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
K   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
L   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
M   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
N   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
O   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\
Q   &   -0.00   &   \textbf{0.00}   &   \textbf{0.00**} &   \textbf{0.00**} &   \textbf{0.11}   &   \textbf{0.00*}  &   -0.11   &   \textbf{0.00}   \\ \hline \hline

 \hline
     \end{tabular}
 \begin{tablenotes}[para,flushleft]
      \small
      \item Long Text Long Text Long Text Long TextLong Text Long Text Long Text Long TextLong Text Long Text Long Text Long Text Long Text Long Text Long TextLong Text Long Text Long Text Long TextLong Text Long Text Long Text Long TextLong Text Long TextTextLong Text Long Text Long Text Long TextLong Text Long Text Long Text Long TextLong Text Long Text Long Text Long TextLong Text Long Text Long Text Long TextLong Text Long Text Long  Long TextLong Text Long Text Long Text Long TextLong Text Long TextLong Text Long Text Long Text Long TextLong  Long  Long TextLong Text Long Text Long Text Long TextLong TextLong Text Long Text Long Text Long TextLong  Long TextLong Text Long Text Long Text Long TextLong Text Long TextLong Text Long Text Long Text Long TextLong TextLong Text Long TextLong Text Long Text Long Text Long TextLong Text Long Text Long Text Long TextLong Text Long Text Long Text Long TextLong Text Long Text Long Text Long TextLong Text Long Text Long Text Long Text ZZZZZZZZ
    \end{tablenotes}
  \end{threeparttable}
}
\end{center}
\end{table}
\end{document}

A: *

*don't use \resizebox

*instead \begin{center} .... \end{center}, which introduce additional vertical space, put \centering after \begin{table}

*consider to use smaller fonts: for table \small and for table notes footnotesize

*see, if you can change page layout, for example increase \textheight and \textwidth.

considering the first three items i obtain the following result:

off-topic:

*

*code for table can be shorter (if whole column is in bold face, than this can be obtain with

\begin{tabular}{lrr *{5}>{\bfseries}r} r >{\bfseries}r}
and omitting all \textbf{ ... } in the table body.

*

*for table caption you should use capability of threeparttable and move caption from multicolumn in tabular to caption in threeparttable:

...
\begin{table}
\small
\centering
 \begin{threeparttable}
\caption{Table 2: Results}
     \begin{tabular}{lrrrrrrrr}
     \hline
%   &   MEAN    &   STD &   SKEW    &   KURT    &   JBpval  &   AC(1)   \\ \hline
 \multicolumn{9}{l}{Panel A: A}         \\ \hline
 ...


text:
Q: Django Forms with dynamic field values First time using Django Forms. I'm stuck trying to get the dropdown choices to reload. My forms.py is below. When the database state changes, the choices do not. I suppose that this is because they are defined at a class level, which means the query happens at initialisation of the module? I've found that the only way to get my dropdowns to update is to restart the webserver.
How can I have the database queries evaluate on every request?
forms.py
from django import forms
from app.models import Collection, ErrorMessage, Service

class FailureForm(forms.Form):
    collections = [(collection.value,)*2 for collection in Collection.objects.all()]
    error_messages = [(message.value,)*2 for message in ErrorMessage.objects.all()]
    services = [(service.value,)*2 for service in Service.objects.all()]

    collection = forms.CharField(label='collection', max_length=100, widget=forms.Select(choices=collections))
    error_message = forms.CharField(label='error_message', max_length=400, widget=forms.Select(choices=error_messages))
    service = forms.CharField(label='service', max_length=100, widget=forms.Select(choices=services))

A: class FailureForm(forms.Form):
    collection = forms.ChoiceField(widget=forms.Select, choices=[])
    ... # etc

    def __init__(self, *args, **kwargs):
        super(FailureForm, self).__init__(*args, **kwargs)
        self.fields['collection'].choices = [(collection.value,)*2 for collection in Collection.objects.all()]
        ... # etc

Note: label='collection' is obsolete. It will be "collection" by default. Same with error_message and service

A: Did some more digging in the documentation and noticed that callables on a ChoiceField are called every initialisation. Therefore, the solution below was I think preferable for me.
class FailureForm(forms.Form):
    collection = forms.ChoiceField(choices=lambda: [(collection.value,)*2 for collection in Collection.objects.all()])
    error_message = forms.ChoiceField(choices=lambda: [(message.value,)*2 for message in ErrorMessage.objects.all()])
    service = forms.ChoiceField(choices=lambda: [(service.value,)*2 for service in Service.objects.all()])