text:
Q: Responsive navbar with onclick search bar I'm trying to make a responsive navbar which sits in-line with a few other icons on my website.
I have it working on desktop mode, but I am struggling with the mobile view.
The main issue I'm having is that I cannot collapse the search bar so when you click the magnifying glass the search bar will pop up below the navbar.
Lining up all 5 icons so that it looks neat.
Below I have attached 3 images:
The first one is where I am currently at with my site
The second Site is What I want to achieve
The Third is how it looks in desktop mode with the search bar working.

I have also attached a js Fiddle with all the content that I currently have.
https://jsfiddle.net/kLo8x29u/

  Home
  Building Materials
  Timber and Hardwood
  Landscaping
  Kitchens and Bathrooms
  Tools
  Flooring
  Tool Hire
  Timber Enginering

Home

Thanks in advance!

A: If you want to align your icons, you have to put the icons and the menu in the same div with an id; Then you give it a position relative and display inline-block. After this, all the icons have to have float left, so that they will be positioned in line. The way you have your code, youre not informing it that you want to have the icons side by side :) if you still need some help, I can help you


text:
Q: regex for multiple linebreaks in a phrase I am learning regular expressions with Python and I want to prepare an RE to match and collect sentence(s) from below input:

*

*Food : Cake : Baked sweet food made from flour, sugar and other ingredients.

*Electronics : Computer : A machine to carry out a computer programming operation.
Computers mainly consists of a CPU, monitor, keyboard and a mouse.

*Automobile : Car : Car is a four wheeled motor vehicle used for transportation.

My expected output should give me category, item and the description of that item. So for 1st item, Cake, the RE should group "Food", "Cake", "Baked sweet food made from flour, sugar and other ingredients.".
My current RE looks like this:
[0-9]+\s*.\s*(\w*)\s*:\s*(\w*)\s*:\s*(.*)

This seems to be working for items which has description with no line-breaks. If it has a line-break, i.e., Computer in the example, the RE only matches its description up to the line-break. The RE discards the second sentence in that description.
Please help me understand what I am missing out here.

A: If the category, item and description  is separated by double newline, you can use this example to parse it (regex101):
import re

txt = '''1. Food : Cake : Baked sweet food made from flour, sugar and other ingredients.

2. Electronics : Computer : A machine to carry out a computer programming operation.
   Computers mainly consists of a CPU, monitor, keyboard and a mouse.

3. Automobile : Car : Car is a four wheeled motor vehicle used for transportation.'''

for cat, item, desc in re.findall(r'^(?:\d+)\.([^:]+):([^:]+):(.*?)(?:\n\n|\Z)', txt, flags=re.M|re.S):
    print(cat)
    print(item)
    print(desc)
    print('-' * 80)

Prints:
 Food
 Cake
 Baked sweet food made from flour, sugar and other ingredients.
--------------------------------------------------------------------------------
 Electronics
 Computer
 A machine to carry out a computer programming operation.
   Computers mainly consists of a CPU, monitor, keyboard and a mouse.
--------------------------------------------------------------------------------
 Automobile
 Car
 Car is a four wheeled motor vehicle used for transportation.
--------------------------------------------------------------------------------

A: This may be a rudimentary approach, but it works on the sample input you've provided:
[0-9]+\s*.\s*(\w*)\s*:\s*(\w*)\s*:\s*((?:.*[\n\r]?)+?)(?=$|\d\s*\.)
Basically, we take as much text (including newlines) as possible in a description until we reach the end of the file, or another numerical index.
You can see the implementation here

redpajama_set_name: RedPajamaStackExchange


text:
Q: get array(s) from jquery / javascript function I've got a javascript function which generates and returns a new array (of arrays):
function getFees(id){

    var prep = new Array, primary = new Array, secondary = new Array, vce = new Array;

    prep[0]         = 733;
    primary[0]      = 792;
    secondary[0]    = 879;
    vce[0]          = 1108;

    if (id == 2) {

        prep[1] = (prep[0] - prep[0] * 5 / 100);
        prep[1] = Math.ceil(prep[1]);

        primary[1] = (primary[0] - primary[0] * 5 / 100);
        primary[1] = Math.ceil(primary[1]);

        secondary[1] = (secondary[0] - secondary[0] * 5 / 100);
        secondary[1] = Math.floor(secondary[1]);

        vce[1] = (vce[0] - vce[0] * 5 / 100);
        vce[1] = Math.floor(vce[1]);

    } else if (id == 3) {

        prep[2] = (prep[0] - prep[0] * 10 / 100);
        prep[2] = Math.ceil(prep[2]);

        primary[2] = (primary[0] - primary[0] * 10 / 100);
        primary[2] = Math.ceil(primary[2]);

        secondary[2] = (secondary[0] - secondary[0] * 10 / 100);
        secondary[2] = Math.floor(secondary[2]);

        vce[2] = (vce[0] - vce[0] * 10 / 100);
        vce[2] = Math.floor(vce[2]);

    } else if (id == 4) {

        prep[3] = (prep[0] - prep[0] * 50 / 100);
        prep[3] = Math.ceil(prep[3]);

        primary[3] = (primary[0] - primary[0] * 50 / 100);
        primary[3] = Math.ceil(primary[3]);

        secondary[3] = (secondary[0] - secondary[0] * 50 / 100);
        secondary[3] = Math.ceil(secondary[3]);

        vce[3] = (vce[0] - vce[0] * 50 / 100);
        vce[3] = Math.floor(vce[3]);

    } else if (id >= 5) {

        prep[4] = (prep[0] - prep[0] * 75 / 100);
        prep[4] = Math.floor(prep[4]);

        primary[4] = (primary[0] - primary[0] * 75 / 100);
        primary[4] = Math.ceil(primary[4]);

        secondary[4] = (secondary[0] - secondary[0] * 75 / 100);
        secondary[4] = Math.ceil(secondary[4]);

        vce[4] = (vce[0] - vce[0] * 75 / 100);
        vce[4] = Math.floor(vce[4]);

    }

    var newArray = [];

    newArray.push({'prep':prep}); //prep array = 733,697
    newArray.push({'primary':primary}); //primary array = 792,753
    newArray.push({'secondary':secondary}); //secondary array = 879,835
    newArray.push({'vce':vce}); //vce array = 1108,1052

    return newArray;
}

Essentially I've given an example in the .push sections at the bottom. I then call my function by doing this:
var fees = getFees(2);
alert(fees);

Which alerts this:
[object Object],[object Object],[object Object],[object Object]

If I do:
alert(fees.toSource());

I get this:
[{prep:[733, 697]}, {primary:[792, 753]}, {secondary:[879, 835]}, {vce:[1108, 1052]}]

What I need to be able to do is get the number from any of the items (prep/primary/secondary/vce) eg..
fees.prep[0];
fees.primary[1];

But when I try that, I get this error:
TypeError: fees.prep is undefined
What am I missing?? Any help would be greatly appreciated!! :)

A: you need to access like this
fees[0].prep[0];


text:
Q: ASP.NET MVC: How to plant a session cookie in a redirection from the controller? I'm trying to redirect from inside a MVC controller to a different external URL, only adding a session cookie that I'd be able to access after redirection.
I've been checking tens of Stackoverflow's questions and more, only found old or irrelevant answers, or with different technologies.
// GET: api/lem/fst?url=xxx
        [HttpGet]
        public ActionResult Get([FromQuery]string url)
        {
            var uri = new UriBuilder(url);
            var cookieOptions = new CookieOptions
            {
                Domain = uri.Host,
            };
            HttpContext.Response.Cookies.Append("key123", "value123", cookieOptions);
            return Redirect(uri.ToString());
        }

For example, if I send a GET to https://.../api/lem/fst?url=www.google.com,
I can see the cookie in the Set-Cookie response header from my server.
Also, redirection works fine, while I can't see the cookie anywhere in the request or response from google.
Thanks!

A: Take a look at: https://stackoverflow.com/a/6761443/7516160
Your code works fine: if it's the same domain then cookie from Get response is stored in cookie inventory and send (in request) to redirected url.
For testing host two seperate web apps on your local machine. For example redirect from localhost:50324 to localhost:47232.


text:
Q: Truncate a floating point number in prolog How to truncate a floating point number up to N decimal places in Prolog?
Is there any built-in tool for this?

A: Actually, it is easy to define a predicate truncate/3 in Prolog. Let's say that we want truncate a real number X up to N decimal places and store its result in Result. Using the mathematical function for truncation in this Wikipedia site, we can define the predicate as follows:
    % truncation for positive numbers
    truncate(X,N,Result):- X >= 0, Result is floor(10^N*X)/10^N, !.

    % truncation for negative numbers
    truncate(X,N,Result):- X <0, Result is ceil(10^N*X)/10^N, !.

I use cut because the two above cases are mutually exclusive.


text:
Q: Returning values and data typs validation in python How can I return (function polygon) not print all this x1 y1, x2 y2, ... values in tuples? Case of an errors of data typs float, how to use exceptions? I use Python 3.
import math
def polygon(num_of_edges, radius, startx, starty, turning_angle):
    turning_angle = 90 - turning_angle
    first_angle = math.radians (turning_angle)
    i = 0
    while (i < num_of_edges):
        angle = 2*math.pi*(-i)/num_of_edges+first_angle
        x = math.cos(angle)*radius+startx
        y = math.sin(angle)*radius+starty
        print ("x",i+1,"=",x)
        print ("y",i+1,"=",y)
        i = i + 1

A: You have to collect those points in a list, then return that list. You can also make your code somewhat shorter by using a for loop instead of while:
def polygon(num_of_edges, radius, startx, starty, turning_angle):
    turning_angle = 90 - turning_angle
    first_angle = math.radians(turning_angle)
    points = []
    for i in range(num_of_edges):
        angle = 2*math.pi*(-i)/num_of_edges+first_angle
        x = math.cos(angle)*radius+startx
        y = math.sin(angle)*radius+starty
        points.append((x, y))
    return points

Instead of collecting them in a list, you could also make your function a generator:
def polygon(num_of_edges, radius, startx, starty, turning_angle):
    turning_angle = 90 - turning_angle
    first_angle = math.radians(turning_angle)
    for i in range(num_of_edges):
        angle = 2*math.pi*(-i)/num_of_edges+first_angle
        x = math.cos(angle)*radius+startx
        y = math.sin(angle)*radius+starty
        yield (x, y)


text:
Q: openedge logging framework roll files We are using the Openedge logging framework and trying to figure out how configure a file rolling setup.
I tried setting up ${t.YYYY}-${t.MM}-${t.DD}-${t.MMM} for testing and see if I would get a new file every minute but the log files do not roll. It just keeps adding to the log which does get created with the right name
"Common.v1.Logging": {
"logLevel": "TRACE",
"filters": [
"myfilter",
{
"name": "NAMED_FILE_WRITER",
"fileName": "../logs/logFile.%t{yyyy}.log",
"appendTo": true
}
]
}

A: This functionality is not currently available in the OpenEdge.Logging code. Please log an idea for it at https://openedge.ideas.aha.io/ so that we can add it to our backlog.
Take a look at the the doc on custom filters; you can create your own rolling logfile filter.


text:
Q: php: Internal Server Error I am trying to create a MVC framework therefore I have to change the urls and to do this, I have to configure the .htaccess file. Following commands are written in the file:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA.L]

I am using the wamp server and rewrite_module is checked in apache modules, still getting the Internal server error as:
Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, admin@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

What is the solution to the problem?

A: Try:
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Notice the , not .


