text:
Q: Using recursion to concatenate two strings My goal is to concatenate two strings using recursion.
The input would be str1 = ("long string") str2 = ("yes so long")
and the output would be: 'lyoensg ssto rlionngg'
Assumptions are that both strings are the same length.
My code as of now is:
def concat_order(str1, str2):
    if len(str1) == 0:
        return 'complete'
    i = 0
    new_str = str1[i] + str2[i]
    i = i + 1
    return concat_order(str1[1:], str2[1:])
    return new_str
print(concat_order("long string"', "yes so long"))

Im sure Im no where close but I am struggling with making it loop.
I am not allowed to use loops but I can use if statements

A: You don't need to pass 'i' like this: new_str = str1[i] + str2[i]
as you are already returning string excluding previous character: return concat_order(str1[1:], str2[1:]).
Also a function can not have two return statements like this:
    return concat_order(str1[1:], str2[1:])
    return new_str

any statement after return statement won't execute. That's why we write multiple return statements in some conditional statement like if else
Modified your program to give the correct answer.
def concat_order(str1, str2, new_str):
    if len(str1) == 0:
        return new_str
    new_str += str1[0] + str2[0]

    return concat_order(str1[1:], str2[1:], new_str)

ans = ""
print(concat_order("long string", "yes so long", ans))

or you can do this:
def concat_order(str1, str2):
    if len(str1) == 0:
        return ''

    return str1[0] + str2[0] + concat_order(str1[1:], str2[1:])

print(concat_order("long string", "yes so long"))

as the control flow reaches base case, we already have what we wanted so don't return anything.

A: Recursion just needs a base case and a recursion case. Here your base case is a little strange. You never want the string "complete" so you shouldn't return that. The base case when str1 is empty should just return the empty string.
Then you just need to take the first letter from each string, concat, and concat with recursion of the rest:
def concat_order(str1, str2):
    if len(str1) == 0:
        return ''

    a, b = str1[0], str2[0]

    return a + b + concat_order(str1[1:], str2[1:])

concat_order("long string", "yes so long")
# 'lyoensg  ssot rlionngg'

Note the extra space is the correct behavior unless there's a requirement to prevent them.

A: def concat_strings_rec(str1, str2):
    if len(str1) < 1:
        return ""
    else:
        curStr = str1[0] + str2[0]
        return curStr + concat_strings_rec(str1[1:], str2[1:])

def concat_string_iter(str1, str2):
    return "".join([str1[i] + str2[i] for i in range(len(str1))])

string1 = "long string"
string2 = "yes so long"

print(concat_strings_rec(string1, string2))
print(concat_string_iter(string1, string2))

Expected output:
lyoensg  ssot rlionngg
lyoensg  ssot rlionngg

Recursive solution
You need the base case which is when the array length is 0. In that case return an empty string. In all other cases return the first element of each string concatenated with the return value of the recursive call to concat_strings_rec(). Remember to decrease the array size for the recursive calls!
Iterative solution
The iterative solution just loops through the array concatenating each character within the two strings and putting the concatenated first, second, third,... character in an array. Then use "".join() to concatenate those two character strings in the array to a complete string.
Recommendation
Don't use the recursive solution as it just consumes more memory due to the call stack and it will be slower and since Python has a limit on the number of calls on the call stack it will fail for larger strings.


text:
Q: Parse xml from url. Exception I need to get some info from URL("http://someurl.com/file.xml").
Info in tags - "name", "surname".
How can I do that ?
I know I must using AsyncTask for internet connection.
I trying using XMLPullParser in AsyncTask, but I get exception "IndeOutOfBound"
class RequestTask extends AsyncTask<String, Void, Void> {
        String name;

        @Override
        protected InputStream doInBackground(String... uri) {
                try {
                    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                    factory.setNamespaceAware(true);
                    XmlPullParser xpp = factory.newPullParser();
                    xpp.setInput(new InputStreamReader(
                            getUrlData("http://someurl.com/file.xml")));

                    while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
                        if (xpp.getEventType() == XmlPullParser.START_TAG) {
                            if (xpp.getName().equals("name")) {
                                name=xpp.getAttributeValue(0);
                            }
                        }
                        xpp.next();
                    }
                } catch (Throwable t) {
                }

} catch (IOException e) {
        //Handle problems..
        }
        return null;
        }

@Override
protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        Toast.makeText(getActivity().getApplicationContext(),
        "name="+name, Toast.LENGTH_SHORT).show();

        }

}

