text:
Q: Show two name from one table different id I have two tables
tb_masteropsi
id, type, name
1, Job, Painter
2, Job, Singer
3, Use, Kanvas
4, Use, Guitar
5, Use, Microphone

tb_employee
id, name, job, use
1, Jhon, 1, 3
2, Mark, 2, 4
3, Tom, 2, 5

I'm using this query that obviously doesn't work
select
    a.*,
    b.*
from tb_employee a
  join tb_masteropsi b
  on a.job = b.id and a.use = b.id;

My goal is to get following result
id, name, job, use
1, Jhon, Painter, Kanvas
2, Mark, Singer, Guitar
3, Tom, Singer, Microphone

How can I fix it?

A: You have to join tb_employee table twice to get two different rows from that table (once for 'job' and once for 'use' columns of tb_employee table).
So you need something like this to achieve expected result
SELECT
    te.`id`,
    te.`name`,
    tm1.`name` as 'job',
    tm2.`name` as 'use'
FROM `tb_employee` te
    LEFT JOIN `tb_masteropsi` tm1
    ON tm1.`id`=te.`job`
    LEFT JOIN `tb_masteropsi` tm2
    ON tm2.`id`=te.`use`
;

Note: Please, consider splitting tb_masteropsi table into two separate tables - one for "Job" and one for "Use".
Navicat test preview:


text:
Q: Vuetify.js Responsive v-toolbar not triggering open/close event I'm attempting to create a responsive navigation toolbar (using the v-toolbar component and router-links). I'd like to create a navigationbar that collapses into a responsive vertical list (similar to bootstrap navbar) so that when on mobile a hamburger menu appears and a vertical list can be shown and hidden by clicking on the hamburger icon.
I've created a toolbar (see here) however when I reduce the size of the display to activate the responsive toolbar the burger menu does not expand to show the router-links. Similarly, the router-links do not activate (I suspect that the anchor tag is being overridden by the v-btn).
HTML (Pug)
div#app
  nav
    v-toolbar
      v-toolbar-title
        router-link.nav-item(to="/") Mysite
      v-spacer
      v-toolbar-side-icon.hidden-md-and-up
      v-toolbar-items.hidden-sm-and-down
        v-btn(flat)
          router-link.nav-item(to="/about") About
        v-btn(flat)
          router-link.nav-item(to="/contact") Contact

Edit
Edited code to implement suggestion from LShapz (updated Codepen here)
nav
  v-toolbar.hidden-sm-and-down
    v-toolbar-title
      router-link.nav-item(to="/") MySite
    v-spacer
    v-toolbar-items
      v-btn(flat)
        router-link.nav-item(to="/about") About
      v-btn(flat)
        router-link.nav-item(to="/contact") Contact

  div.hidden-md-and-up
    v-expansion-panel
      v-expansion-panel-content
        div(slot="header")
          router-link.nav-item(to="/") MySite
        v-card
          v-card-text
            router-link.nav-item(to="/about") About
        v-card
          v-card-text
            router-link.nav-item(to="/contact") Contact

Can anyone suggest an edit that will allow me to show/hide the responsive menu when clicking the hamburger menu?
Previous codepen
https://codepen.io/atgarbett/pen/wPYMoY
Working codepen
https://codepen.io/atgarbett/pen/QOZoyg

A: As @LShapz has suggested, you can use a combination of v-toolbar and v-expansion-panel. Each of which is shown or hidden depending on the size of the display. This allows for a vertical list style navigation when on smaller displays.
nav
  v-toolbar.hidden-sm-and-down
    v-toolbar-title
      router-link.nav-item(to="/") MySite
    v-spacer
    v-toolbar-items
      v-btn(flat)
        router-link.nav-item(to="/about") About
      v-btn(flat)
        router-link.nav-item(to="/contact") Contact

  div.hidden-md-and-up
    v-expansion-panel
      v-expansion-panel-content
        div(slot="header")
          router-link.nav-item(to="/") MySite
        v-card
          v-card-text
            router-link.nav-item(to="/about") About
        v-card
          v-card-text
            router-link.nav-item(to="/contact") Contact

See example here: https://codepen.io/atgarbett/pen/QOZoyg

A: You do not actually have the code for a v-menu with a list of items on there, nor do have an activator on the v-toolbar-side-icon.

redpajama_set_name: RedPajamaStackExchange


text:
Q: light ray undergoing total internal reflection thrice inside a prism Can it ever be possible that a light ray going inside a triangular prism of refractive index  n having refracting angle A undergo total internal reflection thrice before emerging out?
Note:I know it "may" be possible if the medium surrounding the prism from the three sides is different but I am asking for the case when the medium is same on all the three sides.

A: The answer is YES. See diagram:

The key here is that you can write down the expressions for the angles $a_2, a_3, a_4$ in terms of the angles of the prism $\alpha, \beta, \gamma$ and the first angle $a_1$. Now  $\alpha + \beta + \gamma = 180$ and you know you must have total internal reflection with the first three angles, but not with $a_4$.
$$a_2 = \gamma - a_1\\
a_3 = \beta - a_2\\
a_4 = \alpha - a_3$$
So expressing $a_4$ in terms of $a_1$ we get
$$\begin{align}\\
a_4 &= \alpha - (beta - (\gamma - a_1))\\
&= \alpha - \beta + \gamma - a_1\\
&= \alpha + \beta + \gamma - (a_1 + 2\beta)\\
&= 180 - (a_1 + 2\beta)\end{align}$$
Playing around a bit with these equations, I find that the optimal solution is obtained with
$$\alpha = 36\\
\beta = 72\\
\gamma = 72\\
a_1 = 36$$
In this case, you have $a_2 = 36, a_3 = 36, a_4 = 0$. In other words, as long as you can get total internal reflection with an angle of incidence of 36 degrees, you can do it - and as a bonus, you go "straight in" and come "straight out" - see below (approximately accurate):

This requires a refractive index just greater than 1.7 ($1/\sin(36)$ - definitely possible.
If you are willing to have the exit direction ($a_4$) be something other than zero, then you can improve on the above solution (make it possible with lower refractive index).

A: This is not a complete answer, just a possible way to handle the problem.
I assume that the transversal section of your prism is a triangle with all the angles equal to 60⁰. Let's denote by A, B, C, the three corners of this triangle. Let's denote by $P_1$ the point of incidence on the prism, and then by $P_2$, $P_3$, $P_4$ the points where the ray falls on the internal surfaces of the prism.
Let $θ_i$ be the incidence angle of the ray on your prism.

*

*Then $θ_1$ is the refraction angle, given by
$$\sin(θ_1) = \sin(θ_i)/n$$

*Now, look at the triangle  $P_1 A P_2$. Its angles are equal to:
$90⁰-\arcsin(\sin(θ_i)/n)$, $60⁰$, and $30⁰+\arcsin(\sin(θ_i)/n)$.
Therefore, on the second internal surface of the prism your ray falls under an incident angle
$$θ_2 = 90⁰-30⁰-\arcsin(\sin(θ_i)/n) = 60⁰-\arcsin(\sin(θ_i)/n)$$

*You have to check if this angle satisfies the requirement of total reflection, which is $\sin(θ_2) \ge 1/n$. To help you a bit, according to simple trigonometric rules
$$\sin(60⁰-\arcsin(\sin(θ_i)/n))   = \sin(60⁰)\cos(\arcsin(\sin(θ_i)/n)))
                              - \cos(60⁰)\sin(\arcsin(\sin(θ_i)/n)))
                            \\ =(\sqrt{3}/2)\cos(\arccos(90⁰-\sin(θ_i)/n))
                              - (1/2)\sin(θ_i)/n
                            \\ ={(\sqrt{3})[(π/4)-\sin(θ_i)] - \sin(θ_i)}/(2n)
                           \\ = {(π/8)x\sqrt{3} - [(1+\sqrt{3})/2]\sin(θ_i)}/n $$

*If the last line is greater or equal to $1/n$, then repeat the steps 2 and 3, until you find your answer. But, it seems to me that the answer is negative. Even if you take $θ_i = 0$, you get that the last line is smaller than $1/n$.

So, maybe you try with a triangle which doesn't have all the angles equal, but I don't believe that it will do better.


text:
Q: Sorting map by date(value) using stream Java I have Map with abbreviation as a key and time(duration) as a value
VBM=01:12.434
SVF=01:04.415
CSR=01:12.950
DRR=01:12.013
KMH=01:13.393
SPF=01:12.848
SVM=01:12.463
CLS=01:12.829
BHS=01:13.179
LHM=01:12.460
LSW=01:13.323

and I need to sort it from the shortest duration to the longest.
I use 4 big methods to do it and I wonder if I can do it easily with streams.

A: To sort a map, try the following. Be very sure to use a LinkedHashMap because it doesn't remain sorted otherwise. You can replace Map.Entry.comparingByValue() with a Comparator of your choice.
map
  .entrySet()
  .stream()
  .sorted(Map.Entry.comparingByValue())
  .collect(Collectors.toMap(
    Map.Entry::getKey,
    Map.Entry::getValue,
    (e1, e2) -> e1,
    LinkedHashMap::new
  ));

A: Map<String, String> unSortedMap = new LinkedHashMap<>();
    unSortedMap.put("VBM","01:12.434");
    unSortedMap.put("SVF","01:04.415");
    unSortedMap.put("CSR","01:12.950");
    unSortedMap.put("DRR","01:12.013");
    unSortedMap.put("KMH","01:13.393");
    unSortedMap.put("SPF","01:12.848");
    unSortedMap.put("SVM","01:12.463");
    unSortedMap.put("CLS","01:12.829");
    unSortedMap.put("BHS","01:13.179");
    unSortedMap.put("LHM","01:12.460");
    unSortedMap.put("LSW","01:13.323");
    System.out.println("Unsorted Map : " + unSortedMap);
    LinkedHashMap<String, String> sortedMap = new LinkedHashMap<>();
    unSortedMap.entrySet()
        .stream()
            .sorted(Map.Entry.comparingByValue());
            .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
        System.out.println("\n\n\nSorted Map   : " + unSortedMap);


text:
Q: Ajax request parameter cannot be retrieved within servlet issue As part of learning Ajax, I have created a little servlet + some HTML page + Javascript code. The page contains a couple of buttons. The idea is to pass a parameter value in a request according to the pressed button and return the value in the response. Nothing crazy.
Here is the function making the request (button are linked to this function on click):
function loadXMLDoc2() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","/WebFront/Ajaxlet",true);
    var retr = this.id;
    var param = "cmd=" + retr;
    document.getElementById("L1_LEFT").innerHTML = param;
    xmlhttp.send(param);
}

The L1_LEFT element allows me to check the constructed parameter (for example: cmd=bd_info).
The following method is called on the servlet side to proceed the request and response:
private void setAnswer2(HttpServletRequest req, HttpServletResponse res) throws IOException {

    Enumeration<String> iter = req.getParameterNames();

    System.out.println("Parameters=");
    while (iter.hasMoreElements()) {
        String next = iter.nextElement();
        System.out.println(next);
    }

    ...

}

However, each time I click on buttons, I get an extra parameter line printed:
Parameters=
Parameters=
Parameters=
Parameters=
...

Why? What am I doing wrong?
EDIT
Following BalusC's solution, I modified my code as following:
var retr = this.id;
var param = "cmd=" + encodeURIComponent(retr);
document.getElementById("L1_LEFT").innerHTML = param;
xmlhttp.open("POST","/WebFront/Ajaxlet",true);
xmlhttp.send(param);