text:
Q: Implementing Autoplay on glider.js So I'm working with glider.js (https://nickpiscitelli.github.io/Glider.js/) on my website for handling slides, because I really want to keep it minimal (I know there are other sliders out there, but glider.js is the lightest). However, I really need the autoplay function, but I can't seem to be able to make it work (I don't really know my way around JS, I just copy code snippets for things I need)
I found some code for an autoplay, it looks like this:
function sliderAuto(slider, miliseconds) {
 slider.isLastSlide = function() {
   return slider.page >= slider.dots.childElementCount - 1;
 }

 var slide = function() {
   slider.slideTimeout = setTimeout(function() {
     function slideTo() {
       return slider.isLastSlide() ? 0 : slider.page + 1;
     }

     slider.scrollItem(slideTo(), true);
   }, miliseconds);
 }

 slider.ele.addEventListener('glider-animated', function(event) {
   window.clearInterval(slider.slideTimeout);
   slide();
 });

 slide();
}

But I don't know how to activate it, to make it work. I know I should pass the parameters to "slider" and "miliseconds", but I don't know what exactly should I pass, should I set a special class to each slide, and pass that class? Let's say my html is the following:

your content here

your content here

your content here

your content here

How do I make the autoplay work? Thanks!

A: Based on the docs that you've linked and the code snippet i would say that
First things first, slider parameter is supposed to be your glidder object (what you created with new Glidder(..., and milliseconds is the amount of time in milliseconds that each slide will be visible.
Now, an example of what it could look like:

1

2

3

4

const glider = new Glider(document.getElementById('glider'));

function sliderAuto(slider, miliseconds) {
 const slidesCount = slider.track.childElementCount;
 let slideTimeout = null;
 let nextIndex = 1;

 function slide () {
   slideTimeout = setTimeout(
     function () {
       if (nextIndex >= slidesCount ) {
         nextIndex = 0;
       }
       slider.scrollItem(nextIndex++);
     },
     miliseconds
   );
 }

 slider.ele.addEventListener('glider-animated', function() {
   window.clearInterval(slideTimeout);
   slide();
 });

 slide();
}

sliderAuto(glider, 1000)

I've edited the snippet a bit because you don't seem to use dots.
working fiddle

A: I have tweaked the accepted answer to pause autoplay on mouse hover. In addition, you can handle autoplay loop with the repeat argument of the slideAutoPaly function.
var slider = new Glider(document.querySelector('.glider'), {
    slidesToScroll: 1,
    slidesToShow: 1,
    dots: '#dots',
    arrows: {
        prev: '.glider-prev',
        next: '.glider-next'
    }
});

slideAutoPaly(slider, '.glider');

function slideAutoPaly(glider, selector, delay = 5000, repeat = true) {
    let autoplay = null;
    const slidesCount = glider.track.childElementCount;
    let nextIndex = 1;
    let pause = true;

    function slide() {
        autoplay = setInterval(() => {
            if (nextIndex >= slidesCount) {
                if (!repeat) {
                    clearInterval(autoplay);
                } else {
                    nextIndex = 0;
                }
            }
            glider.scrollItem(nextIndex++);
        }, delay);
    }

    slide();

    var element = document.querySelector(selector);
    element.addEventListener('mouseover', (event) => {
        if (pause) {
            clearInterval(autoplay);
            pause = false;
        }
    }, 300);

    element.addEventListener('mouseout', (event) => {
        if (!pause) {
            slide();
            pause = true;
        }
    }, 300);
}

Also, check the Github issue: https://github.com/NickPiscitelli/Glider.js/issues/43


text:
Q: Finding the value of $f(2001)$ given the functional equation $f\bigl(f(n)\bigr)= 3n$ and strict monotonicity of $f:\mathbb N\to\mathbb N$
Let $f:\mathbb N\to \mathbb N$ be a strictly increasing function such that $f\bigl(f(n)\bigr)= 3n\ \forall\ n\in \mathbb N$
Find the value of $f(2001).$

Now I tried to solve this by myself but I'm stuck somewhere in the middle of my solution. Please help me with my solution. Also my solution is a bit long as I'm writing almost every observation I made, so please be kind enough to bear with me.
My Approach:
We know that $f$ is strictly increasing.
Suppose for some $n_1$ and $n_2$, we have $f(n_1)=f(n_2)$. Thus $f\bigl(f(n_1)\bigr)=f\bigl(f(n_2)\bigr)\implies 3n_1=3n_2$ hence $n_1=n_2$. (I just realized that his step was actually not required.)
$\therefore$ $f$ is an injective strictly increasing function.
Suppose for some $n\in \mathbb N$, we have $f(n)\leq n$, then $f\bigl(f(n))\leq f(n)\leq n$ as $f$ is strictly increasing.
This gives us $3n\leq n$ which isn't true for any $n\in \mathbb N$.
$\therefore f(n)>n\ \forall\ n\in \mathbb N $
Now suppose $f(1)=l>1$. Thus $f\bigl(f(1)\bigr)=3=f(l)>f(1)=l\implies 1<l<3$ and since $l\in \mathbb N$, we know that $f(1)=2$.
This means that $f\bigl(f(1)\bigr)=f(2)=3$ and $f\bigl(f(2)\bigr)=f(3)=6$ and so on.
A few such values are:
$f(1)=2$
$f(2)=3$
$f(3)=6$
$f(6)=9$
$f(9)=18$
$f(18)=27$
$f(27)=54$
$f(54)=81$
Now here a pattern can be observed.
Claim: $f(3^n)=2\cdot3^n$
Proof: Suppose the above claim is true. Then $f\bigl(f(3^n)\bigr)=f(2\cdot3^n)=3^{n+1}$. Now $f\left(3^{n+1}\right)=f\bigl(f(2\cdot3^n)\bigr)=2\cdot3^n\cdot3=2\cdot3^{n+1}$
$\therefore$ $f(3^n)=2\cdot3^n$ and $f(2\cdot3^n)=3^{n+1}$
One more thing can be observed here that if $3^n<k<2\cdot3^n$, then $2\cdot3^n<f(k)<3^{n+1}$ and since there are exactly $3^n$ permitted values for both $k$ and $f(k)$ and $f$ is strictly increasing, the unique function satisfying the given condition can easily be found.
But unfortunately $2\cdot3^6<2001<3^7$, thus a unique function cannot be found using the observation stated above.
Now this is where I am stuck. Firstly, is this question solvable using my approach? If yes, then what should I add to my approach in order to reach the solution? Please help.
THANKS

A: $f(f(7))=21$, but we have $f(12)=21$ from the "exactly $3^n$ permitted values" point, so $f(7)=12$. In the same way we can show $f(8)=15,f(19)=30$ and so on. In general
$$f(3^n)=2\cdot3^n$$
$$f(2\cdot3^n)=3\cdot3^n$$
$$f(3^n+k)=2\cdot3^n+k,0\le k\le3^n$$
$$f(2\cdot3^n+k)=3\cdot3^n+\mathbf{3k},\ 0\le k\le 3^n$$
Thus
$$f(2001)=f(2\cdot3^6+543)=3\cdot3^6+3\cdot543=3816$$
$f$ is OEIS A003605. The same question but asking for $f(1992)$ was problem 5 of BMO 1992.


text:
Q: jQuery multi select drop down and SharePoint I'm hoping I could get some help with multiple drop down selection.  I have a SharePoint jQuery form that I created and I am trying to populate the multiple selection drop down with data.  The data in the column is comma delimited (ex: Contract A, Contract B).
Please take a look on my SharePoint site. It's better to show to understand.  As you will see, the "Contracts" column is the last column and when you click edit, the "Contract" multiple selection element does not populate.


text:
Q: Consulta em um banco de questões que não pode retornar acertos Eu tenho um banco de questões organizado da seguinte forma:
questoes:
    ID | pergunta            | a    | b     | c    | d      | e     | correta
    1  | Qual meu nome?      | joao | pedro | jose | mateus | lucas | pedro
    2  | Qual a minha idade? | 15   | 18    | 20   | 22     | 25    | 18

Quando o usuário acessa sua página de perfil, uma pergunta aleatória deste banco de dados deverá aparecer pra ele. No entanto, perguntas que ele já acertou no passado não deverão aparecer novamente.
Para isso, tentei criar uma nova tabela que relacionasse as questões com o usuário, como no exemplo abaixo:
cad_questoes:
id_tabela | id_questao | id_usuario | acerto
1         | 1          | 2          | sim
2         | 2          | 2          | nao
3         | 1          | 1          | sim

Para pedir a pergunta ao banco de dados que será mostrada ao usuário, utilizo o seguinte comando no PHP/MySQL:
$busca_questoes = "SELECT * FROM cad_questoes
                    INNER JOIN questoes ON cad_questoes.id_questao = questoes.ID
                    WHERE acerto='nao' ORDER BY rand() LIMIT 1";

No entanto, para que este comando funcione na prática, eu teria que atualizar o banco de dados cad_questoes manualmente para notificar que existem perguntas que não foram respondidas, mas eu gostaria que isso fosse feito automaticamente.
Minha pergunta é: Como solicitar uma pergunta ao banco de dados que o usuário não tenha respondido ela e como fazer essa verificação?
Espero que tenha conseguido ser claro, fico a disposição para fornecer quaisquer informações que contribuam para a pergunta.

A: Uma forma de fazer seria buscando no banco todas questões foram respondidas por qualquer usuário exceto o em questão, na query a seguir eu utilizei DISTINCT para não retornar perguntas repetidas.
$buscaQuestoes = "SELECT DISTINCT c.* FROM cad_questoes as cq
        INNER JOIN questoes as q ON cq.id_questao = q.ID
        WHERE acerto = 'nao'
        WHERE cq.id_usuario <> '$idUsuario'";

Outro método possível é adicionar uma coluna cad_questoes.respondida para identificar se a questão já foi respondida, também seria necessário inicializar uma linha pra cada questão ao criar um novo usuário.


text:
Q: nginx ignores Port in redirect and logs 499 I want to setup an nginx proxy for a legacy systems api. My barebone Setup for the redirect does work for redirects without ports:
# test redirecting to html
location /api  {
  proxy_pass https://my.host.de/main.html;
}

But some test systems do have Ports inside their HTTPS location e.g. https://my.host.de:8441/.../
# test redirecting to html
location /api  {
  proxy_pass https://my.host.de:8441/main.html;
}

So if I add a rule like this the nginx will log a 499 error and the Requesting Browser will endlessly loop, and the Target System wont show any logs (so no request was made).
I tried using proxy_redirect http://my.host.de:8441/ http://my.host.de/ (and the other way arouund) which didnt show any improvments. My guess is that the Port is not used? Since there is no request recorded on the target system.
Any Ideas what the problem could be?


text:
Q: Control PointToClient() vs PointToScreen() The MSDN does not provide, IMHO, a clear difference between Control.PointToScreen(link) and Control.PointToClient(link) methods.
Is there somebody who could explain in a few simple words what is the difference between these methods. Especially is unclear for me the notion of "Client".
I understand PointToScreen the real screen coordinate (with [0, 0] in the left upper corner of the screen) of the given point.
By example, debugging some code I have
?click.Location
{X = 3 Y = 9}

?shapeSender.PointToClient(click.Location)
{X = -470 Y = -565}

?shapeSender.PointToScreen(click.Location)
{X = 476 Y = 583}

Thanks.

A: The PointToClient method is the reverse of the PointToScreen method.
(If it wasn't so long and repetitive, they would be named ScreenPointToClientPoint and ClientPointToScreenPoint.)
You use the conversions when you have one kind of coordinates and need the other, for example if you have the coordinates of a mouse click relative to the screen, and need to know where in the control the user clicked.
If you convert a screen point that is outside the client area, you will get coordinate components that are either negative or larger than the size of the control client area.

A: The "client" coordinates are relative to the top left of a control's client area. The "screen" coordinates are relative to the top left of the (primary) monitor.
The "client area" is the area of a control in which child controls can be placed. The client rectangle of a form is the area inside the form, excluding the borders and title bar. For most other controls, the client area is the same as the area that the control occupies on the screen.
PointToScreen converts client coordinates to screen coordinates. PointToClient does the reverse: it converts screen coordinates to client coordinates.

A: Best way to think of it is: relative vs absolute coordinates. Where the relative coordinate is relative from the upper left corner of the client area of a window.  The client area of a window is a window minus its border. Relative coordinates are useful because they don't change when the user moves a window and don't depend on the border and caption size of the window.
Most coordinates in WinForms are relative coordinates, MouseEventArgs.Location for example. Some are absolute, Cursor.Position for example. If you pass a relative coordinate to PointToClient you'll get garbage, as you saw in your debug session.  It must be an absolute coordinate.
Some coordinate properties can seemingly be both, Control.Location for example.  On a child control it represents the control's location relative from its container.  A form's Location is absolute.  That seeming contradiction disappears when you think a Control.Location as relative from a control's Parent.  The Parent of a form is the desktop.
A common usage is to map a coordinate relative to one control to another control.  First map to absolute screen coordinates with control1.PointToScreen(), then map the result to the other control with control2.PointToClient().  The Point value changes by the offset between the controls, regardless of who their parents are. Doing it any other way is very painful.
Keep out of trouble by only ever passing an absolute coordinate to PointToClient and a relative coordinate to PointToScreen.

A: Suppose a screen is 800x600 and a window is at 50,50 having a size of 200x200 pixels. If the point P lies at 10,10 relative to the window's upper-left then PointToScreen(P) will return 60,60. If this P is given to PointToClient(P) with the window handle then we will get 10,10 again.
Hope that clears the confusion


text:
Q: How to deploy AWS Lambda Function Correctly Using serverless, I am trying to deploy a lambda function through AppSync. I see that my function gets deployed in the AWS Console, however, it is showing that it's over 50MB and can't display the inline editing. How do I properly deploy my lambda function?
Here's what the console looks like.

A: Like @LLL said, the lambda function has already been deployed. One way you can confirm that is by going to your CloudFormation stack and check the status of the lambda function. If it's successfully deployed the status should be CREATE_COMPLETE or UPDATE_COMPLETE.
If you would like to view the deployed function, you can click the Actions dropdown the page you visited in the image and click Export function. This will download all the files deployed with your lambda function.


text:
Q: Sort array contains numeric string using c# array Please refer the following array,
string[] numArray = {"two","three","one", "seven","nine", "two", "one"};
we need sort this array by numeric and return the sorted array like
string[] output = {"one","one","two","two","three","seven","nine"};

Please suggest the best logic in c# code using only string array or any method.

A: You can store numbers in a dictionary where the keys would be strings (e.g. "two") and the values would be integers (e.g. 2). And by using LINQ you could first replace the strings in your input array with numbers and then sort them with OrderBy. After the numbers are sorted you can convert the numbers back to strings:
Dictionary<string, int> numbers = new Dictionary<string, int>() {
    { "one", 1 },
    { "two", 2 },
    { "three", 3 },
    { "four", 4 },
    { "five", 5 },
    { "six", 6 },
    { "seven", 7 },
    { "eight", 8 },
    { "nine", 9 },
};

string[] wordArray = { "two", "three", "one", "seven", "nine", "two", "one" };

var numberArray = Enumerable.Range(0, wordArray.Length)
                            .Select(i => numbers[wordArray[i]])
                            .OrderBy(x => x).ToArray();

var output = Enumerable.Range(0, numberArray.Length)
                       .Select(i => numbers.FirstOrDefault(x => x.Value == numberArray[i]).Key)
                       .ToArray();

Output = {"one","one","two","two","three","seven","nine"}

A: You need give an order (actually a equivalence relation) to be able to sort. The order on characters is usually a,b,c,... and the order usually given on words such as 'one' is called lexicographic order. However you want to sort by the meaning behind, its semantic: integers.
Your computer doesn't know that you want this, so you need to provide the meaning., which is through a function (technically a dictionary).
Computers have order on integers builtin (it's also builtin in standard integers, in usual mathematics). Hence you need to provide a one-to-one function (eg., with a dictionary, or a list of uples eg., List<(string, int)>), so you sort your words from their integer peer. You can also map words with letters: one-a, two-b, ... and when you reach z, you continue with aa (it's a base 27 counting). You can also do this with bits (base 2), base64, etc. But there is always a map with integers.
IMHO, understanding is more important than knowing. Now you can code many solutions.


text:
Q: How to use python csv module in a class I am trying to instantiate a csv writer in the init method of a class and I want to use it from a class method storeToCSV(). For some strange reason this does not work. No data is written to the file when I call self.storeToCSV(['test']). What is the reason for this and how can I fix this?
class postprocessing:
    def __init__(self,topic):

        try:
           os.remove(topic+'.csv')
        except:
           pass

        csvfile = open(topic+'.csv', 'a')
        self.csvwriter = csv.writer(csvfile, delimiter=';',quotechar='"')
        self.csvwriter.writerow(['id','url1'])

    def storeToCSV(self, arg_a):
        print self.csvwriter.writerow(arg_a)

A: I think you need to add a
csvfile.close()

after writing the data.

A: The code works here. Calling
postprocessing('afile').storeToCSV(['1', 'c9.io'])
Fills up afile.csv with
id;url1
1;c9.io

Make sure you don't read from the file before the writer object is deleted and the file object is closed as data isn't written immediately to disk.
And don't close the file before you're done writing to it.


text:
Q: Parton model and impulse approximation for the process $2\to 1$ Consider a process
$$
\tag 1 N+N\to X+\text{all},
$$
where $N$ are nucleons and $X$ is some massive particle. Assuming the parton model is valid and there is vertex $PP'X$, where $P,P'$ are partons inside the nucleons, the process $(1)$ can be described as the $2 \to 1$ Drell-Yan like process
$$
\tag 2 P+P'\to X
$$
Following Drell and Yan, let's assume that the parton model is applicable if the lifetime of the virtual state with the partons inside the nucleon is much larger than the time of the interaction $(2)$,
$$
\tag 3 t_{\text{lifetime}}\gg t_{\text{int}}
$$
If it holds, parton can be assumed as free particle carrying amount $x$ of the nucleon momentum, and probabilistic interpretation of the process $(2)$ becomes valid (this approximation is known as impulse approximation).
Assuming that nucleons have sufficiently large momenta $|\mathbf p|$ at their CM frame, $t_{\text{lifetime}}$ can be estimated as (using time-energy uncertainty principle)
$$
\tag 4 t_{\text{lifetime}} \simeq 2|\mathbf p|/m_{N}^{2}
$$
As for the interaction time, naively I think that it can be estimated using Fermi Golden rule,
$$
\tag 5 t_{\text{int}}^{-1}\simeq \frac{1}{V}\frac{1}{2E_{P}2E_{P'}}\int |M_{\text{hard}}|^{2}\delta(p_{X} - p_{P}-p_{P'})\frac{d^{3}\mathbf p_{X}}{(2\pi)^{3}2E_{X}},
$$
where $V\simeq m_{N}^{-3}\gamma_{N}^{-3}$ is the proper volume of the nucleon and $M_{\text{hard}}$ is the matrix element of the process $(2)$.
Assuming that this is correct, the validity criterion $(3)$ depends on the mass of $X$ particle and on its coupling to partons. However, in the literature (see this overview article for example, expression $(33)$ and corresponding discussion) the criterion $(3)$ is replaced by very simple relation
$$
\tag 6 s_{PP'} \gg \Lambda_{\text{QCD}}^{2},
$$
where $s_{PP'} = m_{X}^{2}$ is partonic invariant mass. Therefore we replaced probability criterion by more special QCD perturbativity criterion.
My question is the following. Whereas $(3)$ is model dependent criterion (it depends on the type of nucleon, the coupling of $X$ to partons and $X$ mass, as is demonstrated by $(5)$-$(6)$), $(6)$ depends only on $X$ mass. I don't clearly understand why it is reasonable to replace $(3)$ by $(6)$, since naively $(3)$ can be violated while $(6)$ holds, and vice versa. Could you please comment on that?
P.S. In principle, my question is related to general process $2\to n$, but for clarity let's concentrate on $2 \to 1$ process.


text:
Q: Draw multiple canvas from inputs and calculate how to align them A small project is on following address: PLEASE CLICK HERE
Plan is to draw multiple rectangle in canvas based on user input (width, height, color) and align them in field bellow and to take smaller area as possible. Field is Grid Preview.
Current JavaScript that successfully draw one rectangle is:
var canvas = document.getElementById('canvasgrid');
canvas.width = 855;
canvas.height = 500;
var context = canvas.getContext('2d');

function draw(){
    var x = document.getElementById("width").value;
    var y = document.getElementById("height").value;
    var boja = document.getElementById("color").value;
    var arr = [x,y,boja];
    let pos = {x: 0, y: 0};
    arr.forEach(p => {
        context.rect(pos.x, pos.y, p.w, p.h);
        pos.x += p.w; // should return to zero at the edge of the canvas
        pos.y += p.h;
        context.beginPath();
        context.stroke();
        context.fillStyle = boja;
        context.fill();
        context.fillStyle = "white";
        context.font="bold 10px sans-serif";
        context.textAlign="center";
        context.textBaseline = "middle";
        context.fillText(x+'x'+y, 10+(x/2),10+(y/2));
    });
}

I do have a problem loading other inputs, after user click on green button.
Color JavaScript plugin that I am using is jsoclor, also not sure how to load it in each duplicated field.
Please let me know if any additional info is needed. All codes can be seen in source files via mentioned link.
Thanks.

A: A simple answer might be to store the user input in an array of objects (eg [{w: ..., h: ..., color: ...}, {...}...]) and iterate over that in your function.
In your function you might then have something like the following:
let pos = {x: 0, y: 0};
arr.forEach(p => {
  context.rect(pos.x, pos.y, p.w, p.h);
  pos.x += p.w; // should return to zero at the edge of the canvas
  //pos.y += left as an exercise to the reader ;)
});


text:
Q: When tossing a coin, what's the likelihood of coming up heads when it came up 999 tails consecutively? Consider that you're tossing a coin $1000$ times.
First $999$ times, it came up heads.
Is it $50\%$ chance that the coin tails after $1000^{th}$ trial?
Are these discrete events?
Since the mean of these experiments is $500H$ $500T$, each heads increases the probablility of tails, doesn't it?
Edit: Let me ask the question that way:
If I toss the coin 10 times, $5H$ and $5T$ is the mean.
If $TTT$ comes up, then probability of $H$ would be $\frac{5}{7}$, would it not?

A: Assuming you have a fair coin, then yes, it is $\frac{1}{2}$. Thinking otherwise is known as the gambler's fallacy.


text:
Q: JAXRS vs JAXWS(Heap utilization) We've written a java CXF service, which has both JAXWS and JAXRS endpoints. The client can request one of them to get a response.
Some more details:
We executed stress tests on this service. For that we set Xmx to 2GB and used JProfiler to check heap utilization.
We detected a huge difference in heap utilization between JAXWS and JAXRS for similar requests.
Used heap space is ..

*

*1.7 GB for JAXWS and

*0.4 GB for JAXRS

Question:
Has anyone experienced this?
Is the difference based on the way these endpoints create output XML?


text:
Q: automation testing of window based application I have a window based application (c++) with list of log files;
 number of logs would vary.
When each of the listed log file(each has different name) is double clicked a window pops up.The success criteria here is the successful opening of window on double click - this is to verified for each log file
How can I automate this process?

A: I would look into a program like Winium. It is a Selenium-based tool for testing windows apps. For further info, check this out: https://github.com/2gis/Winium
An alternative could be an Robotic Process Automation tool (RPA) like UIPath. It is not a testing tool per se, but it can be used as such and get your job done. There is a free community version available. Here's a link: https://www.uipath.com/


text:
Q: What is the incantation of the apparition spell? Is there any canon reference of someone saying an incantation when apparating?
I don't remember one and even on the lessons in the sixth year, the teacher never mentions any.

A: There isn't a spell. We see the complete instructions, and it doesn't have a spell:

He waved his wand. Old-fashioned wooden hoops instantly appeared on the floor in from of every student.
"The important things to remember when Apparating are the three D's!" said Twycross. "Destination, Determination, Deliberation!
"Step one: fix your mind firmly upon the desired destination," said Twycross. "In this case, the interior of your hoop. Kindly concentrate upon that destination now."
"Step two," said Twycross, "focus your determination to occupy the visualised space! Let your yearning to enter it flood from your mind to every particle of your body! "
"Step three," called Twycross, "only when I give the command... turn on the spot, feeling your way into nothingness, moving with deliberation. On my command, now... one —"
Harry Potter and the Half-Blood Prince, Chapter 18


text:
Q: Least squares projection Let $x_1$ and $x_2$ such that $x_1\ne x_2$ are two least-squares solutions to the equation $Ax=b$.
Prove that $Ax_1=Ax_2$, meaning that the projection of $b$ on $Col(A)$ is unique.
My way:
I know that the norm of the residual vectors is the same. I'd like to show that $Ax_1-b$=$Ax_2-b$ but I stuck here.

A: First, we know that $Ax_1-b$ and $Ax_2-b$ are in the left nullspace of $A$ (i.e. the orthogonal complement of the image of $A$). This is because, if $Ax_1-b$ was not in the left nullspace of $A$, then the residual $\|Ax_1-b\|$ would not be minimized and $x_1$ would not be a least-squares solution.
Now, notice that:
$$b=Ax_1-(Ax_1-b)=Ax_2-(Ax_2-b)\implies Ax_1-Ax_2=(Ax_1-b)-(Ax_2-b)$$
The left side of this equation is clearly is in the image of $A$, since $Ax_1$ and $Ax_2$ are both in the image of $A$. Meanwhile, the right side of this equation is in the left nullspace of $A$, since $Ax_1-b$ and $Ax_2-b$ are both in the left nullspace of $A$. Thus, this quantity is in both the image and the left nullspace of $A$, but since these two subspaces are orthogonal complements of each other, the only way a vector can be in both of them at the same time is if that vector is $\vec 0$.
Therefore:
$$Ax_1-Ax_2=\vec 0\implies Ax_1=Ax_2$$


text:
Q: Add indicator to BottomNavigationBar in flutter any way to add indicator to BottomNavigatorBarItem like this image?

A: This package should be able to help you achieve it.

A: You can use a TabBar instead of a BottomNavigationBar using a custom decoration:
class TopIndicator extends Decoration {
  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _TopIndicatorBox();
  }
}

class _TopIndicatorBox extends BoxPainter {
  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration cfg) {
    Paint _paint = Paint()
      ..color = Colors.lightblue
      ..strokeWidth = 5
      ..isAntiAlias = true;

    canvas.drawLine(offset, Offset(cfg.size!.width + offset.dx, 0), _paint);
  }
}

Then pass the decoration to the TapBar using TapBar(indicator: TopIndicator ...).

To use the TabBar as the Scaffold.bottomNavigationBar, you will most likely want to wrap it in a Material to apply a background color:
Scaffold(
  bottomNavigationBar: Material(
    color: Colors.white,
    child: TabBar(
      indicator: TopIndicator(),
      tabs: const <Widget>[
        Tab(icon: Icon(Icons.home_outlined), text: 'Reward'),
        ...
      ],
    ),
  ),
  ...
)

Thanks Ara Kurghinyan for the original idea.

A: I've had the same problem and all the packages I found seem to require raw IconData, which makes it impossible to use widget functionality like number badges (e.g. the number of unread chat messages).
I came up with my own little solution; first, I made a widget to display the actual indicators:
class TabIndicators extends StatelessWidget {
  final int _numTabs;
  final int _activeIdx;
  final Color _activeColor;
  final Color _inactiveColor;
  final double _padding;
  final double _height;

  const TabIndicators({
    required int numTabs,
    required int activeIdx,
    required Color activeColor,
    required double padding,
    required double height,
    Color inactiveColor = const Color(0x00FFFFFF),
    Key? key }) :
    _numTabs = numTabs,
    _activeIdx = activeIdx,
    _activeColor = activeColor,
    _inactiveColor = inactiveColor,
    _padding = padding,
    _height = height,
    super(key: key);

  @override
  Widget build(BuildContext context) {

    final elements = <Widget>[];

    for(var i = 0; i < _numTabs; ++i) {
      elements.add(
        Expanded(child:
          Padding(
            padding: EdgeInsets.symmetric(horizontal: _padding),
            child: Container(color: i == _activeIdx ? _activeColor : _inactiveColor),
          )
        )
      );
    }

    return
      SizedBox(
        height: _height,
        child: Row(
          mainAxisSize: MainAxisSize.max,
          children: elements,
    ),
      );
  }
}

This can be prepended to the actual BottomNavigationBar like this:
bottomNavigationBuilder: (context, tabsRouter) {
  return Padding(
    padding: const EdgeInsets.only(top: 4.0),
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        TabIndicators(
          activeIdx: tabsRouter.activeIndex,
          activeColor: Theme.of(context).primaryColor,
          numTabs: 4,
          padding: 25,
          height: 4,
        ),
        BottomNavigationBar(...

This works perfectly well for me, but to make it look decent, you'd have to set the BottomNavigationBar's elevation to zero, otherwise there's still a faint horizontal line between the indicators and the icons.


text:
Q: score in pong game. How to update the score in a pong game? ok so i'm creating the game pong and i'm currently setting up the score.There is a small bug I'm unable to fix. The code I tried was R2Score = R2Score + 1 for it to add a point every time it gets out of the screen. It is telling me there's an error with this code and i'm under how to fix it. Also as it is going to get out of the screen the ball slows down which I'm confused on why that could also be happening.
ERROR:

Traceback (most recent call last):
File "/Users/name/Documents/PongGame.py", line 130, in <module>
   R2Score = R2Score + 1
TypeError: unsupported operand type(s) for +: 'pygame.Surface' and 'int'

# import the necessary modules
import pygame
import sys
import time

#initialize pygame
pygame.init()
screenSize=(700,500)
screen=pygame.display.set_mode((screenSize), 0)

# set the caption for the screen
pygame.display.set_caption("Pong Game")

# define colours you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)

# set the size for the surface (screen)
screen_h = screen.get_height()
screen_w = screen.get_width()
cx = int(screen_w/2)
cy = int(screen_h/2)

#initialize variables for player
#variables for first rectangle
R1x = 660
R1y = 300
R1w = 10
R1h = 132

R1dx = 0
R1dy = 0
R1_score = 0

#variables for second rectangle
R2x = 10
R2y = 2
R2w = 10
R2h = 132

R2dx = 0
R2dy = 0
R2_score = 0

#ball variables
bx = cx
by = cy
dby = 3
dbx = 3
br = 5
cy =  screen.get_height()/2
cx =  screen.get_width()/2

# variable for scores
R1_score = 0
R2_score = 0

playerRect = pygame.Rect(R1x, R1y, R1w, R1h)
playerRect2 = pygame.Rect(R2x, R2y, R2w, R2h)
ballRect = pygame.Rect (cx,cy,30,30)

#speed
speed = 3

fontsize = 50
fontScore = pygame.font.SysFont('arial', 50)
fontScore = pygame.font.SysFont('arial', 50)

R1Score = fontScore.render(str(R1_score), True, (WHITE))
R2Score = fontScore.render(str(R2_score), True, (WHITE))

# speed of object "clock"
clock = pygame.time.Clock()

# set main loop to True so it will run
main = True
# main loop
while main:
    for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
        if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
            main = False         # set the "main" variable to False to exit while loop
        if event.type ==pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                R1dx = 0
                R1dy = -speed
            elif event.key == pygame.K_DOWN:
                R1dx = 0
                R1dy = speed
            if event.key == pygame.K_w:
                R2dx = 0
                R2dy = -speed
            elif event.key == pygame.K_s:
                R2dx = 0
                R2dy = speed
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                R1dx = 0
                R1dy = 0
            elif event.key == pygame.K_w or event.key == pygame.K_s:
                R2dx = 0
                R2dy = 0

    playerRect.y = playerRect.y + R1dy
    playerRect2.y = playerRect2.y + R2dy
    ballRect.move_ip(dbx,dby)

    R1y = R1dy + R1y
    R2y = R2dy + R2y
    bx = dbx + bx
    by = dby + by

    if R1y >= screen_h - 80 or R1y < 0:
        R1dy = 0
    if R2y >= screen_h - 80 or R2y < 0:
        R2dy = 0
    if by >= screen_h - br:
        dby = -1
    if by <= 15:
        dby = 1
    if bx >= R2x - br and by - R2y > 0 and by - R2y <100:
        dbx = -1
    if bx >= R1x - br and by - R1y > 0 and by - R1y <100:
        dbx = 1
    if bx == 1:
        R2Score = R2Score + 1
        pause = True
    if bx == 699:
        R2Score = R2Score + 1
        pause = True

    #collision of ball
    if ballRect.top <= 0:
        dby = -dby
    if ballRect.bottom >= screen_h:
        dby = -dby

    if ballRect.colliderect(playerRect2):
        dbx = -dbx
    if ballRect.colliderect(playerRect):
        dbx = -dbx

    screen.fill(BLACK)

    # draw the shapes
    pygame.draw.rect(screen, WHITE,(playerRect),0)
    pygame.draw.rect(screen, WHITE,(playerRect2),0)
    pygame.draw.circle(screen, RED,ballRect.center,br,0)
    screen.blit(R1Score, (280,10))
    screen.blit(R2Score, (400,10))

    # we are using .flip() here,  it basically works the same as .update()
    time.sleep(0.005)
    pygame.display.flip()

# quit pygame and exit the program (i.e. close everything down)
pygame.quit()
sys.exit()

A: R2Score is a pygame.Surface object, so what do you expect by R2Score = R2Score + 1?
You can't add 1 to a Surface.
If you wan to increment the score, then you have to (re-)render the Surface. e.g.:
if bx == 1:
    R1_score += 1
    R1Score = fontScore.render(str(R1_score), True, (WHITE))


text:
Q: Prove $\int_0^1\frac{\log(t^2-t+1)}{t^2-t}\mathrm dt=\frac{\pi^2}9$ I am in the middle of proving that
$$\sum_{k\geq1}\frac1{k^2{2k\choose k}}=\frac{\pi^2}{18}$$
And I have reduced the series to
$$\sum_{k\geq1}\frac1{k^2{2k\choose k}}=\frac12\int_0^1\frac{\log(t^2-t+1)}{t^2-t}\mathrm dt$$
But this integral is giving me issues. I broke up the integral
$$\int_0^1\frac{\log(t^2-t+1)}{t^2-t}\mathrm dt=\int_0^1\frac{\log(t^2-t+1)}{t-1}\mathrm dt-\int_0^1\frac{\log(t^2-t+1)}t\mathrm dt$$
I preformed the substitution $t-1=u$ on the first integral, then split it up:
$$\int_0^1\frac{\log(t^2-t+1)}{t-1}\mathrm dt=\int_{-1}^0\frac{\log(2u+i\sqrt3+1)}u\mathrm du+\int_{-1}^0\frac{\log(2u-i\sqrt3+1)}u\mathrm du-2\log2\int_{-1}^0\frac{\mathrm du}u$$
But the last term diverges, but I don't know what I did wrong. In any case, I would be surprised if there wasn't an easier way to go about this. Any suggestions? Thanks.

A: I start from
$$
\int_0^1\frac{\log(t^2-t+1)}{t-1}\mathrm dt-\int_0^1\frac{\log(t^2-t+1)}t\mathrm dt .
$$
In the first integral, substitute $t=1-u$. Then
$$
\int_0^1\frac{\log(t^2-t+1)}{t-1}\mathrm dt
=-\int_0^1\frac{\log(u^2-u+1)}{u}\mathrm du .
$$
So you get
$$
\sum_{k\geq1}\frac1{k^2{2k\choose k}}
= -\int_0^1\frac{\log(t^2-t+1)}t\mathrm dt .
$$
ADDENDUM
After some sleep, I managed to compute the integral with the help of polylogarithm.
For $n\in\mathbb R$, define
$$
\mathrm{Li}_n(z) = \sum_{k=1}^\infty \frac{z^k}{k^n}.
$$
Some simple facts.

*

*$\mathrm{Li}_1(z)=-\log(1-z)$.

*$\mathrm{Li}_2(-1)=\sum_{k=1}^\infty \frac{(-1)^k}{k^2} = -\frac{\pi^2}{12}$.

*$z\frac{d}{dz} \mathrm{Li}_n(z) = \mathrm{Li}_{n-1}(z)$.

*$\mathrm{Li}_n(z) = \int_0^z \frac{\mathrm{Li}_{n-1}(s)}{s}\,ds$.

Then
$$
\begin{split}
-\int_0^1\frac{\log(t^2-t+1)}t\mathrm dt
&= -\int_0^1\frac{\log(1+t^3)-\log(1+t)}t\mathrm dt \\
&= \frac13\int_0^1\frac{\mathrm{Li}_1(-t^3)}{t^3}3t^2\mathrm dt
  - \int_0^1\frac{\mathrm{Li}_1(-t)}{t}\mathrm dt \\
&= \frac13 \int_0^1\frac{\mathrm{Li}_1(-t)}{t}\mathrm dt
  - \int_0^1\frac{\mathrm{Li}_1(-t)}{t}\mathrm dt \\
&= -\frac23 \int_0^1\frac{\mathrm{Li}_1(-t)}{t}\mathrm dt \\
&= -\frac23 \int_0^{-1}\frac{\mathrm{Li}_1(t)}{t}\mathrm dt \\
&= -\frac23 \mathrm{Li}_2(-1)
= -\frac23 \left(-\frac{\pi^2}{12}\right)
= \frac{\pi^2}{18}.
\end{split}
$$

A: Let's multiply by $1$ the integral found in @Federico's answer.
$$\int_0^1\frac{\log(1-x+x^2)}x dx =\int_0^1\frac{\ln(1+x^3)-\ln(1+x)}{x}dx$$
$$\int_0^1\frac{\ln(1+x^3)}{x}dx\overset{x=t^{1/3}}=\frac13\int_0^1 \frac{\ln(1+t)}{t^{1/3}}\,t^{1/3-1}dt\overset{t=x}=\frac13\int_0^1\frac{\ln(1+x)}{x}dx$$
$$\sum_{n=1}^\infty \frac1{n^2{2n\choose n}}
=\frac23 \int_0^1 \frac{\ln(1+x)}{x}dx=\frac23\sum_{n=1}^\infty \int_0^1\frac{(-1)^{n-1}x^{n-1}}{n}dx$$$$=\frac23\sum_{n=1}^\infty \frac{(-1)^{n-1}}{n^2}=\frac23\cdot\frac{\pi^2}{12}=\frac{\pi^2}{18}$$
Above I used: $\ \displaystyle{\ln(1+x)=\sum_{n=1}^\infty \frac{(-1)^{n-1}x^n}{n}}$

A: Another Approach is to employ Feynman's Trick:
Let
$$I(x) = \int_{0}^{1} \frac{\ln\left| x^2\left(t^2 - t\right) + 1\right|}{t^2 - t}\:dt$$
Note $I = I(1)$ and $I(0) = 0$
Thus
\begin{align}
I'(x) &= \int_{0}^{1} \frac{2x\left(t^2 - t\right)}{\left(x^2\left(t^2 - t\right) + 1\right)\left( t^2 - t\right)}\:dt = \frac{2}{x}\int_{0}^{1} \frac{1}{\left(t - \frac{1}{2}\right)^2 + \frac{4 - x^2}{4x^2}}\:dt\\
&= \frac{4}{x}\int_{0}^{\frac{1}{2}} \frac{1}{t^2 + \frac{4 - x^2}{4x^2}}\:dt = \frac{8}{\sqrt{4 - x^2}}\arctan\left(\frac{x}{\sqrt{4 -x^2}} \right)
\end{align}
We now integrate to solve $I(x)$
$$I(x) = \int\frac{8}{\sqrt{4 - x^2}}\arctan\left(\frac{x}{\sqrt{4 -x^2}} \right)  \:dx = 4\left[\arctan\left( \frac{x}{\sqrt{4 - x^2}}\right) \right]^2 + C $$
Where $C$ is a constant of integration. As $I(0) = 0$ we find $C = 0$ and so:
$$I(x) = 4\left[\arctan\left( \frac{x}{\sqrt{4 - x^2}}\right) \right]^2$$
And finally
$$ I = I(1) = 4\left[\arctan\left( \frac{1}{\sqrt{3}}\right) \right]^2 = \frac{\pi^2}{9}$$

A: Firstly observe that, for $x$ real,
\begin{align}(1-x)^2-(1-x)+1&=(1-2x+x^2)-1+x+1\\
&=x^2-x+1
\end{align}
\begin{align}J&=\int_0^1 \frac{\ln(x^2-x+1)}{x(x-1)}\,dx\\
&=-\int_0^1 \frac{\ln(x^2-x+1)}{1-x}\,dx-\int_0^1 \frac{\ln(x^2-x+1)}{x}\,dx
\end{align}
In the first integral perform the change of variable $y=1-x$,
\begin{align}J&=-2\int_0^1 \frac{\ln(x^2-x+1)}{x}\,dx\\
&=-2\int_0^1 \frac{\ln\left(\frac{x^3+1}{x+1}\right)}{x}\,dx\\
&=2\int_0^1 \frac{\ln\left(x+1\right)}{x}\,dx-2\int_0^1 \frac{\ln\left(x^3+1\right)}{x}\,dx\\
&=2\int_0^1 \frac{\ln\left(x+1\right)}{x}\,dx-2\int_0^1 \frac{x^2\ln\left(x^3+1\right)}{x^3}\,dx\\
\end{align}
In the latter integral perform the change of variable $y=x^3$,
\begin{align}J&=2\int_0^1 \frac{\ln\left(x+1\right)}{x}\,dx-\frac{2}{3}\int_0^1
\frac{\ln\left(x+1\right)}{x}\,dx\\
&=\frac{4}{3}\int_0^1 \frac{\ln\left(x+1\right)}{x}\,dx\\
&=\frac{4}{3}\int_0^1 \frac{\ln\left(1-x^2\right)}{x}\,dx-\frac{4}{3}\int_0^1 \frac{\ln\left(1-x\right)}{x}\,dx\\
&=\frac{4}{3}\int_0^1 \frac{x\ln\left(1-x^2\right)}{x^2}\,dx-\frac{4}{3}\int_0^1 \frac{\ln\left(1-x\right)}{x}\,dx
\end{align}
In the first integral perform the change of variable $y=x^2$,
\begin{align}J&=\frac{2}{3}\int_0^1 \frac{\ln\left(1-x\right)}{x}\,dx-\frac{4}{3}\int_0^1 \frac{\ln\left(1-x\right)}{x}\,dx\\
&=-\frac{2}{3}\int_0^1 \frac{\ln\left(1-x\right)}{x}\,dx\\
&=-\frac{2}{3}\Big[\ln x\ln(1-x)\Big]_0^1 -\frac{2}{3}\int_0^1 \frac{\ln x}{1-x}\,dx\\
&=-\frac{2}{3}\int_0^1 \frac{\ln x}{1-x}\,dx\\
&=\frac{2}{3}\zeta(2)\\
&=\frac{2}{3}\times \frac{\pi^2}{6}\\
&=\boxed{\frac{\pi^2}{9}}
\end{align}

A: Let $I(a)=\int_0^1\frac{\ln(4\sin^2a \ (t^2-t)+1)}{t^2-t}dt$. Then
$$I'(a)= \int_0^1 \frac{2\cot a }{t^2-t+\frac14\csc^2a}dt
=8a
$$
and
$$\int_0^1\frac{\ln(t^2-t+1)}{t^2-t}dt=I(\frac\pi6)=\int_0^{\pi/6}8a\ da=\frac{\pi^2}9
$$


text:
Q: The space of continuous function on $[0,1]$ in dense in $L^{\infty}$ respect to the weak$-*$ topology I am reading Rudins' book on Functional Analysis for self study. I stumbled upon an exercise and I would like someone to revise my solution: exercise 7 chapter $3$ second edition.
The exercise asks to prove that the space of continuous functions $C([0,1])$ is dense in $L^{\infty}([0,1])$ respect to the weak-$*$ topology.
I tried to prove that
$$
N_{f_{1}}(g_{1},\epsilon_{1}) \, \cap C([0,1])\neq \emptyset \quad \forall g_{1} \in L^{\infty}([0,1]),\quad \forall f_{1} \in L^{1}([0,1]),\,\quad \forall \epsilon_{1}>0.
$$
where $N_{f_{1}}(g_{1},\epsilon_{1})$ is defined as
$$
N_{f_{1}}(g_{1},\,\epsilon_{1})=\left\{ m \in L^{\infty}:  \left \vert \int_{0}^{1}f_{1}(x)\left(g_{1}(x)-m(x) \right)\,dx \right\vert<\epsilon_1 \right\}.
$$
I thought that a continuous function of $[0,1]$ that might fall into $N_{f_{1}}(g_{1})$ could be one of the form $g_{1}*\rho_{\epsilon}$ where $\{\rho_{\epsilon}\}_{\epsilon >0}$ is a family of mollifiers.
Firstly, I choose $M$ such that
$$
\int_{0}^{1}  \left\vert f_{1}(y)-f_{1}(y)\cdot \mathbb{1}_{\left\{ \vert f_{1} \vert \leq M \right\}}\right\vert \, dy \leq \dfrac{\epsilon_{1}}{2\left( 1+2\,\Vert g_1 \Vert_{\infty} \right)}.
$$
Secondly, I split the main integral in the sum of two integral and use triangular inequality
$$
\begin{gather*}
\left\vert \int_{0}^{1}f_{1}(x)\left(g_{1}(x)-g_{1}*\rho_{r}(x) \right)\,dx \right\vert\\
\leq \left\vert \int_{0}^{1} f_{1}(y)\cdot \mathbb{1}_{\left\{ \left\vert f_{1} \right\vert >  M \right\}}  \, \left( g_{1}(y)-g_{1}*\rho_{r}(y) \right) \,dy \right\vert + \left\vert \int_{0}^{1}f_{1}(y)\cdot \mathbb{1}_{\left\{ \left\vert f_{1} \right\vert \leq  M \right\}}  \, \left( g_{1}(y)-g_{1}*\rho_{r}(y) \right) \,dy  \right\vert \\
\leq 2\Vert g \Vert_{\infty}\cdot \int_{0}^{1}\vert f_{1}(y) \vert \, \cdot \mathbb{1}_{\left\{ \left\vert f_{1}\right\vert>M \right\}}(y)\,dy+ M\cdot \int_{0}^{1}\vert g_{1}(y)-g_{1}(y)*\rho_{r}(y) \vert\,dy \\
\leq \frac{\epsilon_{1}}{2}+ M\cdot \int_{0}^{1}\vert g_{1}(y)-g_{1}(y)*\rho_{r}(y) \vert\,dy.
\end{gather*}
$$
Finally, by the mollifiers properties, I can choose $r$ small enough so that
$$
M\cdot \int_{0}^{1}\vert g_{1}(y)-g_{1}(y)*\rho_{r}(y) \vert\,dy<\frac{\epsilon_{1}}{2},
$$
and for such an $r$ we have $g_{1}*\rho_{r} \in N_{f_{1}}(g_{1},\,\epsilon_{1});$ since the sets of the form $N_{f_{1}}(g_{1},\epsilon_{1})$ are a pre-base for the weak-$*$ topology we conclude that $C([0,1])$ is dense in $L^{\infty}.$

A: Your solution is mostly correct. However, for a set $A$ to be dense in a topological space $X$, it is not sufficient that $A$ intersects a pre-base of the topology $(*)$. You must verify that $A$ intersects a base, and this follows from the argument you present. The proof can be shortened a bit if you use the fact (which you essentially reprove) that continuous   functions are dense in $L^2$.
$(*)$ consider $\mathbb R^2$ with the pre-base    of all products $$\{(a,b) \times \mathbb R  : \, a<b \} \, \cup \, \{  \mathbb R \times (c,d)\,  : \, c<d \} \,. $$  Then the union of the $x$ and $y$ axes intersects every set in the pre-base but is not dense in $\mathbb R^2$.

A: A relative simple proof can be obtained by application of Hahn-Banach's theorem.
Denote by $m$ the Lebesgue measure on $([0,1],\mathscr{B}([0,1])$.  Let $M=\overline{C[0,1])}$ where the closure is taken with respect the weak topology $\sigma(L_\infty(m),L_1(m))$. Suppose $x^*\in L_1(m)$ such that
$\langle x^*,x\rangle=\int^1_0 x(t)x^*(t)\,dt=0$ for all $x\in M$. In particular
$$\int^1_0 \phi(t)x^*(t)\,dt=0,\qquad \phi\in C([0,1])$$
The Riesz representation theorem yields a unique finite Radon signed measure $\mu$ on $[0,1]$ such that $\langle x^*,\phi\rangle=\int \phi\,d\mu=0$ for all $\phi\in \mathcal{C}([0,1])$.  Hence $\mu=x^*(t)\,dt\equiv0$ and so, $x^*=0$ $m$-almost surely . The conclusion follows from the Hahn-Banach theorem: If $y\in L_\infty\setminus M\neq\emptyset$ then there would be $x^*\in L_1$ such that $\langle x^*, x\rangle=0$ for all $x\in M$ and $\langle x^*,y\rangle =1$.


text:
Q: How to apply arithmetic operations on size of two queries I have two queries on the same table :
Query #1 - one with where clause:
SELECT * FROM T1 WHERE condition1 ;

Returns 551 rows
Query #2 - the other one, identical but with more conditions :
SELECT *
FROM T1
WHERE condition1 AND condition2 AND condition3;

This returns 189 rows
Result seeked :
SELECT *
FROM T1
WHERE condition1 AND condition2 AND condition3
   AND (Q2_NumberOfRows / Q1_NumberOfRows > 0,15)

As you can see, in the 4th condition of Q2, I need to divide number of rows of Q1 by those of Q2. Because if this condition is not respected I don't want any row to be returned. I'm using the result as a filter by ID in another query.
So if (Q2_NumberOfRows / Q1_NumberOfRows > 0,15) then I assume that I have no ID to filter, otherwise I will.
How can I do that with only one query?

A: You can do this by using conditional analytic COUNTs and then filtering the rows accordingly, like so:
SELECT <list of t1 cols>
FROM   (SELECT t1.*, -- ideally, you should specify the exact columns you want to retrieve.
               COUNT(*) OVER () cnt_all,
               COUNT(CASE WHEN condition2 AND condition3 THEN 1 END) OVER () cnt_restricted
        FROM   t1
        WHERE  condition1)
WHERE  condition2
AND    condition3
AND    cnt_restricted/cnt_all > 0.15;

The OVER () part of the COUNT function is what makes it analytic - i.e. it won't collapse the rows. OVER () means "take the whole data set as one group, with no ordering and apply the COUNT function to it."
This has the advantage over Zip's answer, in that you are only querying the table once.

A: Try this:
SELECT *
FROM T1
WHERE condition1
  AND condition2
  AND condition3
  AND ((SELECT count(*) FROM T1 WHERE condition1) /
       (SELECT count(*) FROM T1 WHERE condition1 AND condition2 AND condition3) > 0,15)


text:
Q: trim non-numeric and numerics from varchar have the following column in my SQL
identifier
----------
z250
tr015
011s

I want to extract the numbers and non numeric characters from it, so I have an output like this:
identifier | pre  | number | post
-----------+------+--------+-----
z250       | z    | 250    | NULL
tr015      | tr   | 015    | NULL
11s        | NULL | 11     | s

Can someone point in which way I need to start looking. The column has about 700 records, and the naming conventions haven't been followed, so the could be any number of characters preceding and following the numbers.
BTW: the returned characters don't need to be NULL per se, an empty String also works. The leading zero for the numbers also doesn't matter.

A: MySQL has a number of string functions will help.
To get you started, please see the MySQL Regex page.
Here's an example that uses :alnum: for an alphanumeric search. Substituting :digit: could be of use to you, to extract the digits in the middle.
mysql> SELECT 'justalnums' REGEXP '[[:alnum:]]+';       -> 1
mysql> SELECT '!!' REGEXP '[[:alnum:]]+';               -> 0

A: you can create functions like this:https://dba.stackexchange.com/questions/106535/how-to-split-numbers-and-text-in-mysql

With some modifications for pre and post
 DROP function IF EXISTS `pre`;

DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION `pre`(
vStr CHAR(75)) RETURNS char(32) CHARSET latin1
BEGIN
    DECLARE vInd, vLen SMALLINT DEFAULT 1;
    DECLARE vReturn CHAR(32) DEFAULT '';
    DECLARE vCharacter CHAR(1);
    REPEAT
    SET vLen = CHAR_LENGTH(vStr);
    BEGIN
        SET vCharacter = MID(vStr,1,1);
         IF vCharacter REGEXP '[[:digit:]|[:punct:]]' THEN
                 SET vReturn:=NULL;
                 RETURN vReturn;
            ELSE
            SET vCharacter = MID(vStr,vInd,1);
        IF vCharacter REGEXP '[[:alpha:]]' THEN
            SET vReturn=CONCAT(vReturn,vCharacter);

        SET vInd =vInd+1;
        ELSE
          SET vInd:=vLen+1;

         END IF;
            END IF;
    END;
    UNTIL vInd > vLen END REPEAT;
    RETURN vReturn;
END$$

DELIMITER ;

    DROP function IF EXISTS `post`;
    DELIMITER $$
    CREATE DEFINER=`root`@`localhost` FUNCTION `post`(
    vStr CHAR(75)) RETURNS char(32) CHARSET latin1
    BEGIN
        DECLARE vInd,limite, vLen SMALLINT DEFAULT 1;
        DECLARE vReturn CHAR(32) DEFAULT '';
        DECLARE vCharacter CHAR(1);
       SET vInd = 1;
       SET vLen = CHAR_LENGTH(vStr);
       SET limite=vLen;
       REPEAT

              BEGIN
            SET vCharacter = MID(vStr,vLen,1);
            IF vCharacter REGEXP '[[:digit:]|[:punct:]]' THEN
                 SET vReturn:=NULL;
                 RETURN vReturn;
            ELSE

              SET vCharacter = MID(vStr,vLen-vInd+1,1);

            IF vCharacter REGEXP '[[:alpha:]]' THEN
               SET vReturn=CONCAT(vCharacter,vReturn);

                    SET vInd=vInd+1;

            ELSE
                  SET vInd=limite+1;

               END IF;

            END IF;
             END;
             UNTIL vInd > limite END REPEAT;
            RETURN vReturn;

    END$$

    DELIMITER ;

And query:
SELECT identifier,pre(identifier) as pre,num(identifier) as num,post(identifier) as post  FROM table


text:
Q: Optiplex 980 wont wakeup We have a desktop machine that appears to go into sleep mode (sleep is set to never in power options).  The user can remote into the desktop from her laptop successfully.  Yet, when we move the mouse or tap the keyboard...the machine will not respond.  She has to restart the machine from her remote session.
I tried a PS/2 keyboard thinking it may be a USB problem, no success.  Any ideas?
Specs: dell optiplex 980 with windows 7.

A: A lot of computers are really bad at initializing sleep properly, sometimes this is a failure of the implementatino of the standard in the BIOS, sometimes this is a shortcoming of the OS not properly setting the system to sleep. In this scenario I would recommend not relying on sleep, as in most scenarios you can't improve the situation.

A: Update BIOS if available.  Check manufacturer's website.


text:
Q: Highcharts chart not respecting container's width I'm using highcharts inside tabs from Element UI framework and on first load the chart is always exceeding the parent container. How can I fix this ?
It seems the chart renders before its container is affected by the tabs rendering and making it smaller. I'd be interested to know if I can ensure Highcharts always laods after Element UI.
Also I know I can reflow the chart after but there are no events I can hook into that happen after all elements are properly rendered.
<div id="app">
    <template>
        <el-tabs tab-position="left" class="tabs">
            <el-tab-pane label="Tab1">
                <el-button @click="reflowChart">Reflow chart</el-button>
                <highcharts ref="highchart" :options="chartOptions"></highcharts>
            </el-tab-pane>
            <el-tab-pane label="Tab2">
                Test
            </el-tab-pane>
        </el-tabs>
    </template>
</div>

I have reproduced the problem here:
https://codepen.io/AlexisSK/pen/XQJKMW

A: Thanks for your quick responses, I had tried this and I thought it wasn't working because when developing locally, the bug remained sometimes. When deployed, it is fixed. I believe it is something to do with how webpack serves assets in development mode that made the styles trigger in the wrong order or something..
If anyone knows how webpack-dev-server with Hot Module Replacement can cause this and how to avoid it, I'd be interested to know !


text:
Q: Is 'artisks' a word? (I met this word in 'The Invisible Man') In 'The Invisible Man' by H.G.Wells, there is a sentence;"Wait till the summer," said Mrs. Hall sagely, "when the artisks are beginning to come. ..."
Mrs.Hall is the wife of Mr.Hall, who is the owner of the inn where the invisible man(whose name is Griffin) is staying. Mr.Hall does not like Griffin so whenever he can, he expresses that they should evict him. The quoted sentence is the response of the wife when Mr.Hall said so in the late April.
What is 'artisks'? Why is there the definite article 'the'?

A: You may differ, finally, but my take on that use of 'artisks' by that character in that work is that it's a malapropism springing from 'artists' via the lips of the sage Mrs. Hall. If you read on, I expect you'll find that the artists do indeed come to the inn in the summer, and that Mrs. Hall has a vaguely disapproving yet tolerant attitude toward those same artists.
Of course, it could just be a typo in an ineptly proofed edition.

A: Well, point out that Mrs Hall is speaking 'sagely' but at the same time is quite perplexed whether there would be some guests at the inn. So the word 'Artisks' is a result of her paradoxical mental state.


text:
Q: SQLalchemy couldn't find the target column? ticker_table = Table('ticker_data', MetaData(),
    Column('id', Integer, primary_key=True),
    Column('ticker', String(100), nullable=False),
    Column('adj_slope', Float(3), nullable=False),
    Column('sector', String(100), nullable=False),
    Column('sub_sector', String(100), nullable=False)
    )
price_data = Table('price_data', MetaData(),
    Column('id', Integer, primary_key=True),
    Column('ticker', String(100), ForeignKey('ticker_data.ticker'), nullable=False),
    Column('date', Date),
    Column('price', Float(3)),
    )
price_data.create(bind=engine)

I'm getting this error

Foreign key associated with column 'price_data.ticker' could not find table 'ticker_data' with which to generate a foreign key to target column 'ticker'

I'm using MySQL Workbench with Python 3.6 and the most up to date everything else. Not sure what would be causing this error? Any help would be much appreciated. Maybe because I'm using the mysqlclient since the actual plugin isn't updated to python 3.6? I'm relatively new to all things sqlalchemy so any feedback would greatly benefit me.

A: Your problem is that you are using two fresh, unrelated  MetaData instances for each of your table. That way, inside sqlalchemy data structures, the second table won't "see" the other.
The correct thing to do is to use a single metadata object for both tables, and create both at once with a call to .create_all() on the MetaData instance:
...
metadata = MetaData()
ticker_table = Table('ticker_data', metadata,
    Column('id', Integer, primary_key=True),
    Column('ticker', String(100), nullable=False),
    Column('adj_slope', Float(3), nullable=False),
    Column('sector', String(100), nullable=False),
    Column('sub_sector', String(100), nullable=False)
    )
price_data = Table('price_data', metadata,
    Column('id', Integer, primary_key=True),
    Column('ticker', String(100), ForeignKey('ticker_data.ticker'), nullable=False),
    Column('date', Date),
    Column('price', Float(3)),
    )

metadata.create_all(bind=engine)

There is a way to ensure sqlalchemy "sees" the other table, even using distinct MetaData objects: just reference the foreign key column as the Python object, instead of a string. When you create a table, it gets the c attribute which is the column collection - so you could declare your second table like this:
price_data = Table('price_data', MetaData(),
    Column('id', Integer, primary_key=True),
    Column('ticker', String(100), ForeignKey(ticker_table.c.ticker), nullable=False),
    Column('date', Date),
    Column('price', Float(3)),
    )

A: Try replacing the string 'ticker_data.ticker' with the column name ticker_table.c.ticker, as in:
Column('ticker', String(100), ForeignKey(ticker_table.c.ticker), nullable=False)


text:
Q: Split a string that I read from a file I have a file like this
GET /index.html k
GET /docencia.html k
GET /ejemplo.html k

and I want to read it line by line and split it up with this delimiter " " but is giving me this error: segmentation fault(core dumped) and I don't know what to try.
This is my code:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char ordenes[150];
    char *orden[3];
    char *token;
    int tok;

    FILE *fp;
    fp = fopen(argv[1], "r");
    if (fp == NULL) {
        printf("File error");
        exit(1);
    }

    while (feof(fp) == 0) {
        fgets(ordenes, sizeof(ordenes), fp);
        printf("%s \n", ordenes);
        token = strtok(ordenes, " ");
        tok = 0;
        while (token != NULL) {
            orden[tok] = strdup(token);
            tok++;
            token = strtok(NULL, " ");
        }

        printf("\n%s\n", orden[0]);
        printf("\n%s\n", orden[1]);
        printf("\n%s\n", orden[2]);
    }
    fclose(fp);
}

The error shows when I call the first strdup. If I try to print the token just after I call the first strtok, it fails too (the same segmentation fault core dumped) so I guess the problem is with the strtok.

A: You do not include <string.h>, so the compiler applies the default argument promotions on the signature of strtok, in particular it considers that strtok returns an int.
So the compiler will apply an operator of coercion from int to pointer to char at the assignment
token = strtok(ordenes, " ");

and this assignment will be compiled as
token = (int->char*) strtok(ordenes, " ");

A: There are multiple problems in your code:

*

*As alinsoar diagnosed with a sharp eye, you do not include <string.h>. strtok is not defined, the compiler must assume it returns an int, which it does not, and this int is silently converted to a char *.  The code generated invokes undefined behavior and will most likely crash on 64-bit targets.  You should compile with all warnings enabled to let the compiler help avoid this kind of silly mistake. gcc -Wall -W or clang -Weverything...

*You do not check if command line arguments have been passed to your program before calling fp = fopen(argv[1], "r");. If no arguments are passed, argv[1] is a null pointer.

*while (feof(fp) == 0) is incorrect, read Why is "while ( !feof (file) )" always wrong? . You should instead write while (fgets(ordenes, sizeof(ordenes), fp)) {...

*You do not check if tok < 3 before storing token into the orden array.  If the line has more than 3 fields, you will cause a buffer overflow.

*You do not check if 3 tokens were indeed found before printing all 3 entries in orden. This too might invoke undefined behavior, especially if fgets() failed to read a line, which you do not check.
Here is an improved version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char ordenes[150];
    char *orden[3];
    char *token;
    int i, tok;

    if (argc < 2) {
        fprintf(stderr, "Missing command line argument\n");
        exit(1);
    }
    FILE *fp = fopen(argv[1], "r");
    if (fp == NULL) {
        fprintf(stderr, "Cannot open input file %s: %s\n",
                argv[1], strerror(errno));
        exit(1);
    }

    while (fgets(ordenes, sizeof(ordenes), fp)) {
        printf("%s", ordenes);
        token = strtok(ordenes, " ");
        for (tok = 0; tok < 3 && token != NULL; tok++) {
            orden[tok] = strdup(token);
            token = strtok(NULL, " ");
        }
        for (i = 0; i < tok; i++) {
            printf("%s\n", orden[i]);
            free(orden[i]);
        }
        printf("\n");
    }
    fclose(fp);
    return 0;
}

A: You can do the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void play_with_token(char *token, char const *delim)
{
  if (token == NULL)
    return;
  printf(" %s", token);
  play_with_token(strtok(NULL, delim), delim);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
      return 1;
    FILE *fp = fopen(argv[1], "r");
    if (fp == NULL)
      return 1;

    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    while ((read = getline(&line, &len, fp)) != -1) {
      printf("parsing line :");
      char const *delim = " ";
      play_with_token(strtok(line, delim), delim);
      printf("\n");
    }
   free(line);
   fclose(fp);
}

A: For starters you should change the condition in the outer loop statement the following way
while ( fgets(ordenes, sizeof(ordenes), fp) != NULL )

The condition in the inner loop should be written at least like
  while ( tok < 3 && token != NULL) {

The tokens should be outputted in a loop and the allocated memory must be freed. For example
  for ( int i = 0; i < tok; i++ )
  {
      printf("\n%s\n", orden[i]);
      free( orden[i]);
  }

A: try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){
    char ordenes[150];
    char *orden[3];
    char *token;
    int tok;
    FILE *fp;

    fp = fopen (argv[1], "r");
    if(fp==NULL){
        printf("File error");
        exit(1);
    }
    while(fgets(ordenes, sizeof(ordenes), fp)){
        printf("%s\n",ordenes);
        token = strtok(ordenes, " ");
        tok = 0;
        while (token != NULL){
            orden[tok++] = strdup(token);
            token = strtok(NULL," ");
        }
        printf("\n%s\n",orden[0]);
        printf("\n%s\n",orden[1]);
        printf("\n%s\n",orden[2]);
        free(orden[0]);free(orden[1]);free(orden[2]);
    }
    fclose(fp);
}


text:
Q: Importing audio track (wav or aiff) in Python I have an audio track in AIFF format. I would like to open this audio file with Python, and import the amplitudes of the sound and perform some mathematical analysis such as Fourier Transform, etc.

*

*Is this possible in Python?

*Are there libraries or modules, which allow me to acquire an audio file?

Throughout my search, I have found scipy.io.wavfile, which works for WAV audio files.

*

*Are there other libraries to import audio files in Python?

*Is there something similar for AIFF files?

Obviously, I can convert the AIFF into a WAV file, but I would like to import the AIFF file directly, if possible.
As a side question: are there some more specific (by specific, I mean better than Python) programming languages to perform such kind of analysis and acquisition of audio files?

A: Python comes with AIFF support as part of the standard library -- see the aifc module.

This module provides support for reading and writing AIFF and AIFF-C
  files. AIFF is Audio Interchange File Format, a format for storing
  digital audio samples in a file. AIFF-C is a newer version of the
  format that includes the ability to compress the audio data.

Depending on what your end goals are, you may be more productive using a tool like PureData that's designed just for working with audio and has things like reading audio files and performing ffts as primitives.

A: Yes, I also came across this problem using scipy.io.wavfile. I looked up the problem and see that Scikits might be interesting to get around this wave only solution.
https://sites.google.com/site/ldpyproject/scikits-audiolab
As for Pure Data I use this a lot, but of course it does depend on what you wishing to do with your sound file...?


text:
Q: Passing data from table to modal using PHP Whenever I clicked the view button, in a specific person, the modal is giving me a wrong data.

I clicked Paul's data from the table, and the modal is giving me Kharen's data, I want to display the correct data when selected.
PHP code so far for displaying of table only
<?php
$rs = $PDOCon->prepare("SELECT * FROM applicant)
");
if ($rs->execute()) {
}else{
    echo "";
}
$str="

";
$str.="

            Applicant ID
            Full Name
            Applied Job
            Date Applied
            Action

";
    while($row=$rs->fetch(PDO::FETCH_ASSOC)){
        $str.= "
";
            $str.= "" .( $row['people_id']) . "	";
            $people_id= $row['people_id'];
            $str.= "" .($row['FName']) . " " .( $row['MName']) . " " .( $row['LName']) ."	";
            $LName= $row['LName'];
            $FName= $row['FName'];
            $MName= $row['MName'];
            $str.= "" .( $row['job_description']) . "	";
            $str.= "" .( $row['applicant_applied_date']) . "	";
            $str.= " VIEW RESUME	 ";
        $str.= "
";
    }
        echo $str;
    echo "

";

Code above will display the data from the database.
Modal is in the same page as the first one. Here it is:
echo '
';
    echo '
';
        echo '
';
            echo '
';
                echo '<button type="button" class="close" data-dismiss="modal">×</button>';
                echo '
View Applicant Information
';
            echo '
';
            echo '
';
                echo 'Name: '.$LName.', '.$FName.' '.$MName.'
';
                echo 'Email Address:
';
                echo 'Contact Number:
';

                echo 'VIEW DETAILED RESUME';
                echo 'VIEW PDF RESUME';
                echo 'VIEW HH PDF RESUME';
            echo '
';
        echo '

';     ?>

This is my code so far, I'm new to PHP, should I use Javascript, in getting the value, but I'm not familiar in Javascript?
Any idea?

A: You can use the below template.
Added people id in the view links so that the modal will know which particular record to retrieve.
Replace:
$str.= " VIEW RESUME	 ";

With:
$str.= " VIEW RESUME	 ";

On modal open, the below code retrieves the record from database using the people id that is in the view link. This uses ajax and a separate php file to retrieve the record of the relevant person.
Use this modal handler:

The below code will respond with the requested record in json format to display in the modal.
Create a file named get_person.php
if(isset($_POST['submit'])){
    $people_id = isset($_POST['people_id'])?$_POST['people_id']:0;

    if($people_id > 0){
        $dbh = new PDO('mysql:host=localhost;dbname=peeps', 'dbuser','dbpasss');
        $stmt = $dbh->prepare("SELECT * FROM tblname WHERE people_id = :people_id");
        $stmt->bindValue(":people_id", $people_id);

        if($stmt->execute()){
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            exit(json_encode(array('status'=>'success', 'data'=>$row)));
        }
    }
}

exit(json_encode(array('status'=>'fail', 'msg'=>'Failed to fetch data!')));

A: Your issue is due probably because you reset people_id every row with the last value.
$people_id= $row['people_id'];
You must store all data in an array and after report the data on the page.
So you can have the correct matching between the different elements in the page

A: You need to load the applicant data dynamically
If you don't know (or you don't want) make an ajax req.:
Change this line:
$str.= " VIEW RESUME	 ";

whit this:
$str.= " VIEW RESUME	 ";

Change your modal to this (you can remove php of the modal):

                <button type="button" class="close" data-dismiss="modal">×</button>

View Applicant Information

                Name: ,

                Email Address:

                Contact Number:

                VIEW DETAILED RESUME
                VIEW PDF RESUME
                VIEW HH PDF RESUME

And add this script to the end of your page:
$('#myModal').on('show.bs.modal', function (event) {
    var applicant = $(event.relatedTarget);
    var LName = applicant.data('LName');
    var FName = applicant.data('FName');
    var MName = applicant.data('MName');
    var people_id = applicant.data('people_id');

    modal.find('.modal-LName').text(LName);
    modal.find('.modal-FName').text(FName);
    modal.find('.modal-MName').text(MName);
    modal.find('.resume-link').attr('src', 'encode_view.php?id='+people_id);
    modal.find('.resumepdf-link').attr('src', 'print_pdf_2.php?id='+people_id);
    modal.find('.resumehh-link').attr('src', 'print_pdf.php?id='+people_id);
});


text:
Q: how to check if the cell value is nothing or not in vb.net?
i am using grid view in vb.net.
here is code...
If Not DataGridView1.SelectedRows.Count = 0 Then
                i = DataGridView1.SelectedRows(0).Index
                If DataGridView1.Rows(i).Cells(0).Value <> Nothing Then
                    namebox.Text = Trim(DataGridView1.Rows(i).Cells(0).Value)
                    salarybox.Text = DataGridView1.Rows(i).Cells(1).Value
                End If
End If

now if the cell has nothing in it then it will show the exception....
like this...
Operator '<>' is not defined for type 'DBNull' and 'Nothing'.

this is code will be called when selected cell will be changed.
i trying to get the values of the selected cell and put that in in one text box.

A: You don't want to use the <> operator, you should us value IsNot Nothing to check if it IsNot Nothing or inversely Is Nothing to check if a value Is Nothing.
Also the reason is that there is no comparer for the DBNull and Nothing Types so if this is the case you will need to check to see for both. Something like
If value IsNot Nothing AndAlso value <> DBNull.Value Then

   ''#Do something

End If

A: Change
If DataGridView1.Rows(i).Cells(0).Value <> Nothing Then

to
If Not DataGridView1.Rows(i).Cells(0).Value Is DBNull.Value Then


text:
Q: Getting error while using pip installation I am trying to install Chatterbot using pip but getting following error.

Command "python setup.py egg_info" failed with error code 1 in
  /private/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/pip-build-8wG6yW/ruamel.yaml/

Full log is as below
➜  Documents pip install ./ChatterBot
Processing ./ChatterBot
Collecting chatterbot-corpus<1.1,>=1.0 (from ChatterBot==0.7.3)
  Using cached chatterbot_corpus-1.0.0-py2.py3-none-any.whl
Collecting jsondatabase<1.0.0,>=0.1.7 (from ChatterBot==0.7.3)
  Using cached jsondatabase-0.1.7-py2.py3-none-any.whl
Collecting nltk<4.0,>=3.2 (from ChatterBot==0.7.3)
  Using cached nltk-3.2.4.tar.gz
Collecting pymongo<4.0,>=3.3 (from ChatterBot==0.7.3)
  Using cached pymongo-3.4.0-cp27-cp27m-macosx_10_12_intel.whl
Collecting python-dateutil<2.7,>=2.6 (from ChatterBot==0.7.3)
  Using cached python_dateutil-2.6.1-py2.py3-none-any.whl
Collecting python-twitter<4.0,>=3.0 (from ChatterBot==0.7.3)
  Using cached python_twitter-3.3-py2-none-any.whl
Collecting sqlalchemy<1.2,>=1.1 (from ChatterBot==0.7.3)
  Using cached SQLAlchemy-1.1.11.tar.gz
Collecting ruamel.yaml<=0.15 (from chatterbot-corpus<1.1,>=1.0->ChatterBot==0.7.3)
  Using cached ruamel.yaml-0.15.0.tar.gz
    Complete output from command python setup.py egg_info:
    /var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:6:8: warning: explicitly assigning value of variable of type 'yaml_parser_t' (aka 'struct yaml_parser_s') to itself [-Wself-assign]
    parser = parser;  /* prevent warning */
    ~~~~~~ ^ ~~~~~~
    /var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:6:10: warning: variable 'parser' is uninitialized when used here [-Wuninitialized]
    parser = parser;  /* prevent warning */
             ^~~~~~
    /var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:5:1: note: variable 'parser' is declared here
    yaml_parser_t parser;
    ^
    2 warnings generated.
    /var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:6:8: warning: explicitly assigning value of variable of type 'yaml_parser_t' (aka 'struct yaml_parser_s') to itself [-Wself-assign]
    parser = parser;  /* prevent warning */
    ~~~~~~ ^ ~~~~~~
    /var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:6:10: warning: variable 'parser' is uninitialized when used here [-Wuninitialized]
    parser = parser;  /* prevent warning */
             ^~~~~~
    /var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:5:1: note: variable 'parser' is declared here
    yaml_parser_t parser;
    ^
    2 warnings generated.
    sys.argv ['-c', 'egg_info', '--egg-base', 'pip-egg-info']
    test compiling test_ruamel_yaml
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/pip-build-8wG6yW/ruamel.yaml/setup.py", line 858, in <module>
        main()
      File "/private/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/pip-build-8wG6yW/ruamel.yaml/setup.py", line 847, in main
        setup(**kw)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 111, in setup
        _setup_distribution = dist = klass(attrs)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/dist.py", line 272, in __init__
        _Distribution.__init__(self,attrs)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 287, in __init__
        self.finalize_options()
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/dist.py", line 326, in finalize_options
        ep.require(installer=self.fetch_build_egg)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2385, in require
        reqs = self.dist.requires(self.extras)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2617, in requires
        dm = self._dep_map
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2606, in _dep_map
        if invalid_marker(marker):
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 1424, in is_invalid_marker
        cls.evaluate_marker(text)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 1549, in _markerlib_evaluate
        env = cls._translate_metadata2(_markerlib.default_environment())
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 1537, in _translate_metadata2
        for key, value in env
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 1536, in <genexpr>
        (key.replace('.', '_'), value)
    ValueError: too many values to unpack

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/pip-build-8wG6yW/ruamel.yaml/

My pip installation is already at latest version. I even tried re-installing it as suggested on other websites but couldn't make it working yet. Any help is appreciated.

A: Command worked after installing setuptools.
pip install -U pip setuptools --user python

I tried this earlier also but without --user python . It was failing then but worked after appending user.


text:
Q: Expectation of Ito Integrals. Consider the stochastic differential equation:$$dx(t)=f(x(t))dt+g(x(t))dB(t)$$
where $B(t)$ is the standard brownian motion.
Is the following always true:
$$\mathbb{E}\int_0^tH(x(t))dB(t)=0$$
If it is not true in general, what are the conditions on the function $H(x)$ that makes the equality holds?

A: If the stochastic integral wrt to the B.M. is well defined, then your claim is always true. For the integral to be well defined we need the integrand process H to be $\{\mathscr{F}_t\}$-adapted and also to satisfy
$$\int_0^t |H_u|^2 du < \infty.$$


text:
Q: Please teach me how to make the template parameters of a following function I am a beginner of template. I want to make a function with template template parameters. For me, it is complicated template template parameter. And I cannot make it. Someone, please let me know how I can make it. Thank you very much.
class Vertex {
};

main() {
    std::vector<std::shared_ptr<Vertex>*> vertexes_a, vertexes_b;
    CompareVector(&vertexes_a, &vertexes_b);
}

/* I made the following template parameters. But compiler cannot compile it.
 * They said template parameters invalid... It must have my stupid understanding.
 * So please ignore my template parameters and
 * please teach me how to make the template parameters. */
template <typename Elm, template<template<Elm> class SharedPtr, typename Allocator=std::allocator<template<Elm> class SharedPtr> > class STL>
bool CompareVector(STL<std::shared_ptr<Elm>>* org, STL<std::shared_ptr<Elm>>* cmp) {
}

Thank you very much.

A: Maybe you want this?
template <template <typename ...> class C, typename ...Args>
bool CompareVector(C<Args...> const * lhs, C<Args...> const * rhs)
{
    // ...
}

If you only want it to work for vectors:
template <typename T, typename A>
bool CompareVector(std::vector<T, A> const * lhs, std::vector<T, A> const * rhs);

If you want it to work for arbitrary template classes whose first template argument is a template class with one argument (but why):
template <template <typename ...> class C,
          template <typename> class SP,
          typename T,
          typename Args...>
bool CompareBizzare(C<SP<T>, Args...> const * lhs, /* ... */);

Note that none of your desired function arguments are specializations of a template that has template template parameters. The standard library does not contain any templates that take template template parameters (for now).


text:
Q: Not appearing all level after SKTransition I am trying to do a transition between game menu and the first level.
But instead of all Level1 (it is built by using an Level1.sks file(here I have designed a level) and Level1.swift(here I have created my "hero" etc.)) on the screen appears just hero, but no locations that was designed in Level1.sks.
How I can resolve this problem?
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        if (playbutton .containsPoint(location)){

            runAction(SKAction.playSoundFileNamed("play.wav", waitForCompletion: false))

            let transition = SKTransition.revealWithDirection(SKTransitionDirection.Down, duration: 1)
            let scene = Level1(size: CGSizeMake(1024, 768))
            scene.scaleMode = SKSceneScaleMode.AspectFill
            self.scene?.view?.presentScene(scene, transition: transition)
            transition.pausesOutgoingScene = true

        }

A: You need to unarchive the sks file into an SKScene object so that the elements from the file can be loaded into the scene.
XCode usually generates a method called unarchiveFromFile in the SKScene's .swift file.
The following code should work:
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        if (playbutton .containsPoint(location)){

            runAction(SKAction.playSoundFileNamed("play.wav", waitForCompletion: false))

            if let scene = Level1.unarchiveFromFile("GameScene") as? GameScene {

                let transition = SKTransition.revealWithDirection(SKTransitionDirection.Down, duration: 1)
                scene.scaleMode = SKSceneScaleMode.AspectFill
                self.scene?.view?.presentScene(scene, transition: transition)
                transition.pausesOutgoingScene = true
            }
        }
    }
}


text:
Q: Can I send c2dm push messages to an android device in which the primary account is the role sender account I developed an app which  uses c2dm. It's implemented at
http://www.controlyourandroid.appspot.com
It's working perfectly when I'm trying it in an emulator or in my friends device. But when I use my own android phone (HTC WildFire, and 2.2.1), I'm not receiving c2dm messages.
I don't know why?
The registration is successful and I'm getting a registration id in my device.
Is it because my primary account in my phone and the role sender account that I'm using for the app is the same.
Thanks

A: As I recall the answer is no. This may change as C2DM is still a beta project (as far as I know). We are using C2DM in one of our Android applications, and we ran into problems using the role sender account on a device. There may be a workaround, but we just created a dedicated gmail email address to use with the C2DM service.


text:
Q: Storing Database Locally in File/Folder I'm in the middle of doing a personal project and would like to create a system of three components.

*

*A simple form application that would allow the user to input data into a database.

*A database of multiple tables.

*An excel spreadsheet that queries the database.
At this point in the project, there is a desire for the database to be stored on the PC of the person working on the project and for all three components of the project to have the ability to be zipped up in a folder and emailed around. I know how to code well enough to query databases from applications and excel, but how can I go about creating a database that can be stored in a specific folder so it can be emailed around?
Thanks!

A: Look into sql compact edition
http://en.wikipedia.org/wiki/SQL_Server_Compact
http://xldennis.wordpress.com/2010/08/30/using-sql-server-compact-edition-database-with-excel/
MS Access might also be an option here.


text:
Q: Is it appropriate to use id-s in MongoDb subdocuments? I'm currently familiarizing myself with NoSQL by building a simple web application using MongoDb with the official C# driver. If i have understood the NoSQL concept correctly, then only the aggregate root document should have an id and the child collections are without identity.
For example in C# code i would have the following 2 Poco-s:
public class User
{
    public BsonObjectId Id { get; set; }

    [BsonElement("pets")]
    public List<Pet> Pets { get; set; }
}

public class Pet
{
    public string Name { get; set; }
}

How would i solve a case, where i want to have separate CRUD views for pets? With a relational database i would do this by having the pet id in the query string, with NoSQL i'm not sure.
This question arose from when i tried to add an Id field to the "Pet" subdocument. Instead of an id for pet, an object named "_csharpnull" was added to the database instead.
For example if i do this:
public class User
{
    public BsonObjectId Id { get; set; }

    [BsonElement("pets")]
    public List<Pet> Pets { get; set; }
}

public class Pet
{
    public BsonObjectId Id { get; set; }
    public string Name { get; set; }
}

Then this document is inserted into the database:
{
    "_id" : ObjectId("5643a1f9766bcf0fc0b26f14"),
    "pets" : [
        {
            "_id" : {
                "_csharpnull" : true
            },
            "Name" : "T-Rex"
        }
    ]
}

When my expected behavior would be something like:
{
    "_id" : ObjectId("5643a1f9766bcf0fc0b26f14"),
    "pets" : [
        {
            "_id" : ObjectId("56439adc766bcf49a0639992"),
            "Name" : "T-Rex"
        }
    ]
}

A: While I am not aware of a particular standard that says yes or no, in my experience this can and should in many cases be done.
The moment you want to be able to handle a Pet on it's own in various operations you need an ID. The simplest way in MongoDB is to just give it an ObjectID.
But I also have run into cases where this was not needed, such as when you have a sub document which always appears together with it's main document.
While I am not familiar with C# particularly, what you are trying to do definitely works in Java. Just make sure you actually initialize the ObjectID manually. While MongoDB creates object IDs for you on the top level documents of a collection it will not do the same for child documents.

A:
If i have understood the NoSQL concept correctly, then only the
  aggregate root document should have an id and the child collections
  are without identity.

I am not sure relational or even NoSQL document-oriented databases goes perfectly well with Domain Driven Design in all cases.
Will your document have an object id /primary key or not should be considered an implementation detail (though if you are not careful, it WILL affect your modelling process).
What is more important is the way you treat that particular document. Do you access it from outside of aggregate root boundaries by id? If you delete it and recreate the complete same object, but with different id will it affect your application logic somehow? Etc.
I think it would be better to have value object without ids so that there would be no temptation for you to address them  using ids. But if on some reason you should have, consider it an implementation detail and concentrate on following the domain logic first.


text:
Q: jQuery thumbnail grid in AngularJS I'm attempting to use a thumbnail grid in my AngularJS application. I've set up a directive for the HTML template part, but am having trouble initializing the jQuery part that expands a tile on click.
I know this is a typical issue when attempting to use jQuery in Angular apps. The jQuery script is very simple, I just don't know how to make it work in Angular. The script:
    <script>
        $(function() {
            Grid.init();
        });
    </script>

Thanks for any advice/help!
Edit:
Page is here: tinyurl.com/jgbrpd6. As you can see, if you click on one of the elements, nothing happens because the jQuery script is located in the HTML of the templateUrl file.
templateUrl file is here: tinyurl.com/zr9ylqf. As you can see, if you click on one of the elements, it behaves as expected, becuase it is now outside of the AngularJS app.