A: Look at the XML in "file.xml".
I suspect the error is here:
 ...
 if (xpp.getEventType() == XmlPullParser.START_TAG) {
   if (xpp.getName().equals("name")) {
     name=xpp.getAttributeValue(0);  // <- Does your"<name>" tag have any attributes???

Here are some tutorials on Android XML processing:

*

*http://www.javatpoint.com/android-XMLPullParser-tutorial

*http://www.xmlpull.org/v1/download/unpacked/doc/quick_intro.html

*http://www.vogella.com/tutorials/AndroidXML/article.html
In particular, note the use of getText() to fetch element content.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PDO Update with variable table, column, row I would like to build an ajax function that updates field variables in some tables.
The tables, fields, and rows are all variable and based on what is posted via the ajax function.
This is the code for my quickedit.php
define( "DB_DSN", "mysql:host=$host;dbname=$data" );
define( "DB_USERNAME", $user );
define( "DB_PASSWORD", $pass );

if(isset($_POST['table'])){ $table = $_POST['table'];}
if(isset($_POST['id'])){ $id = $_POST['id'];}
if(isset($_POST['field'])){ $field = $_POST['field'];}
if(isset($_POST['value'])){ $value = $_POST['value'];}

try {
    $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
} catch (Exception $e) {
    die("Connection Error");
}

try {
    $st = $con->prepare("UPDATE :table SET :field = :value WHERE id = :id");
    $st->execute(array(':table'=>$table, ':id'=>$id, ':field'=>$field, ':value'=>$value));
} catch (Exception $e) {
    die("Query Error");
}
echo "table: ".$table." id: ".$id." field: ".$field." value: ".$value;

As you can see, I wish to dynamically select the table, column, and row.
I'm don't know a whole lot about exceptions, but none of them are being thrown
and it is successfully echoing the stuff at the bottom i told it to.

A: You'll need to build the original mysql sentence in the old way, using PHP to evaluate table and column names.  Then use PDO to bind values to the fields.
 $st = $con->prepare("UPDATE $table SET $field = :value WHERE id = :id");
 $st->bindValue(':id',$id,PDO::PARAM_INT);
 $st->bindValue(':value',$value,PDO::PARAM_STR);
 $st->execute();

Be carefult not to allow quotes or semicolons in the variables youre evaluating. It's fairly easy to perform an SQL injection that way.

A:
As you can see, I wish to dynamically select the table, column, and row.

Yes, we see it.
And this is where your idea is wrong.
This is quite contagious disease every good programmer have to outgrow. You are trying to make Universal Updater. Unfortunately, although the idea of some automation is usually all right, too much automation can be a disaster.
Your application have to have an idea what does it update and why. All the queries have to be pre-written and only data part may vary. It's all right to build a dynamical update from the several  fields, but makeing even table name dynamical is too much.
As of your particular problem, ORM is what you really looking for. Look how it can be done with Yii Active record:
$post=$table::model()->findByPk($id);
$post->$field=$value;
$post->save(); // save the change to database


text:
Q: Identity in MVC I need to get the user's name and ID to be accessible in my view. When I use Page.User.Identity.Name, I get the email I use to authenticate it. This is how I go about authenticating the user from my controller:
if (!userService.ValidateUser(model.Email, model.Password))
    FormsAuthentication.SetAuthCookie(model.Email, false);

How can I be able to do: Page.User.Identity.UserId or Page.User.Identity.FirstName?

A: Your question is not clear but if are using Identity in MVC and you want to get the User's name and ID in your view I think this will help. In your view try this:
@using Microsoft.AspNet.Identity

@if (Request.IsAuthenticated)

{

           @User.Identity.GetUserName() "or" @User.Identity.GetUserId();

}


text:
Q: bootstrap login /img/glyphicons I am having trouble with boostrap-responsive.
When I login to my application on my laptop I get the homepage localhost:8080/abc/ with no problems but when I log into the same app from any mobile device it goes to ip:8080/abc/img/glyphicons-halflings.png. And just displays all bootstraps icons on the page.
If I manually put in the correct url after, the app works fine and if I logout and log back in it works fine. Always occurs the first time you try to log in. Below is the code I am using in my jsp. I have done a search for "img/glyphicons-halflings.png" in my project and the only place it occurs is in the bootstrap code so I cannot understand why it redirects to this page.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ABC</title>
<meta name="description" content="">
<meta name="author" content="">

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="<c:url value="/css/bootstrap.css" />" rel="stylesheet" type="text/css" />
<link href="<c:url value="/css/bootstrap-responsive.css" />" rel="stylesheet" type="text/css">
<style type="text/css">

A: the issue is not from the bootstrap, you just need to set the absolute url.
create an helper class contains static method called baseUrl (or whatever) which return a base url of your website.

A: Just in case somebody has a similar issue, the problem was actually with my spring-security.xml. There was a typo on the part to permitAll() to view the images folder. So my understanding of it is that when bootstrap attempted to access the images folder for the mobile site(not used on desktop version), spring security intercepted this and redirected to the login page which was normal behaviour. Then when I would login spring was redirecting back to the request bootstrap had made before the login and that is why all the glyphicons were being displayed.

A: The problem is that the "glyphicons" are not just CSS, they need other ressources more than js and css, which is the "fonts" this ressources  comes whith "js" and "css" folders  in the bootstrap framework,
Now for making all this working to gather  just  copy the "fonts" folder in the same level of  your "css" and "js"  in your Java EE project.
Thanks.


text:
Q: canu installation error I have searched and read the posts reagrding "canu" assembler since I am facing an issue running the canu program on ubuntu. After I installed canu and run "make" command, it said:

Success! canu installed in /home/server/canu/build/bin/canu

I tried going to the above said path and run the "canu" program syntax:

server@myserver:~/canu/build/bin$ canu -p ecoli -d ecoli-pacbio
genomeSize=4.8m -pacbio pacbio.fastq

It says:

Command 'canu' not found, but can be installed with: sudo apt install
canu

As you suggested earlier, I tried exporting PATH at:

server@myserver:/$ export PATH=$PATH:/home/server/canu/build/bin/canu

But, still I get the same issue .. Command 'canu' not found .. error.


text:
Q: Memory-leak when rewriting data (C++) Ive problem with my code (C++)causing memory leak ( i belive). Basically i want it to do the following: take data from user untill he writes "stop" and make heap out of that data. I guess that I'm missing a removal of booked memory at some point but i dont know how to fix it. Also the code seems to be working in code::blocks but it crashes in Dev C++.
cout<<"Enter data to heap if u wanna stop write stop."<<endl;

int *w1=new int[1];

int kek=0;

    while(true)

{
    cin>>*(w1);

    if (!cin)
        {                                        /// the "stop"" thingy
            w1=w1-kek;
            cout<<"heap:  "<<endl;
            for (int i=0;i<kek;i++)
                {
                    cout<<" "<<*w1<<" ";
                    w1++;
                }
            break;
        }
int *w2=new int[2+kek];
w1=w1-kek;
        for(int t=0;t<kek+1;t++)          ///rewriting data to new chunks of memory
            {

                *w2=*w1;
                w2++;
                w1++;
            }
delete[]w1;                               ///releasing old ones ( i think something is wrong here)
w1=w2;
kek++;
w1=w1-kek-1;
int kekkeeper=kek;
for(int l=log(kek)/log(2);l>0;l--)            /// heapnig things up

        {

            if(*(w1+kekkeeper/2)>*(w1+kekkeeper)) swap (*(w1+kekkeeper/2),*(w1+kekkeeper));
            else break;
            kekkeeper=kekkeeper/2;
        }
    w1=w1+kek+1;
    w2=NULL;
    delete[]w2;

    }

A: look at the last tow lines
you set w2 to NULL before your delete it

A: you changed both pointers w1 and w2 in the following loop
for(int t=0;t<kek+1;t++) {
  *w2=*w1;
   w2++;
   w1++;
}

so you must reset this modification for each pointer before deleting it.
the reseting instruction for w1 can look like this
w1=w1-(kek+1);
delete[]w1;

and for w2 like this
w2=w2-kek;
delete[]w2;

finally you must move the allocation of w1 into the while loop.


text:
Q: Need to extract a specific number from a string with several numbers using Selenium I need to get 293 as an int from the string "1 to 20 of 293 total". I'm unable to do it using .replaceAll method. Please help

A: try this :
    String s = "1 to 20 of 88 total";
    String k [] = s.split("1 to 20 of");
    String t [] = k[1].split("total");
    System.out.println(Integer.valueOf(t[0].replaceAll("\\s+","")));


text:
Q: Data extract from one sheet to another sheet with multiple criteria in excel vba I have large data with 6 columns in sheet 2. I would like to extract the data from sheet 2 to sheet 5 based on multiple criteria.
my sheet 2 data ...
Example data
so, i write following code to extract data from sheet 2 to sheet5.
Sheet2.Range("a1").CurrentRegion.AdvancedFilter _
Action:=xlFilterCopy, CriteriaRange:=Sheet5.Range("a3:d3"), _
CopytoRange:=Sheet5.Range("a10:k10"), Unique:=False
'Columns(6).AutoFit

problem is when I run above code it displays all data from sheet 2, but it is not met with my criteria.
for example  if user selects following details...
Place   : USA
Month   : Jul-19
Variety : I
remarks : PR
output should be like these...
Example Output

A: The CriteriaRange is expecting headers AND criteria, furthermore the CopyToRange will work assigning it just a single cell (you wouldn't know pre-filtering the amount of rows it should contain with each filtering). So with the following setup on sheet1 and sheet5:
Sheet1:

Sheet5:

Running the following code:
Sub AdvancedFiltr()

Sheet2.Range("A1").CurrentRegion.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheet5.Range("A1:F2"), CopyToRange:=Sheet5.Range("A4")

End Sub

Results in Sheet5:

Some remarks:

*

*CriteriaRange: The headers need to match the headers from the database exactly.

*CriteriaRange: You don't need to have every header, just the ones you want to filter by.

*CopyToRange: It's wise to clear the range on Sheet5 before you apply another filter.

*I really think this is a great article on AdvancedFilter to make clear how it works.


text:
Q: Replacing text with jQuery only in active/focussed input-Element I have a page where I have around 10 input-Elements. Some of them I gave the class .no-whitespace-allowed. Now I have a jQuery script running in the background with the purpose to avoid whitespaces in the very input-Elements:
$(function() {
    var elements = $(".no_whitespace_allowed");
    var func = function() {
        if (elements.is(':focus')) elements.val(elements.val().replace(/\s/g, ''));
        else elements.val(elements.val());
    }
    elements.keyup(func).blur(func);
  });

However, it replaces the text in every input field with the result that I have the same text in all inputs. Any ideas?

A:

  $(".no_whitespace_allowed").keyup(function(){
 $(this).val( $(this).val().replace(/\s/g, '') );
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <input class="no_whitespace_allowed" type="text">

Something like this ?


text:
Q: On properties on a certain functional Consider the following function:
$$F(z) = \omega(z)\sin^2\left(\frac{c\Gamma(z)}{z}\right)$$
Here, $\omega(z)$ is a weight we have to construct and $c$ is a constant.
The following three conditions should meet for $\omega(z)$:

*

*$$\omega(z)>\frac{1}{z},\ \forall z\in\mathbf{R}$$
( More generally this condition is added for divergence of $\int_c^\infty F(x)dx$ So ,  $\omega(z)$  can even be complex valued for real domain as long as the given integral is divergent )

*$$\lim_{ y→∞}|F(x ± iy)|e^{−2πy }= 0$$

*$$\int_0^\infty |F(x + iy) − F(x − iy)|e^{−2πy} dy<+\infty$$ for every $x≥1$ and tends to zero as $x\to\infty$.

Question : Can we Explicitly construct $\omega(z)$.

If anyone could omit the first condition and could find the weight satisfying condition 2 and 3 please mention.

(Is it even possible?)
See this MSE post ( see the part after UPDATE) and this MSE post for more details.
The question is inspired by following analysis:
\begin{align}f(x) = {} & \sin^2\left(\frac{π\Gamma(x)}{2x}\right)\\
\sum_{k=2}^p f(k)= {} & \frac{f(2) +f(p)}2 + \int_2^p f(x) \, dx \\ & {}+ i\int_0^∞\frac{f(2+iy) − f(2−iy)}{e^{2πy }− 1} \, dy +i \int_0^∞\frac{f(p-iy) − f(p+iy)}{e^{2πy }− 1} \, dy
\end{align}
As we can see the above summation is 'sort of' a prime counting function.
I'm trying to prove the infinitude of primes by trying to show that the above sum diverges as p tends to infinity.
In doing so I faced the following:
The complex integral in the RHS show oscillation of increasing amplitude. So to convert the summation into real integral I tried to attach weight such that the complex integral tends to zero as  p tends to infinity and so we only remained with real integral and some constant terms.


text:
Q: How to take off the marks of a graphic made with a CSV file I'm importing a CSV file and I want to take off the marks of the graphic,how can I do this?
\documentclass{minimal}
\usepackage{pgfplots}
\usepgfplotslibrary{dateplot}

%\usepackage{filecontents}% Commented out dataCL.csv is not overwriten.
\begin{filecontents*}{dataCL.csv}
    x, y
    1, 10
    2, 15
    3, 17
\end{filecontents*}

\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot table [mark = none, draw = none,col sep=comma,x=x, y=y] {dataCL.csv};
\end{axis}
asdfasdfasdfasd
\end{tikzpicture}
\end{document}

A: mark=none is an option to \addplot/\addplot+, not to table. BTW, you should use only marks instead of draw=none. Please find attached an example in which the first plot has only a line and the second one has only marks.
\documentclass{article}
\usepackage{pgfplots}

\usepackage{filecontents}% Commented out dataCL.csv is not overwriten.
\begin{filecontents*}{dataCL.csv}
    x, y
    1, 10
    2, 15
    3, 17
\end{filecontents*}

\begin{document}
\begin{tikzpicture}
\begin{axis}
    \addplot+ [mark=none] table [col sep=comma, x=x, y=y] {dataCL.csv};
    \addplot+ [only marks] table [col sep=comma, x=x, y=y] {dataCL.csv};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: android.view.Surface - OutOfResourcesException I have this strange bug, and found nothing about a possible solution to it. The problem always  appears randomly after playing around a bit with my app. The app runs perfectly on almost all devices. Still one of the devices on which this issue is present is running CM 7.1.0 and I know that a lot of CM7 users were complaining about similar problems.
Unfortunately I have some users that had the same issue with the app, but I don't know if they were using CM7 or not. Since I wasn't able to reproduce this error in other apps on the same ROM it must be related to something else.
As I've said before it appears totally random, so copying the source code doesn't makes no sense. Here's the log instead, hopefully someone already had the same problem and can help me out. Thanks.
msm7k.gralloc(1306): alloc mmap(fd=150, size=614400, prot=3) failed (Try again)
msm7k.gralloc(1306): gralloc failed err=Try again
GraphicBufferAllocator(1306): alloc(320, 480, 1, 00000033, ...) failed -11 (Try again)
GraphicBufferAllocator(1306): Allocated buffers:
GraphicBufferAllocator(1306):   0x20a8d0:  300.00 KiB |  320 ( 320) x  480 |  4 | 0x00000133
GraphicBufferAllocator(1306):   0x20c110:  531.25 KiB |  320 ( 320) x  425 |  1 | 0x00000133
GraphicBufferAllocator(1306):   0x292db0:   31.25 KiB |  320 ( 320) x   25 |  1 | 0x00000133
GraphicBufferAllocator(1306):   0x299568:  300.00 KiB |  320 ( 320) x  480 |  4 | 0x00000133
GraphicBufferAllocator(1306):   0x4a2288:  331.25 KiB |  320 ( 320) x  265 |  1 | 0x00000133
GraphicBufferAllocator(1306):   0x4b2518:   31.25 KiB |  320 ( 320) x   25 |  1 | 0x00000133
GraphicBufferAllocator(1306): Total allocated: 1525.00 KB
SurfaceFlinger(1306): Layer::requestBuffer(this=0x3a7618), index=0, w=320, h=480 failed (Try again)
Surface(7024): Surface (identity=224) requestBuffer(0, 0, 0, 0, 00000033) returned a buffer with a null handle
Surface(7024): getBufferLocked(0, 0, 0, 0, 00000033) failed (Out of memory)
Surface(7024): dequeueBuffer failed (Out of memory)
ViewRoot(7024): OutOfResourcesException locking surface
ViewRoot(7024): android.view.Surface$OutOfResourcesException
ViewRoot(7024):     at android.view.Surface.lockCanvasNative(Native Method)
ViewRoot(7024):     at android.view.Surface.lockCanvas(Surface.java:314)
ViewRoot(7024):     at android.view.ViewRoot.draw(ViewRoot.java:1461)
ViewRoot(7024):     at android.view.ViewRoot.performTraversals(ViewRoot.java:1263)
ViewRoot(7024):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1865)
ViewRoot(7024):     at android.os.Handler.dispatchMessage(Handler.java:99)
ViewRoot(7024):     at android.os.Looper.loop(Looper.java:130)
ViewRoot(7024):     at android.app.ActivityThread.main(ActivityThread.java:3835)
ViewRoot(7024):     at java.lang.reflect.Method.invokeNative(Native Method)
ViewRoot(7024):     at java.lang.reflect.Method.invoke(Method.java:507)
ViewRoot(7024):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
ViewRoot(7024):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
ViewRoot(7024):     at dalvik.system.NativeStart.main(Native Method)

A: After long hours of pulling my git commits I've finally found one that didn't had this problem. Since the app I'm working on displays sensitive data on the screen, I was trying to change the image displayed as the thumbnail in the "Recent Apps" section. In order to achieve this I was setting the secure flag to the window:
http://developer.android.com/reference/android/view/Window.html#setFlags(int, int)
http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_SECURE
Turns out that this was the problem that caused the exception and the black screen that was shown. After I've removed it, everything was working just fine. Hopefully this tip will help other devs facing the same problem.

A: You need to call release() if you are not using your android.view.Surface anymore.
http://developer.android.com/intl/es/reference/android/view/Surface.html#release()

A: I have similar problem, but related to HW surface.
I have ProgressDialog and SignIn component.
All Communication between this components done through Handler class.
In my case the only thing that saves from crash is turning off hw acceleration for specific Activity.


text:
Q: Don't show ad for Developer Survey if you've already taken it I just noticed an advertisement for the Developer Survey 2020:

I have already taken it two weeks ago, and the system knows about this since it awarded me a badge for it. In that case, it's better to reserve valuable advertising space for paying customers (as long as they provide on-topic, non-annoying and non-privacy-attacking ads, but that's another story), and it prevents people from accidentally filling it in twice.


text:
Q: Knockout js valor por defecto en etiqueta select html Tengo una etiqueta de select en mi html con el enlace de Knockout js.

Editar

        Municipio:

            <input id="TextboxMunicipalityNameEdit" type="text" class="form-control" data-bind="value: MunicipalityName" maxlength="40" required />

        Provincia:

            <select id="ComboBoxProvincesEdit" class="form-control" data-bind=" value: ProvinceId, options: $parent.Provinces, optionsText: 'ProvinceName',
                    optionsValue: 'ProvinceId', optionsCaption: 'Seleccione una Provincia...',optionsDisableDefault: true"></select>

            <button class="btn btn-success" data-bind="click: $parent.Update">Guardar</button>

En lugar de que me aparezca seleccione una provincia quiero que si tengo un valor de una provincia que me salga seleccionada la provincia por defecto,
este es mi modelo que me llega con los datos requeridos y la provincia,
municipalityViewModel.Edit = function (model) {
    municipalityViewModel.IsNewButton(false);
    municipalityViewModel.IsBackToListButton(true);
    municipalityViewModel.ShowResult(false);
    municipalityViewModel.IsDetails(false);
    municipalityViewModel.IsNew(false);
    municipalityViewModel.IsEdit(true);
    municipalityViewModel.MunicipalityModel().MunicipalityId(model.MunicipalityId);
    municipalityViewModel.MunicipalityModel().MunicipalityName(model.MunicipalityName);
    municipalityViewModel.MunicipalityModel().ProvinceId(model.ProvinceId);
    municipalityViewModel.MunicipalityModel().ProvinceName(model.ProvinceName);
    municipalityViewModel.MunicipalityModel().CreateBy(model.CreateBy);
    municipalityViewModel.MunicipalityModel().CreationDate(model.CreationDate);
    municipalityViewModel.MunicipalityModel().ModifiedBy(model.ModifiedBy);
    municipalityViewModel.MunicipalityModel().ModifiedDate(model.ModifiedDate);
    LoadProvinces();
    LoadListMunicipalitys();
    //$('#ComboBoxProvincesEdit').val(model.ProvinceId);
    $('#TextboxMunicipalityNameEdit').focus();

};

no se si me entienden pero quiero que este formulario de editar como tengo un municipio con su provicia que me salga la provincia seleccionada por defecto en vez de 'Seleccione una Provincia...',
ayuda,


text:
Q: Difference between String1.Equals(string2) and string1==string2 C#
Possible Duplicate:
C#: String.Equals vs. ==
Are string.Equals() and == operator really same?

sometimes in a condition between two strings, I write:
if(string1==string2) //Do something

and sometimes I write:
if(string1.Equals(string2)) //Do something

The problem is sometimes the first one doesn't work, or miswork, is there any difference between the two expressions?

A: The first one will always work so long as the compile-time type of both operands is string.
If the compile-time type of either operand is anything other than string, it will use the normal reference identity comparison, rather than comparing strings for equality. Basically you want to call the ==(string, string) overload instead of the normal ==(object, object) overload.
Note that the first will succeed even if string1 is null, whereas the second will throw NullReferenceException in that case. An alternative in order to preserve the Equals call but avoiding this problem is to call the static object.Equals(object, object) method:
if (object.Equals(string1, string2))

Personally I'd just use == in cases where the compile-time types are appropriate though.

A: The use of == on two string types will perform a reference identity check, meaning it will only return true if both references point to the same object. Equals on the other hand is expected to perform a value comparison, and will return true if the references point to objects that are equivalent.


text:
Q: Is WD elements with NTFS format supported on Ubuntu? I brought a WD Elements 1tb external hdd and I'm planning to install Ubuntu on my laptop.(not a dual boot). So I was wondering will the hdd work on Ubuntu, it's ntfs formatted.I dont want to format it again just for ubuntu. i want it to be able to work on different os platforms as well

A: Yes, the external hard drive with NTFS file format will work with Ubuntu file system in your laptop. However, if you plan to install Ubuntu on the same hard drive, you need to reformat it to ext4 file system.


text:
Q: Using .split() to add sentences (with commas) into array I am adding sentences to an array, but I need the array items to be split in a way that will take into account sentences with commas in them.
Currently I am using String.split(","); but it splits a single sentence into 2 different array items if the sentence has a comma in it. Ideally I would like to do something simple like ignore commas that are followed by whitespace. ", ".

A: JavaScript .split() can accept a RegExp as argument. So what you want to achieve is fairly simple with a negative look ahead.

var s = "I'm a sentence,I'm another sentence, but with a comma,the last sentence";

console.log( s.split( /,(?! )/ ) )

That being said, you shouldn't use a comma as a delimiter if your sentence contains commas. You should solve your problem at the root: where does the string come from and why is it a string (and not an array)? Unfortunately, we cannot help you more than that with the information provided.


text:
Q: Omnifaces Components#includeCompositeComponent set attribute value When dynamically creating a composite component with Omniface's Components #includeCompositeComponent, is it possible to pass attributes values (such as attribute myValue) so that it is available for a pre-render event on the composite?
<composite:interface>
     <composite:attribute name="myValue" required="true" />
</composite:interface>
<composite:implementation>
    <!-- this works! -->
    <h:outputText value="#{cc.attrs.myValue}" />
    <!-- this doesn't execute -->
    <f:event id="eventId"
             type="javax.faces.event.PreRenderComponentEvent"
             listener="#{bean.someAction(cc.attrs.myValue)}" />
    <!-- stuff -->
</composite:implementation>

However, I'm able to access myValue on the xhtml (via #{cc.attrs.myValue}), but its not available for pre-render (I used UIComponent#getAttributes to specify myValue's value).
Edit: if the attribute is also available in @PostConstruct (via managed-property) it would also do.

A: Check the javadoc:

public static UIComponent includeCompositeComponent(UIComponent parent, String libraryName, String resourceName, String id)
...
Returns:
The created composite component, which can if necessary be further used to set custom attributes or value expressions on it.

So, just get hold of the returned UIComponent instance and make use of UIComponent#getAttributes() to put static values or UIComponent#setValueExpression() to set EL expressions.
UIComponent composite = Components.includeCompositeComponent(parent, library, name, id);
composite.getAttributes().put("myValue", myStaticValue);
// Or:
composite.setValueExpression("myValue", Components.createValueExpression("#{bean.myValue}", String.class));
// ...


text:
Q: Is the empty set internal? Is the empty set internal or not?
And is there a proof (either way), or is it just a convention? If it's just a convention, why was that particular convention chosen?

A: The answer given in the comments can be simplified.  Every finite set is internal.  In particular, so is the empty set. Moreover the empty set is standard because it is already contained in the standard universe before a nonstandard enlargement is defined.  Recall that all standard things are internal but not vice versa.  For example, an infinitesimal number is an internal object but obviously it is not standard.


text:
Q: Read .php file without applying HTML and PHP tags in the result I need to read a .php file as plain text.
Text in main script:
<?php $data = file_get_contents('file2read.php'); ?>
 <?php echo $data; >

For example, I have this in file2read.php:

  <?php> e(enlace('/pages/index', __('index'), True, False, array('class' => 'ajax'))); ?>

The output of the main script is:

'ajax'))); ?>