and
    Map<String, String[]> en = req.getParameterMap();

    System.out.println("Parameters=");
    for (String next : en.keySet()) {
        System.out.println(next);
    }

The GET solution works, but the POST solution does not work (same issue). I read that POST is preferable to GET. Anyone knows why POST would not work?
EDIT II
Here is the servlet code:
@WebServlet(name="Ajaxlet", urlPatterns={"/Ajaxlet"}, asyncSupported=false)
public class Ajaxlet extends HttpServlet {

    private void setAnswer2(HttpServletRequest req, HttpServletResponse res) throws IOException {

        Map<String, String[]> en = req.getParameterMap();

        System.out.println("Parameters=");
        for (String next : en.keySet()) {
            System.out.println(next);
        }

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        out.println(System.currentTimeMillis());
        out.close();

    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        System.out.println("doPost");
        setAnswer2(req, res);

    }

}

EDIT III
Here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">
    <servlet>
        <display-name>Ajaxlet</display-name>
        <servlet-name>Ajaxlet</servlet-name>
        <servlet-class>net.test.Ajaxlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Ajaxlet</servlet-name>
        <url-pattern>/Ajaxlet/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

and my context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/WebFront"/>

EDIT IV
Updated my web.xml to:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0">

    <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

Still having the same issue with POST.

A: You're creating a GET request and then sending the parameter in the request body. This isn't going to work. In order to send data in the request body, you have to create a POST request (and do the server side request processing job in servlet's doPost() method instead of doGet()):
xmlhttp.open("POST", "/WebFront/Ajaxlet", true);
xmlhttp.send(param);

On GET requests, you normally append the query string with the parameters to the request URL, not the request body:
xmlhttp.open("GET", "/WebFront/Ajaxlet?" + param, true);
xmlhttp.send(null);

Regardless of the request method, you should ensure that parameter names and values are properly URL encoded! You can use JS' builtin encodeURIComponent() function for this:
var param = "cmd=" + encodeURIComponent(retr);

Unrelated to the concrete problem, I know that you're learning Ajax, but I suggest to after all take a look at an existing JavaScript library which takes all the nasty and cross browser sensitive details of sending Ajax requests and traversing/manipulating the HTML DOM from your hands, such as jQuery. In this related question you can find some nice examples how to get started with jQuery + Servlets: How to use Servlets and Ajax?
Another unrelated note, you should prefer getParameterMap() to iterate over parameter names and values. It returns a Map instead of an old fashioned Enumeration; a Map allows you to use the enhanced for loop.

A: Had exactly this same problem, for documentations sake the solution was in my Javascript code,
When sending "form data" in your AJAX Post, you need to set a header like so..
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded")
xmlhttp.send("paramName=paramValue")
source: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp


text:
Q: Alternative proof to numbers game - Numbers as digits $\quad$A couple days ago, I heard of a simple numbers game(or trick), and decided to prove it. I succeeded (I think), but don't really like the way I did it, so I was wondering if someone could think of another way.
But first, here is the game:
$\quad$You pick any 2 digit whole number (let's say, for example purposes, you pick 55). Then, add both digits of your number and subtract the result from the original number. $(55 - (5+5) = 45)$ After that, add the digits of your new name and you will always get 9 $(4+5 = 9)$.
and my proof:
Our first number will be N, composed of two digits, x and y.
So:
$N = 10x + y\quad,\quad N,x,y \in \Bbb N^0 \;,\; 10 \le N \le 99\;, \; 1 \le x \le 9\;,\; y \le 9 $
Our second number, N', is composed of digits a and b.
$N' = 10a + b\quad,\quad N',a,b \in \Bbb N^0 \;,\; 10 \le N \le 99\;, \; a \le 9\;,\; b \le 9 $
We want to prove that $a+b = 9, \forall x,y \;\text{in the conditions above} $ :
$$N' = N - (x + y) = 10x +y - x - y = 10x - x + y - y <=> N' = 9x \quad <=> 10a + b = 9x <=>\text{(isolating a+b)} 9a + a + b = 9x <=> a + b = 9x - 9a \quad <=> a + b= 9(x-a) $$
$\quad$So, if we can prove that x-a = 1, we prove that a+b = 9 and, in turn, the game. This is where I have a problem. The only way I can find is not one I like. It goes something like this:
a is the first digit of N' = 9x. So, since there are only 9 possible values for x, we do this table
$$\begin{array}{c|c|cc}
x & \times9= & a & b \\
\hline
1 & \times9= & 0 & 9 \\
2 & \times9= & 1 & 8 \\
3 & \times9= & 2 & 7 \\
4 & \times9= & 3 & 6 \\
5 & \times9= & 4 & 5 \\
6 & \times9= & 5 & 4 \\
7 & \times9= & 6 & 3 \\
8 & \times9= & 7 & 2 \\
9 & \times9= & 8 & 1 \\
\end{array}$$
$\quad$A quick glance at the table is enough to conclude that it is true that $a = x-1  <=> x-a=1$, meaning $a+b = 9$, and so the game is proved.
$\quad$What I'm looking for is a way to prove this without resorting to a table, or anything like that: not writing out all the possible cases. If you read until here, thank you for your time, I sincerely hope you can help me.

A: HINT :
Let AB be the chosen 2 digit number then

$ 10A + B - (A+B) = 9 \times A $

So a multiple of  9 , which will sum to 9 for any A between 1 to 9
ILLUSTRATION:
For example if A = 9 ( B can be anything because any way in the subtraction it gets cancelled) , 9* 9 = 81  which is 8+1 =9.


text:
Q: Sync KeePassX with KeePass2 Simply put:
In Ubuntu I am using KeePassX and in Windows KeePass2. In am not able to export/import passwords from one to another.
I would prefer to use the same database, but I don't really know how.
If there is no possibility to sync the 2, can you recommend another password vault, which is able to sync passwords from 2 OS, using a shared DB.
Thanks
I am using Ubuntu 12.04 and Win 7.
Edit:
I have noticed that KeePass2 is available in the Software Center, so I have installed it, and I can successfully open my Win7 database. Now I will migrate my KeePassX passwords. I am seeing now a huge difference in the looks. While KeePassX doesn't exactly have Ubuntu like look&feel, it's 100 times more elegant than the interface KeePass2 comes with. Well, maybe that was my initial decision for installing KeePassX on my Ubuntu machine. I can't remember.
@fossfreedom, please add your comment as a response, so that I can accept it.
Thank for the suggestion

A: an alternative...
When dealing with critical data such as passwords I personally prefer keeping the same software and database rather than depending upon some-sort of sync or export/import process.
Fortunately, keepass2 runs very well via Mono - so if you are one of the rare breed who is prepared to host Mono libraries on your computer, then you can install Keepass2 via the Software Center.
keepass2
This will install all the relevant parts of Mono needed to run Keepass2

Linked Question:

*

*How do I run keepass2?


text:
Q: View images in the login page All the users have to do the login before access to my site.
So i insert this code in web.config file:
<authentication mode="Forms">
 <forms name="login" loginUrl="~/Login.aspx" defaultUrl="~/index.aspx"/>
</authentication>
<authorization>
    <deny users="?"/>
</authorization>

It works but the login page is rendered without images..
How can i do?
thanks

A: You need to modify the security on your image directory to allow unauthenticated users access. You can do that one of two ways:
1) You can add another Web.Config to the image directory that contains:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <system.web>
      <authorization>
         <allow users="*" />
      </authorization>
  </system.web>
</configuration>

2) Update the Web.Config in your root directory with a location-specific rule:
<location path="images/">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>

Either change should fix the problem.


text:
Q: Fullcalendar using variable to add events I am having trouble using eventString to add events to fullcalendar. I don't know what I am doing wrong.
<script>
$(document).ready(function() {

    var value=<?php echo $_SESSION['calAvail']; ?>;
    console.log(value);
    var eventString = "[{";
    console.log(value.endDate[0].substring(11,16));
    for(var i = 0, max = value.endDate.length; i < max; i++) {
        if( i != value.endDate.length-1) {
            eventString += "title:" + "\"" + value.title[i] + "\", ";
            eventString += "start:" + "\"" + value.startDate[i].substring(11,16) + "\", ";
            eventString += "end: " + "\"" + value.endDate[i].substring(11,16) + "\", ";
            eventString += "dow: [" + value.day[i] + "] },{ ";
        } else {
            eventString += "title: " + "\"" + value.title[i] + "\", ";
            eventString += "start:" + "\"" + value.startDate[i].substring(11,16) + "\", ";
            eventString += "end: " + "\"" + value.endDate[i].substring(11,16) + "\", ";
            eventString += "dow: [" + value.day[i] + "] ";
        }

    }
    eventString += "}]";

    console.log(eventString);
    var eventShow = eventString;

    $('#calendar').fullCalendar({
        defaultDate: moment(),
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        defaultView: 'month',
        events: eventString
    })
});
</script>

<script type="text/javascript">
    function userInfoChange() {
        window.location = "http://localhost/TisTheSeason/profile_user_edit.php";
    }
</script>

So first I am creating a string based off a json that contains the title, start, end fields. My plan was to dynamically pull out the information in the json and then format it so it follows this:
[{ "title": "", "start": "", "end": "" }]

I did that but I can't seem to put the variable in events:

A: In the events property, fullCalendar expects to be given either
a) a JavaScript variable - which must be an array containing a series of event objects (documentation), or
b) a URL from where it can download a JSON string which it will then automatically parse into a JavaScript array containing event objects (documentation), or
c) a function which does the same process as b) but using a custom data source (documentation).
Your code appears to be attempting to implement option a), but instead of creating a JavaScript array from your data you are creating a variable containing a string instead (i.e. some plain text). The string happens to look like JSON, but it's still a string. It is not an array. FullCalendar is not expecting this. It's not a usable data structure. To be usable, first it would have to be parsed and turned into an array, before you give it to fullCalendar.
That's normally what you'd do if you implemented option c) (and in option b), fullCalendar will do that part on your behalf), but it doesn't work for option a).
Now...you're using JavaScript to create this variable, so it would make far more sense to simply create the desired JavaScript array directly by declaring it in the code. Using JavaScript to make a string and then parse it back to a JavaScript array again is just a pointless extra step. (Also, building JSON strings by hand like this is very vulnerable to the injection of accidental syntax errors and should never be attempted in any situation. If you actually need to create JSON then use a suitable code library to do so.)
$(document).ready(function() {
  var value= <?php echo $_SESSION['calAvail']; ?>;
  var eventList = []; //declare an array, not a string!

  for(var i = 0; i < value.endDate.length; i++) {
    var event = {
      "title": value.title[i],
      "start": value.startDate[i].substring(11,16),
      "end": value.endDate[i].substring(11,16),
      "dow": [ value.day[i] ]
    };
    eventList.push(event);
  }

  console.log(JSON.stringify(eventList));

  $('#calendar').fullCalendar({
    header: {
      left: 'prev,next today',
      center: 'title',
      right: 'month,agendaWeek,agendaDay'
    },
    defaultView: 'month',
    events: eventList
  });
});

So all you're doing here essentially is translating the data structure from one format to another. Notice how much cleaner, easier to read (and to test, maintain and debug) it is. Also, the if/else within your for loop appeared to produce an identical object in either case so it's unclear what the purpose of that was. I removed that test in my version.
defaultDate: moment() is also redundant in your fullCalendar declaration - fullCalendar will already show today's date by default (documentation).