I want that output to be something like this in plain text:

  <?php> e(enlace('/pages/index', __('index'), True, False, array('class' => 'ajax'))); ?>

A: Read as plain text
$data = file_get_contents('file2read.php');

Output to a web page in plain text

   <?php echo $data; ?>

A: Done using htmlentities()
<?php echo htmlentities($data); ?>


text:
Q: Fundamentals on Generics Why does the following does not work?
Vector<? extends SomeClass> v = new Vector<SomeClass>();
SomeClass e = new SomeClass();
v.add(e);

I get a compilation error that:

The method add(capture#1-of ? extends SomeClass) in the type
  Vector is not applicable for the
  arguments (SomeClass)

A: Collections with generic wildcards which extend from a type do not allow you to add to that Collection.
As the compiler does not know exactly what type of SomeClass you are attempting to add, it doesn't allow it. The exception to this is a null object which can represent any type of Object.
To answer your comment: Although you cannot add to the Collection, it cannot be described as read only as it is still possible to remove Objects.
To allow addition of Objects, you would need to use a known type:
Vector<SomeClass> v = new Vector<SomeClass>();

A: The problem basically is that by declaring v as Vector<? extends SomeClass> you say that it's a collection of SomeClass or one of its subclasses. The compiler cannot make any assumptions about what specific type the container actually hold, even if the assignment to new Vector<SomeClass>() is done on the same line. As much as the compiler knows v might  have been created as new Vector<SubClassOfSomeClass>(). That is why it refuses to put SomeClass instances (or anything else for that matter) to the collection. You can however get the SomeClass elements out of it.
If you want to be able to put elements to the collection, then declare v as Vector<? super SomeClass>, by which you say that it's a container of SomeClass or one of its superclasses. The compiler knows then that a SomeClass instance will certainly fit in such a collection.
You cannot however get a SomeClass element out of that collection, as the compiler knows nothing about the type of elements in it (except that it is some superclass of SomeClass). By the definition of v it might as well be just a collection of Objects.
This is called the put/get principle in short which is discussed in detail also in other posts like this.

A: This is explained here. The list declared like that is effectively a read-only list, but it is more flexible than a normal List<AbstractClass> list.
If you want to use an abstract class as a template, just use it straight on like this: List<SomeClass> list.
Consider reading Java language specification, there is a lot of information about the generics logic.

A: There should not be problem to you in your problem explanation.  I understood your problem as in the following code.
import java.util.*;
class Test
{
  int x;
}
public class Demo
{
   public static void main(String args[])
   {
      Vector<Test> vect = new Vector<Test>();

      Test t1 = new Test();
      Test t2 = new Test();
      t1.x = 10;
      t2.x = 20;

      vect.add(t1);
      vect.add(t2);

      for(Test t : vect)
      {
         System.out.println(t.x);
      }
  }
}

I read this type of gimmicks in Vector Play With.


text:
Q: Using Nginx as proxy for Node.js' Express and Socket.io I want to run an express server and a socket.io server on an node.js instance which are reachable through nginx. If possible, I would favor to run them both on the same port, but I did not reach that goal either.
I can reach the webserver locally and from extern.
I can only reach the socket server locally.
When I call the page, my browsers log shows the following error:
GET https://example.com/socket.io/?EIO=3&transport=polling&t=O6qCW5Y
400 Bad Request

So I think the problem lies somewhere in the nginx config.
My app.js code for the socket.io server:
const http = require('http').createServer();
const io = require('socket.io')(http);

http.listen(3001, () => {
    console.log('Socket-Server listening on port: 3001');
});

io.on('connection', (socket) => {
    ...
});

My code for the client:
window.onload = function() {
    const socket = io.connect('https://box-api.com/');

    socket.on('connect', () => {
        ...
    }
}

My nginx config:
server {
    server_name example.com;

    root /nodejs/example.com;
    include static_files.conf;

    index app.js;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
    }
    location /socket.io {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;

        proxy_pass http://127.0.0.1:3001;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # Certbot stuff
    ...
}


text:
Q: WP8 + Upload File to Skydrive I'm trying to upload a simple .cer file to SkyDrive. Regardless of the LiveConnectClient-Method I use, nothing happens. There is no compile, runtime or other Exception and my app never receives a LiveOperationResult. I'm using the emulator, and I'm able to log in to MS Live (so my internet connection is fine). Here is a excerpt of the code used:
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
  using(var fileStream = store.OpenFile(certPath, FileMode.Open, FileAccess.Read, FileShare.Read))
  {
    try
    {
      client = new LiveConnectClient(session);
      //LiveOperationResult operationResult = await client.UploadAsync("me/skydrive", certPath, fileStream, OverwriteOption.Overwrite, new System.Threading.CancellationToken(false), null);
      LiveOperationResult res= await client.BackgroundUploadAsync("me/skydrive",
                                                                  new Uri("/shared/transfers/cert.cer", UriKind.Relative),
                                                                  OverwriteOption.Overwrite);
      linkTextBlock.Text = "Done";

As mentioned before, the TextBlock never Displays "Done". It makes no difference if the UploadAsync or BackgroundUploadAsync method is used.

A: BackgroundUploadAsync uses Windows Phone background file transfers which is an intelligent file upload & download scheduling system. Whereas UploadAsync  uses immediate HTTP file uploads and downloads.
By using Background file transfers you're agreeing to the following limitations on your upload:

Maximum upload file size
Over cellular connection - 5 MB
Over Wi-Fi connection with battery power - 20 MB
Over Wi-Fi connection with external power - 100 MB

There are also limits on the maximum number of queues uploads & downloads and other limitations. Read the full documentation @ http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202955(v=vs.105).aspx
All of these limitations are probably causing your async await to wait. Even though it's a pain the limits set forth by background file transfers lead to the best user experience (i.e. uplaods when the app is closed), best battery life and best cellular data usage. Ultimately it's up to your app to decide if you want to use straight up WebRequests (uploadAsync) or background file transfers (BackgroundUploadAsync).


text:
Q: Question on Hartogs's Extension Theorem Does Hartogs's extension theorem hold if one replaces the word holomorphic by analytic (of course still in several variables)?
For Hartogs's Extension Theorem see here:
http://en.wikipedia.org/wiki/Hartogs'_extension_theorem
If yes, is there any reference ?
Thanks
bernard

A: When you use the word analytic, do you mean (1) meromorphic, (2) holomorphic, (3) real analytic, or (4) something else? If (1), this is known as the Levi extension theorem, (2) the Hartogs extension theorem, (3) this is false, (4) you need to be more specific. If you want proof that analytic functions are holomorphic, that depends on how you define analytic. If you define analytic as being solutions to the Cauchy--Riemann equations, and holomorphic as being given locally by convergent complex Taylor series, every book on several complex variables (for example, Krantz, Function Theory of Several Complex Variables, section 1.2, p. 29) proves the equivalence. Krantz also considers several other possible definitions of the word holomorphic and proves equivalence of all of them.

A: Just a long comment (and a very partial positive answer).
I gather you meant "real-analytic". As already observed by others, the corresponding Hartogs extension theorem fails for $u\in\mathcal{C}^{\omega}(\Omega\setminus K)$, $\Omega$ a domain in $\mathbb{C}^n$ and $K\subset\Omega$ compact.
But, if $u$ is assumed to be pluriharmonic and $\Omega\setminus K$ simply connected, then $u$ has a pluriharmonic conjugate $v$ on $\Omega\setminus K$, so that you can apply Hartogs theorem to the holomorphic function $u+\mathrm{i}v$ thus obtaining a (pluriharmonic hence real-analytic) extension $\tilde{u}\in\mathcal{C}^{\omega}(\Omega)$.


text:
Q: What are Virtual Methods? Why would you declare a method as "virtual".
What is the benefit in using virtual?

A: Virtual methods are similar to abstract methods in base classes except their implementation on derived classes is optional. Also you could put logic in virtual method and override these in derived classes.

A: The Virtual Modifier is used to mark that a method\property(ect) can be modified in a derived class by using the override modifier.
Example:
class A
{
    public virtual void Foo()
       //DoStuff For A
}

class B : A
{
    public override void Foo()
    //DoStuff For B

    //now call the base to do the stuff for A and B
    //if required
    base.Foo()
}

A: Even if you don't plan to derive from the class, marking the method virtual may be necessary in order to mock the class.  Some mocking frameworks only allow you to mock virtual methods.  Note that methods implementing an interface are virtual implicitly.
I use RhinoMocks which has this restriction and have taken to marking my methods virtual by default for just this reason.  For me, this is probably the biggest reason to use virtual methods as the cases where inheritance comes into play are much less frequent.

A: Virtual allows an inheriting class to replace a method that the base class then uses.
public class Thingy
{
    public virtual void StepA()
    {
        Console.Out.WriteLine("Zing");
    }

    public void Action()
    {
        StepA();
        Console.Out.WriteLine("A Thingy in Action.");
    }
}

public class Widget : Thingy
{
    public override void StepA()
    {
        Console.Out.WriteLine("Wiggy");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Thingy thingy = new Thingy();
        Widget widget = new Widget();

        thingy.Action();
        widget.Action();

        Console.Out.WriteLine("Press any key to quit.");
        Console.ReadKey();
    }
 }

When you run the Program your output will be:
Zing
A Thingy in Action.
Wiggy
A Thingy in Action.

Notice how even though Widget called the Action() method defined at the Thingy level, internally Thingy called Widget's StepA() method.
The basic answer is it gives inheritors of a class more flexibility.  Of course, you've got to engineer your class well or it could weak havoc.

A: A short question, a short answer!
Qualify your method as "virtual" if you think you will inherit of the class it belongs to.
A longer answer: "virtual enables you to override, to give another meaning of your method in a derived class.

A: In order to be able to override it in inheriting classes.
Check out the MSDN entry for the keyword. That explains it more in depth.

A: A virtual method is a type of method where the actual method calls depends on the runtime type of the underlying object.
A non-virtual method is a type of method where the actual method called depends on the reference type of the object at the point of method invocation.

A: The runtime takes place over compile time.
When you declare a method as virtual, declaring it in derived class require you to add a override or new modifier.
we can see that when TrySpeak. Passing in child and father, both call Speak of father, while TryScream, would call each method.
To understand this, there are some things we should know, in an instance of Child, There are two Scream methods from Child class or Father class. We could either call the Scream  from Child class or Father class.
Because Virtaul Modifier mark the method so it can be overriding by the derived class, which means even the Scream is called from Father class, it is overriden, it would be defferent if you use new modifier.
using System;
class Father
{
    Speak()
    {
        Console.Writeline("Father is speaking")
    }
    virtual Scream()
    {
        Console.Writeline("Father is screaming")
    }
}
class Child: father
{
    Speak()
    {
        Console.Writeline("Child is speaking")
    }
    override Scream()
    {
        Console.Writeline("Child is screaming")
    }
}
class APP
{
    public static void Main()
    {
        // We new two instances here
        Father father = new Father();
        Child child = new Child();
        // Here we call their scream or speak through TryScream or TrySpeak
        TrySpeak(father);
        TrySpeak(child);
        //>>>"Father is speaking"
        //>>>"Father is speaking"
        TryScream(father);
        TryScream(child);
        //>>>"Father is screaming"
        //>>>"Child is screaming"
    }
    // when your method take an Parameter who type is Father
    // You can either pass in a Father instance or
    // A instance of a derived Class from Father
    // which could be Child
    public static void TrySpeak(Father person)
    {
        person.Speak();
    }
    public static void TryScream(Father person)
    {
        person.Scream();
    }
}

A: In C#, for overriding the base class method in derived class, you have to declare base class method as virtual and derived class method as override as shown below:
using System;
namespace Polymorphism
{
 class A
 {
 public virtual void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A
 {
 public override void Test() { Console.WriteLine("B::Test()"); }
 }

 class C : B
 {
 public override void Test() { Console.WriteLine("C::Test()"); }
 }

 class Program
 {
 static void Main(string[] args)
 {

 A a = new A();
 B b = new B();
 C c = new C();
 a.Test(); // output --> "A::Test()"
 b.Test(); // output --> "B::Test()"
 c.Test(); // output --> "C::Test()"

 a = new B();
 a.Test(); // output --> "B::Test()"

 b = new C();
 b.Test(); // output --> "C::Test()"

 Console.ReadKey();
 }
 }
}

You can also mix the method hiding and method overriding by using virtual and new keyword since the method of a derived class can be virtual and new at the same time. This is required when you want to further override the derived class method into next level as I am overriding Class B, Test() method in Class C as shown below:
using System;
namespace Polymorphism
{
 class A
 {
 public void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A
 {
 public new virtual void Test() { Console.WriteLine("B::Test()"); }
 }

 class C : B
 {
 public override void Test() { Console.WriteLine("C::Test()"); }
 }

 class Program
 {
 static void Main(string[] args)
 {

 A a = new A();
 B b = new B();
 C c = new C();

 a.Test(); // output --> "A::Test()"
 b.Test(); // output --> "B::Test()"
 c.Test(); // output --> "C::Test()"

 a = new B();
 a.Test(); // output --> "A::Test()"

 b = new C();
 b.Test(); // output --> "C::Test()"

 Console.ReadKey();
 }
 }
}

GOLDEN WORDS:
The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class.
The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into derived class.
The new keyword is used to hide a method, property, indexer, or event of base class into derived class.
ENJOY :-)

A: Virtual Methods on MSDN

The virtual keyword is used to modify
  a method or property declaration, in
  which case the method or the property
  is called a virtual member. The
  implementation of a virtual member can
  be changed by an overriding member in
  a derived class.
When a virtual method is invoked, the
  run-time type of the object is checked
  for an overriding member. The
  overriding member in the most derived
  class is called, which might be the
  original member, if no derived class
  has overridden the member. (For more
  information on run-time type and most
  derived implementation, see 10.5.3
  Virtual methods.)
By default, methods are non-virtual.
  You cannot override a non-virtual
  method.
You cannot use the virtual modifier
  with the following modifiers:
static abstract override
Virtual properties behave like
  abstract methods, except for the
  differences in declaration and
  invocation syntax.

*

*It is an error to use the virtual modifier on a static property.

*A virtual inherited property can be overridden in a derived class by
  including a property declaration that
  uses the override modifier.

A: Needless to say, virtual methods come in handy when your code is trying to abide with the Open Closed Principle
Read More about the Open Closed Principle here, Uncle Bob's original OCP whitepaper.
Also pls be aware that methods are not virtual by default in C# unlike Java.

A: Virtual functions are the functions that doesn't really exists.The derived class can modify the virtual function by overriding it.Virtual functions are one of the way to achieve run time polymorphism
    public class sample {
      public virtual void fun(){
        Console.WriteLine("base sample class \n");
      }
    }
    public class A : sample{
      public override void fun(){
        Console.WriteLine("Class A \n");
      }
    }
    public class B : sample{
      public override void fun(){
        Console.WriteLine("Class B \n");
      }
    }
    class run{
      public static void main(String[] args){
        sample obj = new sample();
        sample obj1 = new A();
        sample obj2 = new B();
        obj.fun();
        obj1.fun();
        obj2.fun();
      }
    }


text:
Q: HTML5 input type=number should allow only unsigned integer How to prevent other number related characters other than unsigned integer
For example - e ...etc
Demo: http://codepen.io/anon/pen/jrEGrK

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<form action="#" class="container">

  <input class="form-control" onkeyup="value=isNaN(parseFloat(value))?1000:value" type="number" value="0">
</form>

A: If you're ok with HTML5 why not use the pattern attribute and define a number only regex?
<input pattern="[1-9][0-9]*" ...>

A:

function validate(e) {
  var ev = e || window.event;
  var key = ev.keyCode || ev.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]/;
  if( !regex.test(key) ) {
    ev.returnValue = false;
    if(ev.preventDefault) ev.preventDefault();
  }
}
<input type='text' onkeypress='validate(event)' />

A: Taking a clue from your implementation, what if you use a regular expression like that:
onkeyup="value=/^\d+$/.test(value)?value:1000"


text:
Q: Electron: Cannot find DOM elements from child window I am trying to send a parameter and its property from the main process to the renderer process, then append that property value as a string onto a div in my html/ child window. However, the renderer process cannot find the Id I have specified and returns the error:
Cannot read property 'append' of null at EventEmitter.<anonymous>
I thought I could get around this error by sourcing the renderer file to my html but that makes the html look for other elements that are also sourced to that renderer process as I have multiple html files connected to it and it doesn't work either way.
So after this, I created another javascript file specifically for that html window but that window cannot recieve events from the main process.
Here is my current code:
HTML
 <div id="brst_files">
       </div>

<script type="text/javascript" src="./renderer.js">
    </script>
    <script>
    //Open the dialog for burst button
    let brstfile = document.getElementById('brst_add_files')
     brstfile.addEventListener('click', function(event){
      console.log('recieved')
      ipcRenderer.send('brst_add_files')
      console.log('add file')
    })

    ipcRenderer.on('brstfiles', function(event){
    console.log('html recieved')
    document.getElementById('brst_files').append('data.filePath')
    console.log('file path recieved')
  })
    </script>

Main
 //Open burst window dialog menu
 ipcMain.on('brst_add_files', function(event){
  console.log('adding files')
  dialog.showOpenDialog({properties:['openFile','dontAddToRecent','multiSelections'],
  filters: [
    { name: 'All Files', extensions: ['*'] }

    //Recieve and send the file path data
  ]}).then((data) => {
  console.log(data.filePaths);
  mainWindow.webContents.send('brstfiles', data.filePaths)
  console.log('file path sent')
});
})
}

Renderer
//Burst create window
let brstwindow = new BrowserWindow({
  width:400,
  height:415,
  frame: false,
  useContentSize: true,
  backgroundColor: '#00000000',
  alwaysOnTop: false,
  transparent: true,
  resizable: true,
  webPreferences: {
    nodeIntegration: true,
    enableRemoteModule: true,
    useContentSize:true
  }
 });

 brstwindow.loadURL(url.format({
  pathname: path.join(__dirname, 'Burstcreate.html'),
  protocol: 'file',
  slashes:true

}));
brstwindow.webContents.openDevTools()
brstwindow.hide()

//Open the burst button window
let brstopen = document.getElementById('burstbtn')
brstopen.addEventListener('click', function(event){
brstwindow.show()
})

//Recieve file path from main and append to div
ipcRenderer.on('brstfiles', function(event){
  console.log('html recieved')
  document.getElementById('brst_files').append('data.filePath')//I know this just appends a string
  console.log('file path recieved')
})

Other renderer
const { ipcRenderer, webContents} = require('electron');
const app = require('electron').remote.app;
const electron = require('electron');
const { get } = require('http');
const BrowserWindow = electron.remote.BrowserWindow;
const path = require('path');
const { on } = require('process');
const {dialog} = require('electron')
const url = require('url');

//Recieved the file path back from main and appending it to div
ipcRenderer.on('brstfiles', function(event){
    console.log('html recieved')
    document.getElementById('brst_files').append('data.filePath')
    console.log('file path recieved')
  })

So my main question is: How can I find DOM elements in a child window from renderer? Should I do everything from the main process?
Extra question: How do I recieve parameters from main process in the renderer process?


text:
Q: Why is Emit faster than Reflection I've been reading a lot about emit and how it's so much faster than reflection but haven't been able to find out why. I understand emit is injecting IL code but why is this faster than reflection when doing property mapping like an ORM?
Referring to this sort of use case:
Emit mapper vs valueinjecter or automapper performance

A: Reflection uses general purpose code and metadata to perform its actions. Reflection calls will usually do a lot of runtime checking, for example if the property you want to access really belongs to the type of the object you provided. Or that the parameters you want to pass  into a method are compatible with the signature. And of course a lot of boxing and unboxing because everything is just treated as a object.
On the other hand reflection emit generates code specifically for the task you want to perform, checks a lot of things only once during compilation and will then execute as fast as every code you have written in source code.
There is obviously quite some overhead in dynamically generating code but if you do this only once and then use this code many times it will be faster in the long term. It's the same for regular expressions. You can just use them and your expression will essentially be interpreted during operations, but if you have to use the same expression many times you can specify the compiled option and the library will produce code tailored to your expression and then you can just execute it without the need to interpret the expression every time.
So in essence reflection is like interpreting code, reflection emit is (like) compiling it.


text:
Q: undefined method `model_name' for Project:Class I've looked through all the related questions but nothing's new for me here.
I have a Project controller with "new" action
class ProjectsController < ApplicationController
  def new
    @newproject = Project.new
  end
end

Project is a simple class, not active record:
class Project
  attr_accessor :name, :description
  def initialize
    @name = ""
    @description = ""
  end
end

I get the error "undefined method `model_name' for Project:Class"
This is an erb file sample:
<%= form_tag(@newproject)  do |f| %>
  <%= f.label :name %>:
  <%= f.text_field :description %>

<% end %>

A: if Project is not an active record subclass, you need these and you can use form_for
class Project
  extend ActiveModel::Naming
  include ActiveModel::Conversion
  def persisted?
    false
  end
  ...
end

view:
<%= form_for(@newproject)  do |f| %>
  <%= f.label :name %>:
  <%= f.text_field :description %>

<% end %>

A: class Project < ActiveRecord::Base

A: just for the record - here is the Railscast for that issue:
http://railscasts.com/episodes/219-active-model

A: I had a similar issue because my class wasn't using ActiveRecord; adding the following to my class solved it: include ActiveModel::Model


text:
Q: isotope not opening to specified class I am trying to bypass isotope opening all items on page load. Rather I would like to have a certain category open when page is loaded. I have set the first button as class="button is-checked" but it is still loading the full selection rather than the data-filter associated with that button.
You can see an example here: http://thesourcedirect.net/tour_sc2.php
Code is as follows:

  <button style="border-bottom: solid 3px #000000;" class="button is-checked" data-filter="*">Full Tour</button>
  <button style="border-bottom: solid 3px #0a50ff;" class="button is-checked" data-filter=".rubber">Rubber</button>
  <button style="border-bottom: solid 3px hsl( 121, 100%, 36%);" class="button" data-filter=".plastic">Plastic</button>
  <button style="border-bottom: solid 3px hsl( 121, 0%, 52%);" class="button" data-filter=".metal">Metal</button>
  <button style="border-bottom: solid 3px hsl( 0, 100%, 52%);" class="button" data-filter=".electronic">Electronic</button>
  <button style="border-bottom: solid 3px hsl( 51, 100%, 52%);" class="button" data-filter=".dental">Dental</button>
  <button style="border-bottom: solid 3px hsl( 31, 100%, 52%);" class="button" data-filter=".lg">Lawn & Garden</button>
  <button style="border-bottom: solid 3px hsl( 40, 100%, 34%);" class="button" data-filter=".text">Textiles</button>

Any and all help would be appreciated.
Regards,
Jacob

A: Found solution. This is the link: https://stackoverflow.com/a/12009734/2478814 Solved by entering $container.isotope({filter: '.home'});


text:
Q: Signal to forked children processes in C / Linux I have a shared variable set to 0 and then fork N processes. These processes then busy wait for the shared variable to become 1. The parent is responsible for setting this variable to 1. What's the best option here to eliminate busy waiting?
I was looking into semaphores (sem_open, etc) but my understanding is that parent will need sem_post N times so that all presses can proceed.

A: One way would be to create a pipe in the parent process. Each child process closes the write end of the pipe, then calls read (which blocks). When the parent process is ready, it closes both ends of its pipe. This makes all the children return from read and they can now close their read end of the pipe and proceed with their code.

A: For situations like this, I sometimes use atomic operation. You can use atomic flags to notify sub-process, but it creates busy-waiting. So you can use it on a very special cases.
Other method is to create an event with something like pthread_cond_broadcast() and pthread_cond_timedwait(). All sub-process wait on your condition. When you are ready to go, unlock it on parent process.


text:
Q: Concave function with oblique asymptote
I'm looking for a continuous concave function $f:[0,\infty)\to [0,\infty)$ such that $f(0)=0$ and there exists some $\alpha>0$ with $\lim_{x\to \infty}\frac{f(x)}{x} =\alpha$ and $\forall x>0, f(x)>\alpha x$.

I haven't been able to come up with such a function off the top of my head. Intuitively, $f$ must have an inflection point.
Context : a microeconomics professor suggested such a function exists in a lecture

A: For example, combine  $e^{-x}$ with $ax+b$:
$$f:x \mapsto 3x+2(1-e^{-x})$$
Properties:

*

*for $x\in [0, \infty)$ we have $3x \in [0, \infty)$ and
$e^x \in [1,\infty) \implies e^{-x} \in (0, 1] \implies (1-e^{-x}) \in [0,1)$
hence $f(x) \in [0, \infty)$, as required;

*$f(0) = 3\cdot 0 + 2(1-\exp(-0)) = 3\cdot 0 + 2(1-1) = 0+0 = 0$, as required;

*$\lim\limits_{x\to\infty} f(x)/x = \lim [3x/x+2/x - 2\exp(-x)/x] = 3+0-0 = 3$,
hence there exists $\alpha = \lim_{x\to\infty}\tfrac{f(x)}x$, which is greater than zero, as required;

*for all positive $x$ we have $\exp(-x)<1$, so $\delta(x) = (1-e^{-x})>0$,
hence $f(x) = \alpha x + 2\delta(x) > \alpha x$, as required;

and it clearly is continuous, as required.
Additionally,
$$f'(x) = 3 + e^{-x} > 3 > 0$$
$$f''(x) = -e^{-x} < 0$$
so $f$ is increasing and concave (which properties were not required in the question, but concavity was mentioned in the title).
EDIT
As for the additional question from the comment:

Can we have $\lim_x (f(x)−\alpha x)=0$?

Yes, we can.
Suppose $f(x) = \alpha x+ g(x)$. Then $g(x)$ will have properties:

*

*$g(x)>0$ for $x>0$ and $g(0) = 0$;

*$\lim_x g(x) = 0$.

An example:
$$g(x) = x\cdot \exp(-x)$$
see it in WolframAlpha
This, however, is not concave – at some point $(x=1)$ it starts decreasing, but to approach its asymptote it slows down the decreasing rate at some other point $(x=2)$, which means it becomes convex above $x=2$.


text:
Q: Accessing Collections through blade foreach
@foreach ($despatchItems as $despatchItem)
            {{dd($despatchItem)}}
             <input type="text" class="form-control" id="inputQty"  name="qty" value="{{$despatchItem->qty}}">
@endforeach

I need to get the qty of these arrays(3 Collections are there in this case)

The Below worked for me
@foreach ($despatchItems as $collections)
    @foreach($collections as $collection)
        @foreach($collection as $despatchItem)
            <input type="text" class="form-control" id="inputQty" name="qty" value="{{$despatchItem->qty}}">
        @endforeach
    @endforeach
@endforeach

My controller method looks like this
public function create($jobId)
{

  $job = Job::find($jobId);

  $despatches = $job->despatches;

  foreach ($despatches as $despatch) {
    $despatchItems['despatchItems'][] = $despatch->despatch_items;
  }

  return view('employees.invoices.create',compact('despatchItems','job'));
}

A: You have collection of DespatchItem
@foreach ($despatchItems as $despatchItem)
   {{dd($despatchItem->qty)}}
 @endforeach

If you need array of qty, try this:
$despatchItems->map(function ($despatchItem) {
    return $despatchItems->qty;
})


text:
Q: Can disabling secure boot affect Windows? Can disabling secure boot affect Windows OS? I want to disable it to install Linux. I use Windows 10 as my main OS now so all my data would be potentially lost if there is some problem with Windows after disabling secure boot.
Has anybody experience with this?

A: No.
Disabling/enabling SecureBoot doesn't affect already installed operating systems in any way.
The only thing SecureBoot (if enabled) does is to verify that the Operating Systems bootloader has a valid security certificate and it refuses to boot it it doesn't have one.
With SecureBoot disabled that check is simply skipped and the UEFI bios will happily load any operating system, regardless of whether or not it has a certificate.
I have personally installed at least a 100 systems (Windows and Linux) with SecureBoot off and enabled SecureBoot later without any issues.
(Had to switch it of because my installation medias are created with Rufus which uses a UEFI NTFS driver that doesn't work under Secure Boot.)
EDIT: As Akeo pointed out in the comments, a few hours after I originally posted this answer Rufus was updated and now works WITH SecureBoot enabled.


text:
Q: Aggregate the same column in multiple different ways I am trying to get an array of categories associated with each product and then also get the top-level parent category of each product in another column, which by my logic is finding the same values for the categories array, but only selecting where parent_id is NULL which should pull back only one value and 1 record per id.
I really don't know the best way to structure this query. What I have kind of works, but it also shows NULL values in the parent category column for the categories that do have a parent ID and makes a second record for each product because I am forced to put it in the group by. Basically, I think I am not doing this in the correct or most efficient way.
Desired result:
+----+----------------+------------------+------------------------------------------------+------------------+
| id | name           | category_ids     | category_names                                 | parent_category  |
+----+----------------+------------------+------------------------------------------------+------------------+
| 1  | Product Name 1 | {111,222,333}    | {Electronics, computers, computer accessories} | Electronics      |
+----+----------------+------------------+------------------------------------------------+------------------+

My current query (which is not ideal):
select p.id,
p.name,
array_agg(category_id) as category_ids,
regexp_replace(array_agg(c.name)::text,'"|''','','gi') as category_names,
c1.name as parent_category
from products p
join product_categorizations pc  on pc.product_id = p.id
join categories c  on pc.category_id = c.id
full outer join (
   select name, id from categories
   where parent_id is null and name is not null
   ) c1 on c.id = c1.id
group by 1,2,5;

+----+----------------+------------------+-----------------------------------+------------------+
| id | name           | category_ids     | category_names                    | parent_category  |
+----+----------------+------------------+-----------------------------------+------------------+
| 1  | Product Name 1 | {111}            | {Electronics}                     | Electronics      |
+----+----------------+------------------+-----------------------------------+------------------+
| 1  | Product Name 1 | {222,333}        | {computers, computer accessories} | NULL             |
+----+----------------+------------------+-----------------------------------+------------------+

A: Replace the FULL JOIN with an aggregate FILTER clause:
SELECT p.id
     , p.name
     , array_agg(pc.category_id) AS category_ids
     , string_agg(c.name, ', ')  AS category_names  -- regexp_replace .. ?
     , min(c.name) FILTER (WHERE c.parent_id IS NULL) AS parent_category
FROM   products                p
JOIN   product_categorizations pc ON pc.product_id = p.id
JOIN   categories              c  ON pc.category_id = c.id
GROUP  BY p.id;
See:

*

*Aggregate columns with additional (distinct) filters
(Why would you add AND name IS NOT NULL? Either way, min() ignores NULL values anyway.)
While aggregating all products, and while referential integrity is enforced, this should be a bit faster:
SELECT p.name, pc.*
FROM   products p
JOIN  (
   SELECT pc.product_id AS id
        , array_agg(pc.category_id) AS category_ids
        , string_agg(c.name, ', ')  AS category_names
        , min(c.name) FILTER (WHERE c.parent_id IS NULL) AS parent_category
   FROM   product_categorizations pc
   JOIN   categories              c  ON pc.category_id = c.id
   GROUP  BY 1
   ) pc  USING (id);

The point being that product only joins after aggregating rows.
Aside: "name" is not a very helpful column name. Related:

*

*How to implement a many-to-many relationship in PostgreSQL?


text:
Q: Using fonts with Rails 4.2.4 I'm trying to use a particular font in a Rails 4.2.4 app and nothing is working--it stubbornly refuses to show up.  I've spent a few hours on it, and I don't know what I'm doing wrong.
The font is located at app/assets/fonts/comic_andy.tff.
SCSS (located at app/assets/stylesheets/sass/application.css.scss):
@font-face {
font-family: "comic_andy";
src: font-url('comic_andy.ttf');
src: font-url('comic_andy.ttf'), format('truetype');
}

In the browser, the SCSS compiles to this CSS:
@font-face {
font-family: "comic_andy";
src: url(/fonts/comic_andy.ttf);
src: url(/fonts/comic_andy.ttf), format("truetype");
}

Isn't it supposed to be compiling to assets/comic_andy.ttf?  I'm newer to Rails and although I get what the asset pipeline is, it's still proving tricky to wrap my head around enough to use very efficiently.
I've read through Rails 4 - Custom Fonts, How to use fonts in Rails 4 and several other Stack Overflow questions related to fonts/Rails/the asset pipeline, and tried many of the suggestions, including (but not limited to!) adding config.assets.paths << Rails.root.join('app', 'assets', 'fonts') to application.rb (nope), trying asset-url (nope), font-url (nope), and plain url (nope), and restarting the server several times after rake assets:clobber (nope). :(

A: Don't change the assets path
If you put your resources into app/assets, you're all set, as mentioned here.

The default locations are: the images, javascripts and stylesheets directories under the app/assets folder, but these subdirectories are not special - any path under assets/* will be searched.

Use asset-url or font-url
If you refer to The Asset Pipeline page on Ruby on Rails guides, you'll see the adequate method here is to use asset-url (or font-url) as in:
@font-face {
    font-family: 'comic_andy';
    src: asset-url('comic_andy.ttf') format('truetype');
}

On your development environment, it should compile as:
@font-face {
    font-family: 'comic_andy';
    src: url(/assets/comic_andy.ttf) format("truetype");
}

NB: the proper format for .ttf files is format("truetype").
Make sure your font format is supported
If things still don't work, maybe there's a problem with your ttf file (my project is using the woff format) and you should maybe use a service such as Font Squirrel Webfont generator to fix it.

A: Solved the problem, finally.  F I N A L L Y.
The SASS:
@font-face {
    font-family: "comic_andy";
    src: font-url('comicandy.ttf');
    src: font-url('comicandy.ttf'), format("truetype"); }

Application.rb:
config.assets.paths << Rails.root.join("app", "assets", "fonts")
config.assets.enabled = true

Asshat Pipeline wasn't compiling the SASS correctly, because I was missing config.assets.enabled = true.  Somewhere along the line, the font also got renamed.  I don't know why or how that helped solved the issue, but it appeared to somehow help solve the issue.


text:
Q: Mockito swallows up stack trace? Why does Mockito swallow up stack traces? For example, if I have a
public class Foo
{
    public void foo()
    {
        bar();
    }

    public void bar()
    {
        baz();
    }

    public void baz()
    {
        throw new RuntimeException();
    }
}

and a test such as
public class MockTest
{
    @Test
    public void test()
    {
        Mockito.spy(new Foo()).foo();
    }
}

the exception thrown always looks like

java.lang.RuntimeException
    at Foo.baz(Foo.java:17)
    at MockTest.test(MockTest.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

** So, where is all the stuff between
Foo.baz(Foo.java:17)
MockTest.test(MockTest.java:11)

?
(The example provided here is a just a simplification -- I'm dealing with a lot more indirections, classes, and so forth. I can't have Mockito swallowing up the critical parts of a partial mock stack trace...)

A: YES, mockito cleans stacktraces !
The piece of code at work StackTraceFilter
There are different ways to disable that

*

*Since Mockito 1.10.10, provide your own StackTraceCleanerProvider via the mockito extension mechanism (create a resource file mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider with the qualified name of your implementation)

*Override the cleansStackTrace method in a custom IMockitoConfiguration, look there for more information.

A: This is the magic of proxies.
The javadoc of [Mockito.spy()][1] states

Creates a spy of the real object. The spy calls real methods unless they are stubbed.

So spy() returns a mock object, which is a proxy. It is a sub class of Foo so it inherits the methods, but it wraps their execution in a interceptor method. This method has a try catch block which catches any exception thrown in the actual method invocation. The catch block then uses a ConditionalStackTraceFilter to clean up the stack trace. To do this, it uses a StackTraceFilter which in the comments of its filter(..) method states
/**
 * Example how the filter works (+/- means good/bad):
 * [a+, b+, c-, d+, e+, f-, g+] -> [a+, b+, g+]
 * Basically removes all bad from the middle. If any good are in the middle of bad those are also removed.
 */

The call stack at the invocation of baz() is something like (super simplified)
at Foo.baz()
at FooPROXY.baz()
at Foo.bar()
at FooPROXY.bar()
at Foo.foo()
at FooPROXY.foo()
at MockTest.test()

All the PROXY stack trace elements, which are the proxies and the interceptors involved, and everything in between get removed. So you get the result you see.

Note that Junit also cleans it up so as not to show its internals.


text:
Q: css link change every day automatically I have a file with same css link to change every day at 12 midnight. my file link is like this
<link rel="stylesheet" href="<?php $filelocation->fetchdir($css); ?>blue.css">

I want to blue.css to change next week to green.css and the following week yellow.css and then the circle will start over again
How can I do this? please

A: Store your colors in an array, then get the current timestamp and divide it by 7 days. Then get modulo of the result and you're done:
<?php
// (...)
$colors = array('blue', 'green', 'yellow');
$chosenColor = intval(time() / (60 * 60 * 24 * 7)) % count($colors); // 60 seconds, 60 minutes, 24 hours, 7 days, 3 color variants

?>
<link rel="stylesheet" href="<?= $filelocation->fetchdir($css) . $colors[$chosenColor]; ?>.css">

Depending on what color you want to show on what week, change their order in the array.
Note: When you opened the php tag in the href attribute, you used <?php. Assuming that you wanted to output the result, I changed it to <?= which is exactly the same as <? echo.

A: You can use date function to get current week of year and use modulo to choose proper color:
<?php
function color() {
  switch(date('W') %3 ) {
   case 0: return 'blue.css';
   case 1: return 'greeen.css';
   case 2: return 'yellow.css';
  }
}
?>
<link rel="stylesheet" href="<?= $filelocation->fetchdir($css) . color(); ?>


text:
Q: rerouting a normal phone call to skype I am a mobile/web developer but Im trying to see if there is any way this is possible:
Rerouting an incoming telephone call to skype or any other voice chat application?
Can anyone explain what technologies/ APIs are available to do something like this?
Thanks
Apologize if this question is broad or out of context here. Please let me know where to post if so.
Thanks

A: Take a look at SipToSis. This will not only solve the problem (GPL licensed out-of-the-box working product), but most of all studying it will help you understand the APIs used.


text:
Q: Text slider on easyer way I try on a easyer way to do my own text slidder on my way to learn js but I don't have any ideea how to continue. On my console there are my array devided by 5 (I need to see just 5 by 5 not all in one page). Now I try to link my first object (that contain 5 elements) with my first bullet, then second object with my second bullet, so on...
I would like when you make click on first bullet, to see 1-5 articols, when you click on second bullet, to see 5-10 articole, so on. I need my "active" class that is now on every bullet to appear just on the bullet text activ you see it. Al last, I need that slider to go byself every 5 seconds to move from first bullet, to second, to third, so on.
If you may help me it will be greate :)

(function(){

 var box = document.getElementById("box");
 var bulletContainer = document.getElementById("bullet-cont");
 doRequest();

 setInterval(function(){
  doRequest();
 }, 180000);

 function doRequest(){
  $.getJSON("https://gafwebmaster.github.io/json/json2.json", function(data){
   afiseaza(data);
   arata(getBulletsNumber(data));
   newsDevide(data, 5);
  }
 )}

 function afiseaza (ceva) {
  box.innerHTML = "";
  var continut = "";
  for (i=0; i<ceva.news.length; i++){
   var stire = ceva.news[i];
   continut = "

";
   continut += "
" + stire.title + "
";
   continut += "
" + stire.details + "
";
   continut += "
";
   box.innerHTML += continut;
  }
 }

 function getBulletsNumber(calculare){
  return calculare.news.length / 5;
 }

 function arata(bullets){
  bulletContainer.innerHTML = "";
  for (i=0; i<bullets; i++){
   bulletContainer.innerHTML += '

';
  }
 }

 function newsDevide(ourData, nr) {
        var a = [];
        var counter = nr;
        for (var i = 0; i < ourData.news.length; i += nr) {
            a.push(ourData.news.slice(i, counter));
            counter += nr;
        }
        counter = nr;
        for (j = 0; j < a.length; j++) {
            console.log(a[j]);
        }
        return a;
    }
})()
/*Css reset*/
#home html,
#home body,
#home h1,
#home h2,
#home div,
#home section,
#home p{
 border: 0;
 font-size: 100%;
 font: inherit;
 margin: 0;
 padding: 0;
 vertical-align: baseline;
}

/*General style*/
body *{
 box-sizing: border-box;
}

html{
 font-size: 16px;
}

#home {
 font-family: 'Roboto', sans-serif;
}

#home h1{
 font-size: 1.3rem;
 padding: 10px 20px;
 display: inline-block;
}