text:
Q: Get return true values using if else statements in jquery I want to get true values from the if/else statement using jQuery. I apply this code but I can't get the required output. It displays both true and false values.
$.each(response, function(index, value) {
  var user = (user_id == value.User_id);

  if (user_roll == 'Customer' && user) {
    if (user === true) {
      //alert(user === true);
      html += "
";
      html += "" + value.ticket_id + "	";
      html += "" + value.User_id + "	";
      html += "" + value.User_name + "	";
      html += "" + value.Customer_name + "	";
      html += "" + value.subject + "	";
      html += "" + value.priority + "	";
    }
  }

The response is this : [The response I got][1]
[1]: https://i.stack.imgur.com/oePac.png . I want to get only User_id = 1 records

A: try comparing the string values together. Sometimes what happens is one of the id that you pass is read as String.
So ,
user_id.toString() == value.User_id.toString()

this is what I do in Javascript to compare id, please check how to convert into String in jquery.


text:
Q: Why does Doctrine create an index on only one column in the linking table? Just like stackoverflow, there is a many-to-many relationship between Question and Tag.
After running these symfony commands:
./symfony doctrine:drop-db
./symfony doctrine:build-db
./symfony doctrine:build-model
./symfony doctrine:build-sql
./symfony doctrine:insert-sql

With the following schema:
schema.yml
Tag:
 columns:
   name:
     type: string(10)
     notnull: true
 relations:
     Questions:
       class: Question
       foreignAlias: Tags
       refClass: QuestionTag

Question:
  columns:
    html:
     type: string(1000)
  relations:
     Tags:
       class: Tag
       foreignAlias: Questions
       refClass: QuestionTag

QuestionTag:
  columns:
    question_id:
     type: integer
     primary: true
    tag_id:
      type: integer
      primary: true
  relations:
    Question:
      class: Question
      foreignAlias: QuestionTags
      type: many
      foreignType: one
    Tag:
      class: Tag
      foreignAlias: QuestionTags
      type: many
      foreignType: one

In the QuestionTag linking table, which helps establish the many-to-many relationship between Tag and Question tables, I found that Doctrine only created a 'normal' index on the tag_id column. Why on this column but not on the question_id column? I don't know.
I think this is strange, because the index that Doctrine creates should be on both question_id and tag_id columns, and so it should become a 'unique' index, rather than a 'normal' one, because question_id and tag_id together form the composite primary key.
Is my understanding correct?
If yes,  why doesn't Doctrine do it in the correct way?

A: I believe Doctrine doesn't support composite primary (or foreign) keys. Remember, the Doctrine project is moving along extremely quickly but it's still fairly young. New features are being added all the time, though I don't think multi-column keys are planned for the 1.x branch.
The workaround would be to create a unique primary key column, question_tag_id, as one of the 3 fields in the QuestionTag table.

A: If I'm reading your code correctly, you shouldn't define the relationships again in your QuestionTag table.
And it's also possible to create an index over two columns manually (just define it in your schema), although I haven't seen how to apply a unique constraint over two columns in Doctrine.


text:
Q: Force Webpack to build output from invalid TypeScript code Basically, it's not good to make Webpack bundle the source code, when errors exist. However, I often need to check console.log() output when radically rewriting my TypeScript code. I'll show the simplified example.
Suppose, in the below code I decide to replace type of parameter from CertainType1 to CertainType2:
testFunction(parameter: CertainType1): CertainTypeFoo {

    const a: CertainTypeA = doSomethingWithCertainType1Or2(parameter);
    // check "a" value here!
    console.log(a);

    // I don't care what occurs here YET
    const b: CertainTypeB = doSomethingElseWithCertainType1(parameter);
    const foo: CertainTypeFoo = getInstanceOfFoo(a, b);

    // do something with foo...

    return foo;
}

When I replace testFunction(parameter: CertainType1): CertainTypeFoo with testFunction(parameter: CertainType2): CertainTypeFoo, function becomes invalid because doSomethingElseWithCertainType1 requires CertainType1 only.
But I don't care about it YET: for now, I need to check const a value, and when I make sure that everything O'K with const a, I'll advance and deal with const b.
Improper solutions:

*

*Comment out everything from const b row: testFunction must return CertainTypeFoo. Assume that it is not simple to get mock instance by other way.

*First rewrite all code to valid TypeScript, than begin checking const a:  "rewrite all code" could take some hours for real applications.

A: @GeorgeP in his comment was right about TypeScript part, but it also required to setup
module.exports = {

  // ...

  optimization: {
    noEmitOnErrors: false
  }
}

for Webpack.

A: Simply cast the type to what you want:
testFunction(parameter: CertainType2): CertainTypeFoo {

    const a: CertainTypeA = doSomethingWithCertainType1Or2(parameter);
    // check "a" value here!
    console.log(a);

    // I don't care what occurs here YET
    const b: CertainTypeB = doSomethingElseWithCertainType1(parameter as CertainType1);
    const foo: CertainTypeFoo = getInstanceOfFoo(a, b);

    // do something with foo...

    return foo;
}

By doing explicit casting, you are telling typescript that you don't care what it thinks (or does not think) this type is, and typescript will respect that.
There is no need to change the compiler flags


text:
Q: Rotating a sphere I'm trying to rotate a sphere, and I'm having a bit of a problem calculating the angle to rotate it by.  I wonder if anyone can help me?
On my sphere I've marked three points.  If the centre of the sphere is (0,0,0), then the points are where the x, y and z axis exit the sphere.
For example:

What I would like to do, is rotate the sphere so that an axis (lets say the z axis) exits the sphere such that these three points are all exactly the same distance from the z axis.
For example, the z axis would exit the sphere approximately here:

This is what I've got so far.
First I rotate the sphere by 45 degrees around the x axis:

So far, no problem.
I then rotate the sphere by -45 degrees around the y axis.
At first glance, it appears to have worked:

But if I enlarge the circles marked on the sphere, it's obvious that the z axis is not exiting the sphere at the right point:

Now I've done a bit of experimenting, and if I rotate the sphere by -35.1, not -45 degrees around the y axis, then it is roughly in the right position.
I've spent the afternoon with pen and paper trying to figure out what I should be rotating by, but I just can't figure the exact angle to rotate by.
Note: the application for this, is I'm trying to design a small stand to be 3d printed.  I would like the stand to be exactly level.
If anyone can help, it'd be much appreciated!
Thanks in advance!
David.

A: You can use the well-known Rodriguez rotation formula (https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula), which states
$
\textbf{v}' = \textbf{v}\cos\theta + (\textbf{r}\times\textbf{v})\sin\theta + \textbf{r}(\textbf{v}\cdot\textbf{r})(1-\cos\theta)
$
where $\textbf{v}$ is the original vector, $\textbf{r}$ is the vector about which the rotation on angle $\theta$ is performed, and $\textbf{v}'$ is the vector after rotation.
Now, by applying this formula twice (first, for example, for the rotation on angle $\alpha$ about $x-$axis and then on angle $\beta$ around $y-$axis), we get
$\textbf{k}'' = \textbf{i}\cos\alpha\sin\beta -\textbf{j}\sin\alpha + \textbf{k}\cos\alpha\cos\beta$.
Now, to find the angle between $\textbf{k}$ and $\textbf{k}''$, you can take the dot-product of them
$\cos \angle(\textbf{k},\textbf{k}'') = \textbf{k}\cdot\textbf{k}'' = \cos\alpha\cos\beta$.
Alternatively, the same can be found as (suggested by Jonas above)
$\cos \angle(\textbf{k},\textbf{k}'') = \langle (0,0,1),(1,1,1)\rangle/\sqrt{3} = \frac{1}{\sqrt{3}}$.
Now, let consider specific example of $\alpha = 45^\circ$ and $\beta = X^\circ$. So, we have
$\frac{\sqrt{2}}{2}\cos X = \frac{1}{\sqrt{3}}$,
from where $X =\cos^{-1}\sqrt{\frac{2}{3}} \approx 35.2644^\circ$.
You were close when you experimented with angles.
Hope this helps.


text:
Q: Can i send a variable along with xmlhttp response text? I have a function defined like this:
function call_view_details(viewid)
{
    view_details(viewid);
    setInterval(function(){view_details(viewid)},5000);
}

which i call at page load. Mainly it sets interval for view_details().
Here's view_details():
function view_details(viewid)
{
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("item_details").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","view_item.php?id="+viewid,true);
    xmlhttp.send();
    return false;
}

As you can see, view_details() updates some div with view_item.php's response.
But i want on some cases (which happen in view_item.php), to execute clearInterval() on view_details().
Now i don't want to say:
if(xmlhttp.responseText==/*something*/)
    /*clearInterval*/

That's because, first, there are a lot of cases, and second, also in those cases view_item.php echos something i need to update the div with.
So maybe i can let view_item.php pass some variable in addition to its response? And then i can make a condition on that variable.
I hope it's clear enough...
Thank you

A: Return a JSON object.
view_item.php
<?php

  // PHP stuff

$returnArray = array();

$returnArray['message'] = $yourRespondText;

$returnArray['clearInterval'] = true; // return true when you want to call clearInterval

echo json_encode($returnArray);

JS:
function call_view_details(viewid)
{
    view_details(viewid);
    var interval = setInterval(function(){view_details(viewid, interval )},5000);
}

function view_details(viewid, yourInterval)
{
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            data = JSON.parse(xmlhttp.responseText);

            if(data.clearInterval) {
                clearInterval(yourInterval);
            }
            document.getElementById("item_details").innerHTML=data.message;
        }
    }
    xmlhttp.open("GET","view_item.php?id="+viewid,true);
    xmlhttp.send();
    return false;
}


text:
Q: Is there a way to identify remotely that shutdown required for updates to apply? Is there a way to remotely find out if a Windows Server (2003, 2008) has downloaded the Microsoft Windows updates and is just waiting for the user to confirm "Install Updates and Shutdown"?
I saw an excellent similar post, but it didn't specifically identify those updates where SHUTDOWN is required.
Thanks.

A: Assuming you are using WSUS to manage windows update deployments there are a bunch of ways to find out which updates are needed and the status of each update.  This example at the very bottom provides a detailed list of updates for a computer and their current status (Needed, Downloaded, Installed, etc.).
Secondly, you could create a PowerShell script to communicate with the PCs in your domain and find out if they are pending a reboot after installing updates.
Overview from MSDN about Pending Reboots
PowerShell Sample


text:
Q: Rewriting my look at mouse position using a controller analog stick I'm currently rewriting my code to use the new Unity Input system. Previously, I had the below code to orientate my "fire point" towards the mouse:
    Vector2 mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);
    Vector2 lookDir = mousePosition - rb.position;
    float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
    rb.rotation = angle;

I need to do this now with the controller right stick instead but I'm not sure how to do it. I have this on the event callback:
public void OnAim(InputAction.CallbackContext context)
{
    aimDir = context.ReadValue<Vector2>();
}

I tried swapping out mousePosition for aimDir in the original code block but that didn't work. Any suggestions?

A: Your current method is taking the coordinates of the mouse on the screen, and transforming it to world space, then calculating your look direction based off this.
This will obviously not work for your controller because it's stick position has nothing to do with the mouse on the screen.
So lets look at an alternative.
You could have some variable keeping track of the direction you are currently facing, but it looks like your rigidbody can already be doing this with it's transform.forward.
You can then take your stick input and use this to create a delta to rotate your rigidbody by, scaling it by some speed factor and using Time.(Fixed)DeltaTime of course.


text:
Q: Hundreds of failed mail attempts found in log to single email Apologies if this is the wrong section (May be better in serverfault?)
Recently in doing a check of the logs I've found our system was for the last several days constantly attempting to mail somebody. Below is a copy of the mail log excerpt
May  4 17:14:51 li240-237 sm-mta[22961]: p3UN9oiX011581: to=<REDACTED@REDACTED.com>, delay=3+18:05:01, xdelay=00:00:01, mailer=esmtp, pri=48812230, relay=mx3.REDACTED*.com. [REDACTED], dsn=4.0.0, stat=Deferred: Connection refused by mx3.REDACTED*.com.
Does anyone have any ideas why so many attempts have been made and if I can track where these attempts are coming from? We do have a php based form which sends out an email to people upon confirmation of the submission and utilizes swiftMailer. Could this be constantly attempting to send the email for some reason?
My account has not been compromised and is the only one on the server aside from the root. The only other thought is someone attempting to send emails via our servers port 25...
Any ideas?

A: Mail Transfer Agents (MTAs) typically retry sending mail if the recipient's mail-server is unavailable. Usually they keep trying for several days. So this can occur if a user or program on your LAN genuinely sent a single email to someone whose mail-server is unavailable.
If you have a web-page that allows people to send e-mail, these are typically attacked by spammers to use a relays for their spam. It is easier for them to get your computer to send out millions of spam messages than to buy their own computers, plus if your ISP disconnects you for spamming, the spammer has plenty of other victims whose computers they can use. So ensure your PHP scripts sanitize all input. It is best to use scripts that have been explicitly developed with security in mind.
Also check that your MTA is configured to block relaying.


text:
Q: Windows 10 change drive letter hangs I am trying to change the letter of an external USB drive from F: to G:. I have tried using the Disk Management utility to do this, similar to this answer. When I click "OK" for the final step, the cursor changes to the "progress spinner" and stays that way for as long as I've cared to wait.
I am able to access and use the drive normally, so it appears to be basically fine. I just need to use a different letter so that my backup software doesn't lose its mind.
I have tried rebooting into Safe Mode, but I get the same results.
Maybe related: if I try to "Safely Remove" the drive it also seems to hang forever.
So, how do I diagnose & resolve this hang, or change my drive letter some other way?


text:
Q: How do I change the color of a div on scroll? I have a div. It has a fixed position
When the user is at the top of the page, the div is red. But when the user starts scrolling and the viewport is no longer at the top of the page, it is supposed to turn blue.
But I could not figure out how to do that.
Below is the code:

.div {
  position:fixed;
  top:10px;
  left:10px;
  height:100px;
  width:100px;
  background:red;
}

/* I know the below syntax doesn't exist. I just wanted to give an idea of what I wanted */
.div:scroll {
  background:blue;
}

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rhoncus condimentum magna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Integer eget commodo urna, eu fermentum nisl. Nullam ac erat eu nibh pulvinar porttitor. In suscipit sit amet sem sed lobortis. Nam venenatis eros quis feugiat auctor. Praesent bibendum lacus ut velit ultricies dignissim. Sed molestie a erat mollis dictum. Quisque nec elit eget nulla aliquam lacinia id quis orci. Aliquam mattis rhoncus lorem ut cursus. Integer id elit luctus, ultricies elit viverra, interdum tortor. Quisque gravida urna vel felis porttitor, quis porta lectus tempus. Morbi auctor eros porttitor augue viverra pulvinar. Pellentesque rutrum dolor tellus, vitae sollicitudin nulla suscipit eget. Cras nunc ex, tempor eget eleifend non, consectetur id nunc. Maecenas risus magna, feugiat ut efficitur ac, vestibulum at ex.

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rhoncus condimentum magna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Integer eget commodo urna, eu fermentum nisl. Nullam ac erat eu nibh pulvinar porttitor. In suscipit sit amet sem sed lobortis. Nam venenatis eros quis feugiat auctor. Praesent bibendum lacus ut velit ultricies dignissim. Sed molestie a erat mollis dictum. Quisque nec elit eget nulla aliquam lacinia id quis orci. Aliquam mattis rhoncus lorem ut cursus. Integer id elit luctus, ultricies elit viverra, interdum tortor. Quisque gravida urna vel felis porttitor, quis porta lectus tempus. Morbi auctor eros porttitor augue viverra pulvinar. Pellentesque rutrum dolor tellus, vitae sollicitudin nulla suscipit eget. Cras nunc ex, tempor eget eleifend non, consectetur id nunc. Maecenas risus magna, feugiat ut efficitur ac, vestibulum at ex.

Is there any way to implement this idea without using JavaScript?

A: Add an onscroll JavaScript event handler to your window in your JavaScript code and then change the color of the div in the function assigned to the event as follows.
<!DOCTYPE html>

  <title>Hello!</title>

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rhoncus condimentum magna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Integer eget commodo urna, eu fermentum nisl. Nullam ac erat eu nibh pulvinar porttitor. In suscipit sit amet sem sed lobortis. Nam venenatis eros quis feugiat auctor. Praesent bibendum lacus ut velit ultricies dignissim. Sed molestie a erat mollis dictum. Quisque nec elit eget nulla aliquam lacinia id quis orci. Aliquam mattis rhoncus lorem ut cursus. Integer id elit luctus, ultricies elit viverra, interdum tortor. Quisque gravida urna vel felis porttitor, quis porta lectus tempus. Morbi auctor eros porttitor augue viverra pulvinar. Pellentesque rutrum dolor tellus, vitae sollicitudin nulla suscipit eget. Cras nunc ex, tempor eget eleifend non, consectetur id nunc. Maecenas risus magna, feugiat ut efficitur ac, vestibulum at ex.

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rhoncus condimentum magna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Integer eget commodo urna, eu fermentum nisl. Nullam ac erat eu nibh pulvinar porttitor. In suscipit sit amet sem sed lobortis. Nam venenatis eros quis feugiat auctor. Praesent bibendum lacus ut velit ultricies dignissim. Sed molestie a erat mollis dictum. Quisque nec elit eget nulla aliquam lacinia id quis orci. Aliquam mattis rhoncus lorem ut cursus. Integer id elit luctus, ultricies elit viverra, interdum tortor. Quisque gravida urna vel felis porttitor, quis porta lectus tempus. Morbi auctor eros porttitor augue viverra pulvinar. Pellentesque rutrum dolor tellus, vitae sollicitudin nulla suscipit eget. Cras nunc ex, tempor eget eleifend non, consectetur id nunc. Maecenas risus magna, feugiat ut efficitur ac, vestibulum at ex.


text:
Q: Is it possible to provide animation progress to angular animations? I have a quite simple animation which was implemented using the Angular animations framework. Instead of simply triggering the animation and waiting 0.15 seconds until completion i want to provide some custom animation progress value.
animations: [
    trigger('animateMargin', [
      state('min', style({ marginTop: '25px' })),
      state('max', style({ marginTop: '50px' })),
      transition('min => max', [ animate('0.15s ease-in') ]),
      transition('max => min', [ animate('0.15s ease-out') ])
    ])
  ]

Is it possible to tell Angular that i want my animation to be complete to 64% or to 27% for example instead of using fixed timings?


text:
Q: Does the Cloud9 has the Syntax automatically? I want make my code more regular,does the cloud9 has this function?
thanks

A: You can format your code with the shortcut ctrl/cmd + shift + b. You can also find this functionality under Edit -> Code Formatting in the Cloud9 menu.


text:
Q: Alternatives to ArcGIS World Geocoder for searching coordinates in AGOL web app I'm building a web app in ArcGIS Online, and don't really care for the way the ArcGIS World Geocoder (https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer) handles coordinates for the search widget.  Are there any alternatives that might be a bit more user friendly for end users of the app?
Currently, I'm using the coordinate conversion widget as a workaround, since it has "zoom to" and "add point" functionality, but would like to know if there are decent geocoder alternatives for searching coordinates from the search widget (both DD and DMS, if possible).

A: There are many online geocoders, and they tend to separate into two groups:

*