#home h2{
 color: #0f5959;
 font-size: 1.1rem;
}

#home p{
 color: #638ca6;
 font-size: 0.8rem;
}

#home section{
 max-width: 280px;
 margin: 0 auto;
}

#home #box{
 border: 1px solid #0f5959;
 margin-top: -1px;
 padding: 20px;
}

#home #topWidget{
 border: 1px solid #0f5959;
 position: relative;
}

#home .latestNew{
 margin-bottom: 15px;
}

#home #topWidget div.nav{
 position: absolute;
 top: 30%;
 right: 20px;
}

#home #topWidget .bullet{
 background:#bfd70e;
 border-radius:50%;
 width:16px;
 height:16px;
 border:1px solid #679403;
 display: inline-block;
 margin-left: 5px;
}

#home #topWidget .selected{
 background:#666;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Widget Code</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

Latest news


text:
Q: T-SQL numeric(x, y) equivalent data type in Access I have a table definition (from SQL Server) which has columns like abc numeric(22,6) or bce numeric(9,5), or mnp numeric(20,10).
I have to keep those precisions. Which data type is equivalent in Access 2010?
I tried Double but it doesn't work for my target table (which has the data types from above).
I thought perhaps Decimal would work, but this also throws a conversion error when I export the data using SSIS.
Maybe I'm not setting this up correctly. What would you use for a numeric(22,6) in Access? decimal (precision, scale, decimal places)? I tried with (22, 6, auto).

A:
What would you use for a numeric(22,6) in Access?

Decimal(22,6) is definitely the corresponding field type in Access. I just used the
External Data > Import & Link > ODBC Database

feature in Access 2010 to import a SQL Server table like this
CREATE TABLE [dbo].[NumericTest](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [numericcol] [numeric](22, 6) NULL,
    ...

and the resulting Access table did indeed have a Decimal(22,6) column ...

... so it is possible.


text:
Q: Wordpress: using $wpdb->get_results instead of mysqli_query causes empty var I'm trying to translate a query built with mysqli_query in a wordpress query.
The problem is that using $wpdb->get_results I'm getting no results at all. I've even tried with $wpdb->query and $wpdb->get_var with any results too.

$MYSQLi contains the database informations as you can imagine
  Of course all the variables are fine! They have the correct values inside.

The old query
                $check_last_conversation = mysqli_query($MYSQLi,"select * from vp_pms_messages inner join vp_pms_group_users on vp_pms_messages.id = vp_pms_group_users.message_id and vp_pms_messages.group_id = vp_pms_group_users.group_id where vp_pms_group_users.from_username = '".mysqli_real_escape_string($MYSQLi,$session_username)."' and vp_pms_group_users.from_del = '".mysqli_real_escape_string($MYSQLi,'0')."' or vp_pms_group_users.to_username = '".mysqli_real_escape_string($MYSQLi,$session_username)."' and vp_pms_group_users.to_del = '".mysqli_real_escape_string($MYSQLi,'0')."' group by vp_pms_messages.group_id ".$order_data_by_this." desc limit 8");

The Wordpress one
                $check_last_conversation = $wpdb->get_results("select * from ".$wpdb->prefix."vp_pms_messages inner join ".$wpdb->prefix."vp_pms_group_users on ".$wpdb->prefix."vp_pms_messages.id = ".$wpdb->prefix."vp_pms_group_users.message_id and ".$wpdb->prefix."vp_pms_messages.group_id = ".$wpdb->prefix."vp_pms_group_users.group_id where ".$wpdb->prefix."vp_pms_group_users.from_username = '".$session_uid."' and ".$wpdb->prefix."vp_pms_group_users.from_del = '0' or ".$wpdb->prefix."vp_pms_group_users.to_username = '".$session_uid."' and ".$wpdb->prefix."vp_pms_group_users.to_del = '0' group by ".$wpdb->prefix."vp_pms_messages.group_id ".$order_data_by_this." desc limit 8");

Could it be some encoding issue? Cn you give me some directions? Thanks.

A: I assume your wp table prefix is vp_. If that's so, by doing $wpdb->prefix."vp_pms_messages you will get vp_vp_pms_messages which is non-existent table. Same goes for other tables. You can also check your php error logs as well as use plugin called Query Monitor to see if there are any error and other debugging

A: Have you set global $wpdb in your function?
If it's not that, then check the value $wpdb->last_error after the call to see what the issue may be.


text:
Q: php call to file_get_contents() terminates script I have written a small PHP script that I am running from the command line locally in VS-Code (no browser). The script connects to a URL using file_get_contents() up to 4,000 times to download different JSON files.
After a period of time the call is made to file_get_contents(), but doesn't return and the script terminates. I have put an echo statement before and after the file_get_contents() call to try and diagnose the problem.
I thought at first it was a timeout issue, but this is not the case as I can make between 200 and 1,500 successful calls ranging from 30 to 150 seconds. It looks as if the connection is being dropped/rejected/terminated by the other end, but the problem I have is that I am unable to prevent my script from terminating. I have looked in the C:\wamp64\logs folder, but nothing is being logged.
Is there any way of determining what is causing the issue, and more importantly, prevent my script from terminating, so that it can continue.
I have not created/modified any header information for the call to file_get_contents().
foreach ($urls as $url) {
echo "URL: $url\n";
echo "Get file data\n";
$json = file_get_contents($url);
echo "Got file data\n";
}

Sample output...
Get file data
[Done] exited with code=null in 325.239 seconds

A: OK, I have finally got to the bottom of the problem. The problem was related to how it was being run in VS Code. By adding the following setting (File | Preference | Settings) to run code in the integrated terminal and not the output window, it now works :-)
{
    "code-runner.runInTerminal": true
}