*Accurate geocoders (e.g. Google Maps) that prohibit you from using their geocoding results on maps that are not theirs (I assume that's why Google Maps does not work for your use case).

*Inexpensive geocoders without licensing restrictions whose quality is not that great.

We (NetToolKit) recently launched a geocoding service (along with a reverse geocoding service) that tries to fit the quadrant of reasonably accurate geocoders that are inexpensive and that do not have onerous terms of use restrictions. We specialize in US addresses, and use OpenAddresses data so that we have rooftop accuracy for most of the US (we return Nominatim/OpenStreetMap results for the rest of the world). You can compare results of our geocoder with those of other services by using this comparison tool. Our service is also among the most affordable out there (see the bottom of the comparison tool). Our reverse geocoder takes in negative coordinates. (Technical documentation here.)
If you're working primarily with addresses in the US, please try out our service and if you find any deficiencies with the interface, we would be happy to consider your suggestions for enhancements.

A: You can try OSM's nominatim, though it's not meant for commercial use, so it might block you if you have a lot of users
https://nominatim.openstreetmap.org/reverse?format=json&lat=30.3293&lon=-84.1245&zoom=18&addressdetails=1
or HERE's API which should give pretty good results as well and has a pretty good freemium plan
https://places.cit.api.here.com/places/v1/discover/here?app_id={YOUR_APP_ID}&app_code={YOUR_APP_COSE}&at=30.3293,-84.1245
They both have both the reverse geocode function which you are looking for and regular geocoding by query string.


text:
Q: How to using `regexp` to remove all the character not in chinese and english There is ori_string ,how to using regexp to remove all the character not in chinese and english? Thanks!
ori_string<-"没a w t _ 中/国.sz"

the wished result  is
  "没awt中国sz"

A: I have coded it in python, as you didn't specify anything. The idea is here.
def remove_non_english_chinese(text):
    # Use a regex pattern to match any character that is not a letter or number
    pattern = r'[^a-zA-Z0-9\u4e00-\u9fff]'

    # Replace all non-English and non-Chinese characters with an empty string
    return re.sub(pattern, '', text)

A: Seems you want to remove punctuation and spaces:
> regex <- '[[:punct:][:space:]]+'
> gsub(regex, '', ori_string)
[1] "没awt中国sz"


text:
Q: Find if the serie $\frac{n-1}{2n^3-n+4}$ converges. For doing this I chose to compare it to series $\frac{1}{n^2}$:$$\frac{n-1}{2n^3-n+4}\le\frac{n}{n^3}=\frac{1}{n^2}$$. And because $\Sigma\frac{1}{n^2} $ converges absolutely I can deduct that the serie $\Sigma\frac{n-1}{2n^3-n+4}$ also converges. I would like to ask whether the conclusion is true and also what would be the other good ways to determine in this instance whether the serie converges?

A: Yes,your conlusion is true,
Another good general way,but in this case quite equivalent way to solve the exercises, is through ''asymptotic comparison'' with $b_{n} = \frac{1}{n^{2}}$.
Let's enounce it :
Let $\{a_{n}\},\{b_{n}\} \subset \mathbb{R}$ such that $\exists n_{0} \in \mathbb{N} : \forall n \geq n_{0} \{a_{n}\},\{b_{n}\} > 0$ and let's suppose exist $$\exists \lim\limits_{n\to +\infty}\frac{a_{n}}{b_{n}} = L \in [0,+\infty]$$
Then if $\begin{cases}L \in (0,+\infty) \rightarrow \sum\limits_{n \in \mathbb{n}}a_{n} \approx \sum\limits_{n \in \mathbb{n}}b_{n} \\ L=0 \sum\limits_{n \in \mathbb{n}} b_{n} < \infty \rightarrow \sum\limits_{n \in \mathbb{n}} a_{n} < \infty \\ L=+\infty \sum\limits_{n \in \mathbb{n}} b_{n} = +\infty \rightarrow \sum\limits_{n \in \mathbb{n}} a_{n} = +\infty\end{cases}$
In this case $a_{n}=\frac{n-1}{2n^{3}-n+4},b_{n} = \frac{1}{n^{2}}$
We can notice that $\lim\limits_{n\to +\infty}\frac{a_{n}}{b_{n}} = \frac{1}{2}=L \in (0,+\infty)$ so that $\sum\limits_{n \in \mathbb{n}} a_{n} < \infty$

A: Your approach is correct and in fact you have used the Comparison Test. Other useful tests can be found in https://en.wikipedia.org/wiki/Convergence_tests.


text:
Q: Hibernate jpa initialize all proxy in object I am trying to serialize an map of object which in turn can contain hibernate proxy. Does JPA or hibernate have something that will initialize all proxy, or will I have to track each object and initialize them specifically and then serialize.
The map contains 15 keys so its a little huge to track each one and initialize them


text:
Q: Webpage Section Visible Only For Mobiles I've built a webpage for a certain web application I've made.
I'd like to add a specific option only for smartphone users , and don't want it to be visible for non-smartphone users.
Is there any method to define a section ( div ) to be visible only for smartphone users?
Thanks in advance.

A: You could use a Responsive Design approach and achieve what you want with only css, using media queries:
//THIS CSS CLASS IS APPLIED ALWAYS
div.my-option {
    display: none;
}

//THIS MEDIA QUERY APPLIES ITS STYLES ONLY WHEN THE SCREEN WIDTH IS <= 767, SO IT'S A SMARTPHONE DISPLAY.
//IT OVERRIDES THE ONE ABOVE
@media only screen and ( max-width: 767px ) {
    div.my-option {
        display: inline;
    }
}

If you're interested in Responsive Design, two of the most extended options are Bootstrap and Zurb Foundation


text:
Q: Use of Liferays ADT to customize Web Contents I'm using Liferays Application Display Templates to render a set of web contents the way I like (which is working quite fine). Below you find my ADT code to list all news.

    <#list entries as entry>

        <#assign published = entry.getPublishDate()>
        <#assign viewURL = assetPublisherHelper.getAssetViewURL(renderRequest, renderResponse, entry) />

            ${published?string["dd.MM.yyyy"]}
            ${entry.getTitle(locale)}

    </#list>

Now the question I have is how can I customize the actual web content and not just the list of contents? Once I chose one entry to see the full web content using my rendered link I always get a default view with a default headline and some social network buttons and stuff. Is there a way to customize this view as well?
I'm using Liferay 6.2.
Thanks for your help and regards. Sebastian

A: The question implies we're dealing with Asset Publisher portlet customization.
Liferay 6.2 supports customization of the asset list either with ADTs (ie. Freemarker or Velocity templates) or custom display styles (ie. JSPs).
While the support for asset list customization is excellent, Liferay 6.2 doesn't support ADTs or display styles for the asset details. The detail is always rendered by full_content.jsp.
If you need more control of the HTML output for asset detail (title, back link etc.), you have to hook the JSP (full_content.jsp). For general info on JSP hooks, see Overriding Web Resources in the Developer's Guide.
Please note that by hooking this JSP, you'll be overriding the detail view for all Asset Publisher instances in your portal. It's always helpful to think twice, whether the hook is necessary and if it's worth it at all.
Regarding the social network buttons and stuff - this can be configured in Asset Publisher configuration (see Display tab).


text:
Q: Angular bootstrap datetimepicker localization, change language I found out that UI Bootstrap date picker supports localization by including a i18n js file for the specific language for example:
<script src="https://code.angularjs.org/1.0.2/i18n/angular-locale_fr-fr.js"></script>

But this makes the language fixed to French. Is there any way I can switch between 2 languages say English and French on click of a button??

A: We have an outstanding issue in the UIBS datepicker such that the labels are bound using one-time binding syntax.  You can track this issue for more information as well as using your own template to remove the one-time binding syntax to switch languages.


text:
Q: Switch around two products generated by widget In my CMS page, I am using widget to display two products:
{{widget type="catalog/product_widget_new" display_type="new_products" products_count="2" template="catalog/product/widget/new/content/new_grid.phtml"}}

Is there an easy way to switch the places of these two products?
UPDATE
Or, is there a way to call a product just by ID? That way, I can display the 2 products just singular by ID.

A: These might help you.
The block for displaying new product is:
app/code/core/Mage/Catalog/Block/Product/New.php

see the function _beforeToHtml() default sorting is done by start date descending:
->addAttributeToSort('news_from_date', 'desc')

You can copy this block to code/local and replace it with position or the sort order you want.


text:
Q: You don't have permission to access /wp-admin/install.php on this server I'm working on a migration right now and after completing all the necessary steps, I've come across this error when I try accessing the website.
You don't have permission to access /wp-admin/install.php on this server.

I did check my error log and this is what it comes up with:
sudo tail -10 /var/log/apache2/error.log

The errors are as follows:
[Fri Mar 29 16:26:58.360971 2019] [access_compat:error] [pid 41530] [client 66.102.6.237:43764] AH01797: client denied by server configuration: /var/www/html/path_to_files/wp-admin/install.php
[Fri Mar 29 16:29:21.855448 2019] [mpm_prefork:notice] [pid 41505] AH00169: caught SIGTERM, shutting down
[Fri Mar 29 16:29:22.220074 2019] [mpm_prefork:notice] [pid 41633] AH00163: Apache/2.4.29 (Ubuntu) configured -- resuming normal operations
[Fri Mar 29 16:29:22.220165 2019] [core:notice] [pid 41633] AH00094: Command line: '/usr/sbin/apache2'
[Fri Mar 29 16:29:57.546844 2019] [mpm_prefork:notice] [pid 41633] AH00169: caught SIGTERM, shutting down
[Fri Mar 29 16:29:57.653695 2019] [mpm_prefork:notice] [pid 41707] AH00163: Apache/2.4.29 (Ubuntu) configured -- resuming normal operations
[Fri Mar 29 16:29:57.653762 2019] [core:notice] [pid 41707] AH00094: Command line: '/usr/sbin/apache2'
[Fri Mar 29 16:30:05.134525 2019] [access_compat:error] [pid 41726] [client 130.63.49.63:52630] AH01797: client denied by server configuration: /var/www/html/path_to_files/wp-admin/install.php
[Fri Mar 29 16:42:30.993688 2019] [access_compat:error] [pid 41732] [client 130.63.49.63:52828] AH01797: client denied by server configuration: /var/www/html/path_to_files/wp-admin/install.php
[Fri Mar 29 16:42:34.331212 2019] [access_compat:error] [pid 41732] [client 130.63.49.63:52828] AH01797: client denied by server configuration: /var/www/html/path_to_files/wp-admin/install.php

My .conf is as follows:
<VirtualHost *:80>
        ServerAdmin admin@example.com
        ServerName example.com
        DocumentRoot /var/www/html/path_to_files
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Apache2 Version: 2.4.29 (Ubuntu). My file permissions have been set to 755.
Any help on how to resolve this would be great.
.htaccess code:
<files .htaccess>
     Order allow,deny
     Deny from all
</files>
<files readme.html>
     Order allow,deny
     Deny from all
</files>
<files readme.txt>
     Order allow,deny
     Deny from all
</files>
<files install.php>
      Order allow,deny
      Deny from all
</files>
<files wp-config.php>
      Order allow,deny
      Deny from all
</files>

A: You need to temporaly disable blocking access to php install files, after install is complete - enable blocking again. Deny from all blocks access for everyone. Allow from your-ip will enable access only for you. Place "Allow" before Deny on separate line.
This section:
<files install.php>
      Order allow,deny
      Deny from all
</files>
<files wp-config.php>
      Order allow,deny
      Deny from all
</files>

Update: Instead of use order, allow, deny, there are a new option 'Require', so sections should looks like this:
<files install.php>
  Require host address
  # or Require ip ip.address
  # or Require local
</files>

Reference


text:
Q: conflict 'this' references of child and parent components I have also mentioned the issue in code block as comments, I have a child component(Comments) contains form element, when it submit I call "SaveComment()" method of parent component, but this cause conflict of "this" reference..
class VideoDetail extends Component{
  constructor(props){
    super(props)
    this.appState=this.props.appState
    debugger//here this.appState is correctly defined
  }
    SaveComment(e){
      e.preventDefault();
      this.appState.comment.name = this.name.value;
      //this.appState is undefined since "this" keywords refers to 'Comments' child component
      //How can I both use my parent "this" object and a reference object that can get values form child component like here;"this.name.value"
    }
    render(){
        return(

            <Comments {...{totalCommentCount:"12345",bok:"boook!", SaveComment:this.SaveComment}}/>

        )
    }
}

const Comments = (commentContext)=>{
  return (
        <form onSubmit={(e)=>{commentContext.SaveComment(e)}}>
          <input type="text" ref={(input)=>{this.name=input}} placeholder="Name" required=" " />
          <input type="submit" defaultValue="SEND" />

        </form>
  )
}

How can I fix it or change my way to handle it ?

A: There're 2 things to resolve from the above snippet:

*

*How to ensure this refers to the parent instance in event callback

*How to pass form values from child to parent.

To "lock" this keyword, handling events recommends either: a) bind this keyword in constructor b) using property initializer syntax , so that you don't lose the context of "this".
To pass form value to parent, you simply need to change the argument of SaveComment(e) -> SaveComment(comment) in <VideoDetail />, and in the <Comment />, change onSubmit={(e)=>{commentContext.SaveComment(e)} -> onSubmit={(e)=>{commentContext.SaveComment(this.name)}.
In summary, React embraces uni-directional data flow, parent pass props to children and children takes (state, props) => UI to render. If children want to send information back, typically its done through passing arguments to parent's callbacks, so that data still flows in one-way and thus a good separation between Parent & Child regarding data.

A: I hope you would get a error on the console when this executes ref={(input)=>{this.name=input}}.
To access state or prop, you need to have access to their context. So when your function is declared you have to bind. The easiest way is to use arrow functions. So in VideoDetail your SaveComment will look like
  SaveComment = (e) => {
      e.preventDefault();
      // your other logic
  }

Since one cannot use ref in function components, you can convert the Comments function component to a class that extends React.Component. This way you can set ref. If you prefer to follow this path then your Comments would look like
class Comments extends Component {
  render() {
   return (
        <form onSubmit={(e)=>{this.props.SaveComment(e)}}>
          <input type="text" ref={(input)=>{this.name=input}} placeholder="Name" required=" " />
          <input type="submit" defaultValue="SEND" />

        </form>);
  }
 }

In the above method to access the form values in your VideoDetail, you can pass the data from the Comments. So your Comments component will look like
class Comments extends Component {
  onSubmit = (e) => {
   e.preventDefault();
   const formData = {
     name: this.name.value,
   };
   this.props.SaveComment(formData);
  }

  render() {
   return (
        <form onSubmit={this.onSubmit}>
          <input type="text" ref={(input)=>{this.name=input}} placeholder="Name" required=" " />
          <input type="submit" defaultValue="SEND" />

        </form>);
  }
 }

The above way, you can add as many data as you need in formData and send it back to the parent. And your SaveComment in VideoDetail will transform to
 SaveComment = (formData) => {
   // use formData as you wish
 }


text:
Q: -webkit-animation-iteration-count:infinite; working on one style sheet, but not the other? Okay this code works for something simple I threw together as a POC:
.linedcircle
{
width:668px;
height:668px;
background:url(https://robertsspaceindustries.com/rsi/static/images/error/lined_circle.png);
position:relative;
margin: 10px auto 0;
animation:rotating 8s;
animation-timing-function:linear;
animation-iteration-count:infinite;
-webkit-animation:rotating 10s;
-webkit-animation-timing-function:linear;
-webkit-animation-iteration-count:infinite;
}

@keyframes rotating {
0%   {transform: rotate(0deg);}
100% {transform: rotate(360deg);}
}

@-webkit-keyframes rotating
{
0%   {-webkit-transform: rotate(0deg);}
100% {-webkit-transform: rotate(360deg);}
}

The circle spins ad infinitum and there are generally no problems. However with this code on a different style sheet:
.burna{
    animation:fadein 0.50s;
    animation-timing-function:linear;
    animation-iteration-count:infinite;
    -webkit-animation-iteration-count:infinite;
    -webkit-animation:fadein 0.50s;
    -webkit-animation-timing-function:linear;
}
@-webkit-keyframes fadein {
0%{opacity:0;}
40%{opacity:1;}
50%{opacity:1;}
100%{opacity:0.05;}
}
@keyframes fadein {
0%{opacity:0;}
40%{opacity:1;}
50%{opacity:1;}
100%{opacity:0.05;}
}

the animation only plays once. I originally thought it was my javascript or something of that nature but its not. I can change the iteration count to whatever I want and it still only ever plays the animation once. It is working perfectly on Firefox, just not on Chrome, and I THINK Ive tracked it down to the CSS itself, but everything looks correct. So Im not entirely sure what Im doing wrong here. Any advice would be greatly appreciated.

A: The order on the CSS file sometimes is important, in your second example first make the declaration for the animation and then the other properties like iteration-count:
-webkit-animation:fadein 0.50s; /*This first*/
-webkit-animation-iteration-count:infinite;
-webkit-animation-timing-function:linear;

The Fiddle Demo


text:
Q: Koma Script scrlttr2 location height not matching DIN 5008 specification I noticed that the height of the field "location" in Koma Script when using class scrlttr2 did not match the DIN 5008 specifications. There it should be 50mm distance from sheet edge and for the field "backaddress" it should be 45mm, which is right.
But on ym created letter the height from sheet edge to "location" field is about 40mm. So how can i fix this? Or maybe another otion for me, how can i set this height equal to the height of "backaddress", so that both texts will be in the same height?
I added a screenshot. So here you can see that the text-area on the right side (field location) starts not at the in DIN 5008 specified height of 50mm.

A: You can load letter option DIN5008B using \LoadLetterOption{DIN5008B} or \documentclass[...,DIN5008B]{scrlttr2}:
\documentclass[
  ngerman,
  fromphone=true,fromfax=true,fromemail=true,fromurl=true,
  ,DIN5008B% <- needed
]{scrlttr2}
\usepackage{babel}

% only to visualize the position of the address and location fields:
  \LoadLetterOption{visualize}
  \showfields{address,location}
%

\setkomavar{fromname}{Max Mustermann}
\setkomavar{fromaddress}{Musterstr. 42\\01234 Musterstadt}
\setkomavar{fromphone}{01234 56789}
\setkomavar{fromfax}{01234 56789}
\setkomavar{fromemail}{max.muster@muster.com}
\setkomavar{fromurl}{www.muster.com}
\setkomavar{place}{Musterstadt}
\setkomavar{title}{Titel}
\setkomavar{subject}{Betreff}

\begin{document}
\begin{letter}{Erika Musterfrau\\Musterstr. 42\\01234 Musterstadt}
\opening{Hallo}
\end{letter}
\end{document}


text:
Q: Java swing --JPanel on JPanel not showing up I trying to add a JPanel to another JPanel but am faced with the problem that the second Jpanel will not show up on the first one.
My basic structure of things is as follows --
I have a JPanel panel1 which has a BoxLayout and by virtue of HorizontalBoxes and VerticalBoxes i keep adding JComponents to it. All JComponents appear on panel1 except for the second JPanel.
The code for the second JPanel which wont appear is as follows --
public class LabelMacroEditor extends JPanel implements PropertyChangeListener {

    private static final long serialVersionUID = 1L;
    private LabelMacroModel model;

    public LabelMacroEditor(LabelMacroModel bean) {

        this.model = bean;
        model.addPropertyChangeListener(this);
        setupComponents();
        validate();
        setVisible(true);
    }

    public void setupComponents()
    {
        Box allButtons =  Box.createVerticalBox();
        for(MacroModel macroModel : model.getMacroModelList())
        {
            LabelMacroEditorEditableEntity macroEditorEntity =  new LabelMacroEditorEditableEntity(macroModel);
            Box entityBox =  Box.createHorizontalBox();
            entityBox.add(macroEditorEntity.getUpButton());
            entityBox.add(Box.createHorizontalStrut(15));
            entityBox.add(macroEditorEntity.getMacroDetailsButton());
            entityBox.add(Box.createHorizontalStrut(15));
            entityBox.add(macroEditorEntity.getDownButton());

            allButtons.add(entityBox);
        }

        add(allButtons);
    }

    @Override
    public void propertyChange(PropertyChangeEvent arg0) {
        revalidate();
    }

}

I have tested LabelMacroEditor in a standalone way by adding it to a JFrame and found that it appears fine. Im assuming its has something to do with come confliction revalidate/setVisible or the like. Am i missing something obvious ?
I can post more code from the JPanel that is adding LabelMacroEditor if there is a need.
EDIT :
The code snippet from where im adding LabelMacroEditor is as follows --
private final LabelMacroModel labelMacroModel;
private LabelMacroEditor labelMacroEditor;
//code to populate labelMacroModel
Box verticalBox  = Box.createVerticalBox();
// Add all other JComponents to verticalBox
labelMacroEditor = new LabelMacroEditor(labelMacroModel);
verticalBox.add(labelMacroEditor);
add(verticalBox);

A: I recon it's either that your first panel doesn't have a layout manager, in which case you'll need to use setLayout();
or
it's because the second panel has nothing inside it and so it's preferred size is 0. Try adding a new JTextArea(10,5); to it and see what happens.

A: I have the same problem:

*

*I use layouts

*I tried with TextArea as well ... and nothing.

*It is showing fine with JFrame

*Other components are displayed normally (which are basic swing components)

I fix this by setting Preferred size to the custom panel/component.


text:
Q: WMDC emulator connection issues I've got issues connecting my windows mobile 6 emulator to my computer via Window Mobile Developer Center.  I can view the files system on the device.  I can connect to mobile databases on the device.  But I cannot access the web / my local computer from the emulator.
Background: I've been using my emulators for a while now.  Maybe every other month or so, something decides it doesn't want to work any more and I have to twiddle all of the settings I can find until it starts working again.  Today, this has happened to me twice.  I fixed the issues earlier today after lots of hair-pulling, but this time, I don't know what to do any more.
Things I've tried so far:

*

*soft resetting the emulator

*deleting and re-adding the device partnership a la Why is WMDC/ActiveSync so flaky?

*toggling the connection type between 'DMA' and other settings a la How to get Windows Mobile Device Center To Connect to the Emulator

*restarting VS

*restarting my machine

*restarting the emulator manager

No matter what I do, Pocket IE always tells me that it cannot find the website (e.g. yahoo), and my app is unable to connect to my local web site.  Any thing else I should be doing?  Thanks.

A: I've got the connection working now, and I wish I knew what got it working again.  Just prior to the emulator's return to functionality, I was firing-up some of the other emulators to see if they were having issues as well (they weren't).  After trying some other emulators, I went back to the one I want to use, and when I cradled the emulator, it worked.  So, maybe running and cradling some of the other emulators un-clogged something in the bowels of WMDC...


text:
Q: What are the available tools to summarize or simplify text? Is there any library, preferably in python but at least open source, that can summarize and or simplify natural-language text?

A: I needed also the same thing but I couldn't find anything in Python that helped me have a Comprehensive Result.
So I found this Web Service really useful, and they have a free API which gives a JSON result, and I wanted to share it with you.
Check it out here: http://smmry.com

A: Try Open Text Summarizer which is released under the GPL open source license.  It works reasonably well but there has been no development work on it since 2007.
The original code is written in C (both a library and a command line utility) but there are wrappers to it in a number of languages:

*

*Perl

*Ruby

*Python

*C#

A: Maybe you can try sumy. It's a quite small library that I wrote in Python. There are implemented Luhn's and Edmundson's approaches, LSA method, SumBasic, KL-Sum, LexRank and TextRank algorithms. It's Apache2 licensed and supports Czech, Slovak, English, French, Japanese, Chinese, Portuguese, Spanish and German languages.
Feel free to open an issue or send a pull request if there is something you are missing.

A: Not python but MEAD will do text summarization (it's in Perl).  Usually what comes out is comprehensible, if not always particularly fluent sounding.  Also check out summarization.com for a lot of good information on the text summarization task.

A: Take a look at this article which does a detailed study of these methods and packages:

*

*Lex_rank (sumy)

*LSA (sumy)

*Luhn (sumy)

*PyTeaser

*Gensim TextRank

*PyTextRank

*Google TextSum
The ending of the article does a 'summary'.
The author of sumy @miso.belica has given a description in an answer above.
Various other ML techniques have risen, such as Facebook/NAMAS and Google/TextSum but still need extensive training in Gigaword Dataset and about 7000 GPU hours. The dataset itself is quite costly.
In conclusion I would say sumy is the best option in the market right now if you don't have access to high-end machines. Thanks a lot @miso.belica for this wonderful package.

A: I'm not sure if there is currently any libraries that do this, as text summarization, or at least understandable text summarization isn't something that will be easily accomplished by a simple plug & play library.
Here are a few links that I managed to find regarding projects / resources that are related to text summarization to get you started:

*

*The Lemur Project

*Python Natural Language Toolkit

*O'Reilly's Book on Natural Language Processing in Python

*Google Resource on Natural Language Processing

*Tutorial : How to create a keyword summary of text in Python
Hope that helps :)

A: A while back, I wrote a summarization library for python using NLTK, using an algorithm from the Classifier4J library. It's pretty simple but it may suit the needs of anyone that needs summarization: https://github.com/thavelick/summarize


text:
Q: Split a large file into unique files I have huge file 100M, that has the text (few lines below,) stack of lines are unique scaffold1_, scaffold2_ and on.
I would like to have a new file that is specific to each scaffold.1...txt
tried few sed and grep commands but they didn't help.
scaffold1_2,C,C,C,C,N,C,N,C,G,G,C,N,C,C,G,N,N,C,G,N,C,C,C,G,C,N,N,C,C
scaffold1_113,T,T,T,T,T,T,T,T,T,C,T,T,T,T,T,T,C,T,T,T,T,T,C,T,T,N,T,T,T
scaffold1_149,G,G,G,G,C,G,C,G,C,G,G,C,C,G,C,C,G,C,G,G,C,G,G,G,G,C,G,G,G
scaffold1_160,G,G,G,T,G,T,T,T,N,T,T,T,G,T,G,G,T,T,T,T,T,N,T,T,G,G,T,T,G
scaffold2_315,C,C,C,G,C,C,C,C,C,C,C,G,C,C,G,G,G,C,C,C,C,C,C,G,C,C,C,C,G
scaffold2_318,G,A,A,A,A,A,A,G,A,A,A,A,A,A,A,A,A,A,G,A,A,A,A,A,A,A,A,A,A
scaffold2_323,T,T,T,T,T,C,C,T,T,T,T,T,T,T,T,T,T,T,T,C,T,T,T,T,T,T,T,T,T
scaffold2_397,A,A,A,A,A,A,C,A,A,A,A,A,A,A,A,A,C,A,A,A,A,A,A,A,A,A,A,A,A
scaffold3_402,C,C,C,C,C,T,C,C,C,C,C,C,C,T,C,C,C,T,C,C,C,C,C,C,C,C,C,C,C
scaffold3_465,G,G,G,G,G,G,G,G,G,C,G,G,G,G,G,G,G,G,G,G,G,G,G,G,G,G,C,C,G
scaffold3_502,C,C,C,C,C,C,C,C,C,G,C,C,C,C,C,C,C,G,C,G,C,G,C,C,C,C,C,C,C
scaffold3_508,G,G,G,C,G,G,G,G,G,C,G,C,C,C,C,C,G,C,G,C,G,C,C,C,C,C,C,C,C
scaffold3_533,G,G,G,G,A,A,A,G,A,G,A,G,G,A,G,G,A,A,G,A,A,G,G,G,G,G,G,G,G
scaffold4_555,T,T,T,T,T,T,T,T,T,T,T,T,T,T,A,A,T,T,T,T,T,T,T,T,T,T,T,T,T
scaffold4_586,T,T,T,T,T,T,T,T,T,T,T,C,C,T,T,T,T,T,T,T,T,T,C,T,C,T,T,T,T
scaffold4_593,A,G,G,G,A,A,A,A,G,G,A,A,A,A,G,G,A,A,G,A,G,G,A,G,A,G,A,A,G
scaffold4_598,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,A,A,C
scaffold4_664,G,A,A,G,G,G,A,G,G,G,G,G,G,G,G,G,A,G,G,G,G,G,G,G,G,G,G,G,G
scaffold5_667,C,C,C,C,C,C,C,C,T,C,C,C,C,C,C,C,C,C,T,C,T,T,C,C,C,C,T,T,C
scaffold5_670,A,A,A,A,A,A,A,A,G,A,A,A,A,A,A,A,A,A,G,A,G,G,A,A,A,A,G,G,A
scaffold5_679,T,C,C,C,C,C,C,T,C,T,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C,C

resulting files should look something like
cat scaffold1.txt
scaffold1_2,C,C,C,C,N,C,N,C,G,G,C,N,C,C,G,N,N,C,G,N,C,C,C,G,C,N,N,C,C
scaffold1_113,T,T,T,T,T,T,T,T,T,C,T,T,T,T,T,T,C,T,T,T,T,T,C,T,T,N,T,T,T
scaffold1_149,G,G,G,G,C,G,C,G,C,G,G,C,C,G,C,C,G,C,G,G,C,G,G,G,G,C,G,G,G
scaffold1_160,G,G,G,T,G,T,T,T,N,T,T,T,G,T,G,G,T,T,T,T,T,N,T,T,G,G,T,T,G

cat scaffold2.txt
scaffold2_315,C,C,C,G,C,C,C,C,C,C,C,G,C,C,G,G,G,C,C,C,C,C,C,G,C,C,C,C,G
scaffold2_318,G,A,A,A,A,A,A,G,A,A,A,A,A,A,A,A,A,A,G,A,A,A,A,A,A,A,A,A,A
scaffold2_323,T,T,T,T,T,C,C,T,T,T,T,T,T,T,T,T,T,T,T,C,T,T,T,T,T,T,T,T,T
scaffold2_397,A,A,A,A,A,A,C,A,A,A,A,A,A,A,A,A,C,A,A,A,A,A,A,A,A,A,A,A,A

A: for i in $(cat myfile.txt|cut -d"_" -f 1 | sort | uniq)
do
  grep ${i} myfile.txt > ${i}.txt
done

This should work


text:
Q: Have a function time out if a certain condition is not fulfilled in time The issue I have is that my chat client is supposed to recieve and print data from server when the server sends it, and then allow the client to reply.
This works fine, except that the entire process stops when the client is prompted to reply. So messages pile up until you type something, and after you do that, then it prints all the recieved messages.
Not sure how to fix this, so I decided why not have the client's time to type a reply timeout after 5 seconds, so that the replies can come through regardless. It's pretty flawed, because the input will reset itself, but it works better anyways.
Here's the function that needs to have a timeout:
# now for outgoing data
def outgoing():
    global out_buffer
    while 1:
        user_input=input("your message: ")+"\n"
        if user_input:
            out_buffer += [user_input.encode()]
#       for i in wlist:
            s.send(out_buffer[0])
            out_buffer = []

How should I go about using a timeout? I was thinking of using time.sleep, but that just pauses the entire operation.
I tried looking for documentation. But I didn't find anything that would help me make the program count up to a set limit, then continue.
Any idea's about how to solve this? (Doesn't need to use a timeout, just needs to stop the message pileup before the clients reply can be sent) (Thanks to all who helped me get this far)
For Ionut Hulub:
from socket import *
import threading
import json
import select
import signal # for trying to create timeout

print("client")
HOST = input("connect to: ")
PORT = int(input("on port: "))

# create the socket
s = socket(AF_INET, SOCK_STREAM)
s.connect((HOST, PORT))
print("connected to:", HOST)

#--------- need 2 threads for handling incoming and outgoing messages--

#       1: create out_buffer:
out_buffer = []

# for incoming data
def incoming():
    rlist,wlist,xlist = select.select([s], out_buffer, [])
    while 1:
        for i in rlist:
            data = i.recv(1024)
            if data:
                print("\nreceived:", data.decode())

# now for outgoing data
def outgoing():
    global out_buffer
    while 1:
        user_input=input("your message: ")+"\n"
        if user_input:
            out_buffer += [user_input.encode()]
#       for i in wlist:
            s.send(out_buffer[0])
            out_buffer = []

thread_in = threading.Thread(target=incoming, args=())
thread_out = threading.Thread(target=outgoing, args=())
thread_in.start() # this causes the thread to run
thread_out.start()
thread_in.join()  # this waits until the thread has completed
thread_out.join()

A: We can use signals for the same. I think the below example will be useful for you.
import signal

def timeout(signum, frame):
    raise Exception

#this is an infinite loop, never ending under normal circumstances
def main():
    print 'Starting Main ',
    while 1:
        print 'in main ',

#SIGALRM is only usable on a unix platform
signal.signal(signal.SIGALRM, timeout)

#change 5 to however many seconds you need
signal.alarm(5)

try:
    main()
except:
    print "whoops"


text:
Q: What's benefit of docker's image layer? I'm new to Docker. Based on reading some Docker documentation, I plan to convert my project to Docker image as the following design:
My project has the follow natures:

*

*The base OS almost never need to update unless big OS issue, thus say update base OS every 2 years.

*The base libraries might be updated only 6 months.

*Libraries are updated every month.

*Project code are updated once a day.

Thus I plan to create 4 images:

*

*image1 - base os

*image2 - from image1 and add base libraries

*image3 - from image2 and add libraries

*image4 - from image3 and add project code

My understanding is, image4 has 4 layers. Once I build a new image4, Docker only needs to pull layer4, because layer 1,2,3 are same as the old image4. Since my project code is just some text scripts, thus layer4 should be very small, thus pull a new image4 should be very fast.
Is my understanding correct?

A:
Since my project code is just some text scripts, thus layer4 should be very small

Layer4 will be small, but pulling image4 will be fast only if one has already pulled image 1 to 3 before.
And the resulting image4 won't be small, but the result of the concatenation of the 3 base images.
Plus, the term "layer" should not mask the fact that each line in a docker file will create an intermediate image, making the actual image a collection of all those intermediate small layers (resulting from the execution of each Dockerfile command).
You might have 4 "general" layers, but the actual image is  likely to be composed of more than 4 layers.
You can check that with imagelayers.io
I use an alias to cleanup old dangling images:
alias drmiad='docker rmi $(docker images --filter "dangling=true" -q --no-trunc)'

My build script usually include:
. ../.bash_aliases

docker build -t sshd . || exit 1
drmiad 2> /dev/null


text:
Q: Struggling to create a php array to fetch photos from directory that can be used as an array in JavaScript Basically I am trying to create a photo slideshow that will display specific photos depending on the userid. These photos will be stored in the directory of my web server space. Currently I have a html (not changed into php) file with basic html layout, css style sheet and an external js file that has my code that makes the photos fade in and out. I have added php at the bottom of my html. This is what I have:

$user_id = $_GET['userid'];
print "<h1> Hi,  $user_id </h1>";

function returnimages($dirname = "Photos/1") {   //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}

closedir($handle);
}
return($files);
}

echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names

?>

and in my javscript, the code I had before for the array of photos:
// List of images for user one
var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
    userphoto[1] = "Photos/1/2.jpg";
        userphoto[2] = "Photos/1/1.jpg";
            userphoto[3] = "Photos/1/1.jpg";
                userphoto[4] = "Photos/1/1.jpg";

which I have now commented out and replaced it with this:
var userphoto = <? echo json_encode($galleryarray); ?>;

I am hoping to be able to change the src of photodisplay with the new array:
photodisplay[x].attr("src", userphoto[x]);
Sorry if my problem is not clear at all. I am very confused myself. :( hopefully someone can help!

A: $user_id = (int) $_GET['userid'];
print "<h1> Hi,  $user_id </h1>";

function returnimages($dirname = "Photos/1") {
    $dirname = str_replace('..', '.', $dirname); //only remove this if you know why it's here
    $pattern = "*{.jpg,.png,.jpeg,.gif}"; //valid image extensions
    return glob($dirname . DIRECTORY_SEPARATOR . $pattern, GLOB_BRACE);
}

echo "var galleryarray = ".json_encode(returnimages()).";\n";
?>

Also, you should use <?= json_encode($ret) ?> because the PHP short tag (<?) is deprecated, but <?= is not, and is the equivalent of <?php echo.


text:
Q: Decouple unit of work from services or repo I am trying to decouple my unit of work from my services or repository so that I wont have to touch the UoW code whenever I wish to add a new service. How do I do this?
_categoryService = _unitOfWork.Get<ICategoryService>();

so instead of
_unitOfWork.CategoryService.Add(category)

I can just say;
_categoryService.Add(category);

A:
I am trying to decouple my unit of work from my services or
  repository so that I won't have to touch the UoW code whenever I wish
  to add a new service

Well, that's a good start!  ;-)
The solution I am presenting is not the one and only possible solution, there are several good ways to implement UoW (Google will help you out). But this should give you the big picture.
First, create 2 interfaces: IUnitOfWork and IRepository
public interface IUnitOfWork : System.IDisposable
{
  IRepository<TEntity> GetRepository<TEntity>() where TEntity : class;
  void Save();
}

public interface IRepository<T> : IDisposable where T : class
{
  void Add(T entity);
  void Delete(T entity);
  void Update(T entity);
  T GetById(long Id);
  IEnumerable<T> All();
  IEnumerable<T> AllReadOnly();
  IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
}

The implementations are quite straightforward (I removed all my comments for readability purpose, but do not forget to add yours  ;-) )
public class UnitOfWork<TContext> : IUnitOfWork where TContext : IDbContext, new()
{
  private readonly IDbContext _ctx;
  private Dictionary<Type, object> _repositories;
  private bool _disposed;

  public UnitOfWork()
  {
    _ctx            = new TContext();
    _repositories   = new Dictionary<Type, object>();
    _disposed       = false;
  }

  public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
  {
    if (_repositories.Keys.Contains(typeof(TEntity)))
      return _repositories[typeof(TEntity)] as IRepository<TEntity>;

    var repository = new Repository<TEntity>(_ctx);
    _repositories.Add(typeof(TEntity), repository);
    return repository;
  }

  public void Save()
  {
     try
     {
       _ctx.SaveChanges();
     }
     catch (DbUpdateConcurrencyException ex)
     {
       ex.Entries.First().Reload();
     }
  }

  …
}

public class Repository<T> : IRepository<T> where T : class
{
  private readonly IDbContext _context;
  private readonly IDbSet<T> _dbset;

  public Repository(IDbContext context)
  {
    _context = context;
    _dbset   = context.Set<T>();
  }

  public virtual void Add(T entity)
  {
    _dbset.Add(entity);
  }

  public virtual void Delete(T entity)
  {
    var entry = _context.Entry(entity);
    entry.State = EntityState.Deleted;
  }

  public virtual void Update(T entity)
  {
    var entry = _context.Entry(entity);
    _dbset.Attach(entity);
    entry.State = EntityState.Modified;
  }

  public virtual T GetById(long id)
  {
    return _dbset.Find(id);
  }

  public virtual IEnumerable<T> All()
  {
    return _dbset.ToList();
  }

  public virtual IEnumerable<T> AllReadOnly()
  {
    return _dbset.AsNoTracking().ToList();
  }

  public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
  {
    return _dbset.Where(predicate);
  }

}

As you can see, both implementations make use of IDbContext interface. This interface is just for easy testing purpose:
public interface IDbContext
{
  DbSet<T> Set<T>() where T : class;
  DbEntityEntry<T> Entry<T>(T entity) where T : class;
  int SaveChanges();
  void Dispose();
}

(As you can see, I'm using EntityFramework Code First)
Now that the whole plumbing is set up, let's have a look at how this could be used in a service.
I have a base service that looks like this:
internal class Service<T> where T : class
{
  internal Service(Infrastructure.IUnitOfWork uow)
  {
    _repository = uow.GetRepository<T>();
  }

  protected Infrastructure.IRepository<T> Repository
  {
    get { return _repository; }
  }

  private readonly Infrastructure.IRepository<T> _repository;
}

And all my services inherit from this base service.
internal class CustomerService : Service<Model.Customer>
{
  internal CustomerService(Infrastructure.IUnitOfWork uow) : base(uow)
  {
  }

  internal void Add(Model.Customer customer)
  {
    Repository.Add(customer);
  }

  internal Model.Customer GetByID(int id)
  {
    return Repository.Find(c => c.CustomerId == id);
  }

}

And that's it!
Now, if you want to share the same UoW to several services, in a facade method or somewhere else, it could just look like this:
using (var uow = new UnitOfWork<CompanyContext>())
{
  var catService = new Services.CategoryService(uow);
  var custService = new Services.CustomerService(uow);

  var cat = new Model.Category { Name = catName };
  catService.Add(dep);

  custService.Add(new Model.Customer { Name = custName, Category = cat });

  uow.Save();
}

Hope this helps!


text:
Q: How to Disable image button I have an button whose type is image i want to disable button till some action following is the html tag

How to disable this button?

A: You can add a click that returns false:
$('#myButton').click(function() { return false; });

You might want to add a message that explains why it's disabled, and possibly some CSS to make it look disabled as well.

A: This is the code I use to disable or re-enable a control:
function handleControlDisplay(className, foundCount, checked) {

    var button = jQuery(className);

    if (foundCount > 0 && foundCount == checked) {

        // enable

        button.removeAttr("disabled");

    }

    else {

        // set the disabled attribute

        button.attr("disabled", "true");

    };

}


text:
Q: Error opening tensorboard I'm getting an error opening tensorboard.  This is my code:
import tensorflow as tf
a = tf.constant(5,name = 'input_a')
b = tf.constant(3,name = 'input_b')
c = tf.multiply(a,b,name='mul_c')
d = tf.add(a,b,name='add_d')
e = tf.add(c,d,name = 'add_e')
with tf.Session() as sess:
    output = sess.run(e)
    print(output)
    writer = tf.summary.FileWriter('path/to/log',tf.get_default_graph())
    writer.close()

This is the command:
tensorboard --logdir=path/to/log

This is the ERROR:

File "c:\programdata\anaconda3\lib\runpy.py", line 85, in _run_code
      exec(code, run_globals)
  File "C:\ProgramData\Anaconda3\Scripts\tensorboard.exe__main__.py", line 5, in
  File "c:\programdata\anaconda3\lib\site-packages\tensorboard\main.py", line 36, in
  from tensorboard.plugins.audio import audio_plugin
  File "c:\programdata\anaconda3\lib\site-packages\tensorboard\plugins\audio\audio_plugin.py", line 27, in
  from tensorboard import plugin_util
  File "c:\programdata\anaconda3\lib\site-packages\tensorboard\plugin_util.py", line 21, in
  import bleach
  File "c:\programdata\anaconda3\lib\site-packages\bleach__init__.py", line 14, in
  from html5lib.sanitizer import HTMLSanitizer
  File "c:\programdata\anaconda3\lib\site-packages\html5lib\sanitizer.py", line 7, in
   from .tokenizer import HTMLTokenizer
  File "c:\programdata\anaconda3\lib\site-packages\html5lib\tokenizer.py", line 17, in
    from .inputstream import HTMLInputStream
  File "c:\programdata\anaconda3\lib\site-packages\html5lib\inputstream.py", line 9, in
    from .constants import encodings, ReparseException
  ImportError: cannot import name 'encodings'

A: I got the same error and fixed it. Apparently, there is a problem with html5lib, but mrry's suggestion does not solve it because a message will tell you that you already have the latest version installed.
Instead, run this:
pip install html5lib==1.0b8

More about this issue here: https://github.com/xhtml2pdf/xhtml2pdf/issues/318.

A: I had the same problem with Anaconda. This worked for me:
pip uninstall html5lib
conda install -c anaconda html5lib
pip install html5lib==1.0b10

A: I had the same problem and I solved it by installing python 3.7.2 instead of 3.7.
I also deleted the python file left behind 3.7 in directory C:\Users\Your_user_name\appdata\local\programs\python before installing 3.7.2.


text:
Q: Reaching a data in json using getJSON I want to get the username's profile image. So i prefer to use twitter api version 1 for this.(The regular version of api is here). But my code doesn't return any data. How can i fix this?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready( function() {
var userPage = "https//twitter.com/jack";
var arr = userPage.split("/");
var username = "";

for(i=3;i<4;i++)
username += arr[i];

var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username;

        $.getJSON(page, function(data) {
            alert(data.profile_image_url);
        });

})

</script>
</head>

<body>
</body>

</html>

A: Add "&callback=?" to the URL to force jsonp format to get around the Access-Control-Allow-Origin issue.
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username + "&callback=?";

EXAMPLE
JSONP:

The way JSONP works is simple, but requires a little bit of
  server-side cooperation. Basically, the idea is that you let the
  client decide on a small chunk of arbitrary text to prepend to the
  JSON document, and you wrap it in parentheses to create a valid
  JavaScript document (and possibly a valid function call).
The client decides on the arbitrary prepended text by using a query
  argument named jsonp with the text to prepend. Simple! With an empty
  jsonp argument, the result document is simply JSON wrapped in
  parentheses.


text:
Q: Get what exists in one DataTable but not another using LINQ I have two DataTables. I want to get what exists in the first one but does not exist in the second one. I would like the results in another DataTable. I would like to use LINQ.

*

*The First datatable:

DataTable dt1 = cc1roleDAL.GetAll(x, 0);

*

*The second datatable:

DataTable dt2 = cc1roleDAL.GetSpecific(x);

Note: the column names I return from the the two datatables:

*

*crs_name

*name

A: This will do the trick for you:
var rowsOnlyInDt1 = dt1.AsEnumerable().Where(r => !dt2.AsEnumerable()
                    //make sure there aren't any matching names in dt2
                    .Any(r2 => r["crs_name"].Trim().ToLower() == r2["crs_name"].Trim().ToLower() && r["name"].Trim().ToLower() == r2["name"].Trim().ToLower()));

or if you prefer query syntax:
var rowsOnlyInDt1 = from r in dt1.AsEnumerable()
                    //make sure there aren't any matching names in dt2
                    where !dt2.AsEnumerable().Any(r2 => r["crs_name"].Trim().ToLower() == r2["crs_name"].Trim().ToLower() && r["name"].Trim().ToLower() == r2["name"].Trim().ToLower())
                    select r;

You can then put the results into a DataTable by using the CopyToDataTable function:
DataTable result = rowsOnlyInDt1.CopyToDataTable();

A: You want to use the Except extension.
Here is the link to the linq on MSDN.
From what I get from the question somthing like.
var theNonIntersect =
    dt1.AsEnumerable().select(r => r.Field<string>("crs_name"), r.Field<string>("name"))
        .Except(dt2.AsEnumerable().select(r => r.Field<string>("crs_name"), r.Field<string>("name")));

A: HI there hope this code does help you and if i have misunderstood then can ask me to edit this post
DataContext db = new DataContext();
var result  = from a in db.dt1
              from b in db.dt2
              where a.crs_name != b.name
              select a.crs_names;

foreach(var names in result)
{
  dt2Entity obj = new dt2Entity();
  obj.name = names.name;
  db.InsertOnSubmit(obj);
  db.SubmitChanges();
}


text:
Q: What is the syntax to do a cross-domain XMLHTTPREQUEST to an FTP server? I have an webDav CORS plugin, which I can use to POST/PUT/GET/REMOVE/ALLDOCS files on a webDav server.
I now want to do the same for FTP, but I'm struggling to get the xmlhttprequest-syntax to work (I'm just getting error 0 ).
This page on Mozilla says it's possible to use xmlhttprequests for file and ftp as well, but I cannot find a working example or tutorial anywhere.
This is what I'm trying, which returns access to restricted URI denied
function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("GET", "ftp://<username>:<passeword>@mydomain.de/folder/test.txt", true);
oReq.send();

I also tried a regular Ajax request
$.ajax({
  url: "ftp://sharedspace.domain.provider.com/folder/test.txt",
  type: "GET",
  async: true,
  dataType: "text",
  crossdomain : true,
  headers : {
    user: "<username>",
    password: "<password>"
  },
  success: function(e){
    console.log("success");
    console.log(e);
  },
  error: function(e){
    console.log("error");
    console.log(e);
  },
});

which also does not work, returning 0 status code.
Question:
What is the correct syntax to do a cross-domain XMLHTTPREQUEST for FTP.
Thanks!
EDIT:
The only useful link I found is this page here, but it's just bits and pieces of information and I couldn't puzzle them together.
EDIT
Maybe also useful link

A: Although the Mozilla MDN docs reference xmlHttpRequest supporting file and ftp none of the major browsers do AFAIK. It is one of the reasons why you need to serve your web projects from some sort of server, even if it is on the same machine, if you want to develop/test any xmlHttpRequest stuff since file:// doesn't work.
Microsoft specifically states that IE only supports http/https. The W3C spec for it also says that the spec is only for HTTP/HTTPS but that 'some implementations support protocols in addition to HTTP and HTTPS, but that functionality is not covered by this specification'.
As for CORS, it is specifically only for HTTP/HTTPS. The spec is all about using HTTP headers. See the W3C spec here. FTP doesn't have any equivalent type of header as HTTP.

A: oReq.open("PUT", "ftp://`<username`>:`<password`>@mydomain.de/folder/test.txt", true);

req.setRequestHeader('Content-Type', "text/plain");

req.send("Content of test.txt. This will be in test.txt");