text:
Q: nginx recv() failed (104: Connection reset by peer) while reading response header from upstream I have recently upgrade my magento from 1.5 to 1.9 and when ever I add a certain product to basket, I started to receive this error: 502 Bad Gateway
There were no log entries in the var/log/ folder:

So, I had a look at my nginx errors and I found the following entries in nginx-errors.log:
2015/04/09 10:58:03 [error] 15208#0: *3 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 46.xxx.xxx.xxx, server: dev.my-domain.co.uk, request: "POST /checkout/cart/add/uenc/aHR0cDovL2Rldi5zYWx2ZW8uY28udWsvdGludGktYmF0aC1wYWludGluZy1zb2FwLTcwbWwuaHRtbD9fX19TSUQ9VQ,,/product/15066/form_key/eYLc3lQ35BSrk6Pa/ HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fcgi-www-data.sock:", host: "dev.my-domain.co.uk", referrer: "http://dev.my-domain.co.uk/tinti-bath-painting-soap-70ml.html"
2015/04/09 11:04:42 [error] 15208#0: *13 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 46.xxx.xxx.xxx, server: dev.my-domain.co.uk, request: "POST /checkout/cart/add/uenc/aHR0cDovL2Rldi5zYWx2ZW8uY28udWsvdGludGktYmF0aC1wYWludGluZy1zb2FwLTcwbWwuaHRtbD9fX19TSUQ9VQ,,/product/15066/form_key/eYLc3lQ35BSrk6Pa/ HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fcgi-www-data.sock:", host: "dev.my-domain.co.uk", referrer: "http://dev.my-domain.co.uk/tinti-bath-painting-soap-70ml.html"
2015/04/09 11:05:03 [error] 15208#0: *16 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 46.xxx.xxx.xxx, server: dev.my-domain.co.uk, request: "POST /checkout/cart/add/uenc/aHR0cDovL2Rldi5zYWx2ZW8uY28udWsvdGludGktYmF0aC1wYWludGluZy1zb2FwLTcwbWwuaHRtbD9fX19TSUQ9VQ,,/product/15066/form_key/eYLc3lQ35BSrk6Pa/ HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fcgi-www-data.sock:", host: "dev.my-domain.co.uk", referrer: "http://dev.my-domain.co.uk/tinti-bath-painting-soap-70ml.html"
2015/04/09 11:12:07 [error] 15273#0: *1 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 46.xxx.xxx.xxx, server: dev.my-domain.co.uk, request: "POST /checkout/cart/add/uenc/aHR0cDovL2Rldi5zYWx2ZW8uY28udWsvdGludGktYmF0aC1wYWludGluZy1zb2FwLTcwbWwuaHRtbD9fX19TSUQ9VQ,,/product/15066/form_key/eYLc3lQ35BSrk6Pa/ HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fcgi-www-data.sock:", host: "dev.my-domain.co.uk", referrer: "http://dev.my-domain.co.uk/tinti-bath-painting-soap-70ml.html"

I have installed magento on a custom LEMP stack, here are the configurations:

*

*nginx.conf

*fastcgi_params

*dev.my-domain.co.uk.conf (nginx vhost)

*www-data.conf (php-fpm pool config)

This error only appears to be happening when I add a specific product to basket in my upgraded magento and every time the error occurs, I can see a core.XXXXX file (which is approx 350mb) in the public_html folder.
Any idea why my php-fpm is crashing like this? How can I find the cause and fix it?
Here's the last entries on my Linux (CentOS) server, when I run dmesg command:
php-fpm[14862]: segfault at 7fff38236ff8 ip 00000000005c02ba sp 00007fff38237000 error 6 in php-fpm[400000+325000]
php-fpm[15022]: segfault at 7fff38351ff0 ip 00000000005bf6e5 sp 00007fff38351fb0 error 6 in php-fpm[400000+325000]
php-fpm[15021]: segfault at 7fff38351ff0 ip 00000000005bf6e5 sp 00007fff38351fb0 error 6 in php-fpm[400000+325000]
php-fpm[15156]: segfault at 7fff38351ff0 ip 00000000005bf6e5 sp 00007fff38351fb0 error 6 in php-fpm[400000+325000]
php-fpm[15024]: segfault at 7fff38351ff0 ip 00000000005bf6e5 sp 00007fff38351fb0 error 6 in php-fpm[400000+325000]
php-fpm[15223]: segfault at 7fff8d1d5fd8 ip 00000000005c02ba sp 00007fff8d1d5fe0 error 6 in php-fpm[400000+325000]
php-fpm[15222]: segfault at 7fff8d1d5fd8 ip 00000000005c02ba sp 00007fff8d1d5fe0 error 6 in php-fpm[400000+325000]
php-fpm[15225]: segfault at 7fff8d1d5fd8 ip 00000000005c02ba sp 00007fff8d1d5fe0 error 6 in php-fpm[400000+325000]
php-fpm[15227]: segfault at 7fff8d1d5fd8 ip 00000000005c02ba sp 00007fff8d1d5fe0 error 6 in php-fpm[400000+325000]
php-fpm[15362]: segfault at 7fff3118afd0 ip 00000000005c0ace sp 00007fff3118afa0 error 6 in php-fpm[400000+325000]

I analysed the core dump with gdb and this is what I see for the first two frames: http://pastebin.com/raw.php?i=aPvB1sWv (doesn't make much sense to me)...

A: I have similar error because of PHP 5.5.23 patch (also 5.6.7). It fails on SOAP call. The only workaround I had found is downgrade php to 5.5.22. You can detect function that crashes your app by placing breakpoints.

A: For downgrading from 5.6.7 to 5.6.6:
rpm -ivhU --nodeps --force http://rpms.famillecollet.com/enterprise/6.5/php56/x86_64/php-common-5.6.6-1.el6.remi.x86_64.rpm

rpm -ivhU --nodeps --force http://rpms.famillecollet.com/enterprise/6.5/php56/x86_64/php-cli-5.6.6-1.el6.remi.x86_64.rpm

rpm -ivhU --nodeps --force http://rpms.famillecollet.com/enterprise/6.5/php56/x86_64/php-fpm-5.6.6-1.el6.remi.x86_64.rpm

RPMs: http://rpms.famillecollet.com/enterprise/6.5/

A: You can check If you don't try to load module twice. It happened to me with xdebug, got two files wit zend_extension-xdebug.so
It was because I use vagrant to set up my machine and previously default config file had disabled module by default:
20-xdebug.ini:
#zend_module=zdebug.so

so in my provisioning file I symlinked another one 99-xdebug.ini unfortunatelly this recently changed and not xdebug is enabled by default.
Still don't know how to see it - found it by luck after reading this post: https://bugs.php.net/bug.php?id=65584


text:
Q: How to make background move slower than text in Skrollr? tIt seems that I did as it is in example here but my background moving faster than text. What did I do wrong?
My HTML:

    Content text...

A: The demo uses background-attachment:fixed to get full control of the movement.

A: Maybe you forgot to set the class attribute on your loader-bg div
class="skrollable skrollable-between"


text:
Q: Use send() functions to send numbers to __isoc99_scanf("%d", &number) I am trying to solve a pwn problem in a ctf platform. The program only uses scanf() to get index and content of a number array from standard input:
for ( i = 0; i <= 3; ++i )
{
  puts("enter index:");
  __isoc99_scanf("%d", &index);
  if ( index > 3 )
  {
    puts("index is too big");
    exit(0);
  }
  puts("enter value:");
  __isoc99_scanf("%d", &num);
  s[index] = num;
}

while ( j <= 3 )
  printf("0x%08x\t", s[j++]);

return __readgsdword(0x14u) ^ canary;

However, when I use send() function to send 4 bytes int number to the program, the scanf functions seem to detect EOF (rather than the 4-bytes int number) and scanf nothing. Moreover, the following scanf() rejects to get numbers because of the EOF. My send() statements and executing results are as follow:
r.recv()
r.sendline(p32(0x1))
r.recv()
r.sendline(p32(0x1))

exceptional executing results
My question is: How to explain this exceptional problem, and how to correctly use send() to send numbers to __isoc99_scanf("%d", &number) functions in this program?


text:
Q: Run function after AngularJS binding takes place I have a simple app that uses Angular to run a HTTP GET request and then sets the returned data to an array that is bound to the DOM using ng-repeat and I want to run some code that manipulates this DOM after it is done being placed into the body. What is the best way to make this work?
            $http({
                method: 'GET',
                url: 'https://www.*******.com/WebApi/Alert/Items/all',
                cache: false
            })
            .success(function (data, status) {
                $scope.alerts = data.result.Alerts;
                jQuery('.aWidget').iconalt(); // THIS IS THE CODE I WANT TO RUN
            })
            .error(function (data, status) {
                console.log(data);
                alert("error");
            });

See, I want to run the line jQuery('.aWidget').iconalt() after all the DOM is placed into the document. Right now, this line is executing too fast and so it "thinks" that there are no .aWidget elements in the DOM
Is there some kind of callback that I can inject into AngularJS that gets called after the DOM is loaded?

A: You're running up against the digest cycle, which doesn't finish until your code returns. So what you REALLY need is to return but then run a piece of code AFTER that. There's a common JavaScript trick that does this:
// I used Angular's $timeout, but you can use setTimeout() just as easily...
$timeout(function() {
    jQuery('.aWidget').iconalt();
}, 50);

There is also a very cool module called setImmediate.js that polyfills the "setImmediate" function coming in modern browsers. This trick is used so often that browser makers realized it was something they should provide a fast, "correct" way to perform. Your code probably doesn't need to be run faster than 50ms later - the user will never notice... But if you were doing something that DID you could use this tool to run a task on the "next tick", so using the trick wouldn't be a performance hit.


text:
Q: How to check from multiple Boolean columns at least one is true or all column values are false in SQL Server Table format:
+---------+---------+-----------------+
| column1 | column2 | column3| column4|
+---------+---------+-----------------+
| value1  | true    | true   | false  |
| value2  | true    | false  | true   |
| value4  | false   | false  | false  |
+---------+---------+-----------------+

Column 1 to 4 has data type Boolean.
I want to check whether all these Boolean column values are false or at least one column value is true.
Is there any better way to do this using a SQL Server query?
Expected output:
+---------+---------+-----------------+
| column1 | column2 | column3| column4|
+---------+---------+-----------------+
| value1  | true    | true   | false  | = true
| value2  | true    | false  | true   | = true
| value4  | false   | false  | false  | = false
+---------+---------+-----------------+

A: Just use bitwise operators if bit data type.
DECLARE @foo table (column1 bit, column2 bit, column3 bit, column4 bit)
INSERT @foo VALUES (1, 1, 0, 1), (0, 1, 0, 0), (0, 0, 0, 0)

SELECT
    CASE
        WHEN column1 | column2 | column3 | column4 = 0 THEN 'All false'
        ELSE 'Some true'
    END
FROM @foo;

Very simple, no CASTs involved

A: In SQL Server, there's no boolean type, but there's a bit datatype, which I use instead, it's basically 0 and 1 (obviously). So your table would become table of zeros and ones, 0 - false, 1 - true. So to check if at least one column is true out of four, simply add all values and check if it's greater than zero (if all are false, then the sum wuold be equal to zero), like:
case when cast(column1 as int) +
          cast(column2 as int) +
          cast(column3 as int) +
          cast(column4 as int) > 0 then 'at least one true' else 'all false' end

A: SQL Server doesn't have  Boolean type, it has BIT type to represent boolean data
select a.column1,
      case when sum(a.value) >= 1
           then 'one or more is true' else 'all is false' end [CheckBoolVal]
from table t cross apply (
        values (column1, col2), (column1, col3), (column1, col4) )a(column1, value)
group by a.column1

Result :
column1 CheckBoolVal
value1  one or more is true
value2  one or more is true
value4  all is false