text:
Q: pygame quit button not functioning properly my quit button is working in my pygame but only partly. it works once i have just run the game, but after i have been killed in game and the game_loop is reset, the quit button just resets the game loop when i press it and doesn't close the window. it's like it has changed it's function to the same as the function of when the player get's killed if that makes sense.
i am just going to show you my whole games code to make it easier. (btw my game is being changed currently so some things might be in the wrong place and stuff just don't worry about it).
import pygame
import time
import random
pygame.init()
pygame.font.init()
dis_width = 500
dis_height = 500
game_exit = False
hit = False
FPS = 150
record = 0
game_display = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('RACRZ')

clock = pygame.time.Clock()
#COLOURS
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0 ,0)
green = (0, 255, 0)
blue = (0, 0, 255)
sky_blue = (0, 136, 239)
#VEHICLE
bg = pygame.image.load('c:\\users\\riley\\pictures\\Saved Pictures\\spaceImg_bg.png')
carImg = pygame.image.load('c:\\users\\riley\\pictures\\Saved Pictures\\space invader1.png')
car_width = 32
car_height = 33

vel = 3
#projectile
enemyImg = pygame.image.load('c:\\users\\riley\\pictures\\saved pictures\\projectile1.png')
explosionImg = pygame.image.load('c:\\users\\riley\\pictures\\saved pictures\\explosion 1.png')

def car(x, y):
    game_display.blit(carImg, (x, y))

def enemy(enemyx, enemyy):
    game_display.blit(enemyImg, (enemyx, enemyy))
def enemy2(enemyx, enemyy):
    game_display.blit(enemyImg, (enemyx, enemyy))
def enemy3(enemyx, enemyy):
    game_display.blit(enemyImg, (enemyx, enemyy))
def enemy4(enemyx, enemyy):
    game_display.blit(enemyImg, (enemyx, enemyy))
def enemy5(enemyx, enemyy):
    game_display.blit(enemyImg, (enemyx, enemyy))
def enemy6(enemyx, enemyy):
    game_display.blit(enemyImg, (enemyx, enemyy))

def explode(x, y):
    game_display.blit(explosionImg, (x, y))
#TEXT
def textobjects(text, font):
    textsurface = font.render(text, True, green)
    return textsurface, textsurface.get_rect()

#RESTART MESSAGE
def message_display(text, colour, locationX, locationY):
    largeText = pygame.font.Font('freesansbold.ttf', 50)
    text = largeText.render('HIT', True, (colour))
    game_display.blit(text, (locationX, locationY))
    pygame.display.update()
    time.sleep(2)

    game_loop()

def collision(ex, ey, ew, eh, x, y, w, h):
    if x > ex and x < ex + ew or x + w > ex and x + w < ex + ew:
        if y > ey and y < ey + eh or y + h > ey and y + h < ey + eh:
            print ('HIT')
            hit = True
            game_loop()

def score(rounds):
    font = pygame.font.SysFont(None, 35)
    text = font.render(f'ROUND {rounds}', True, green)
    game_display.blit(text, (0,0))

#GAME LOOP
def game_loop():
#beggining car location
    x = dis_width * 0.45
    y = dis_height * 0.8
#movement variables
    x_change = 0
    y_change = 0

    loop_count = 0

    enemy_startx = random.uniform(0, dis_width)
    enemy_starty = -1000

    enemy2_startx = -1000
    enemy2_starty = random.uniform(0, dis_height)

    enemy3_startx = random.uniform(0, dis_width)
    enemy3_starty = -24

    enemy4_startx = random.uniform(0, dis_width)
    enemy4_starty = 500
    #goes from top side diagonaly to bottom left
    enemy5_startx = random.uniform(0, dis_width)
    enemy5_starty = -24
    #goes from bottom side diagonaly to top right
    enemy6_startx = random.uniform(0, dis_width)
    enemy6_starty = 500

    enemy_speed = 3
    enemy_width = 24
    enemy_height = 24

#game has not been quit
    game_exit = False
#while the game is running this will happen
    while not game_exit:
        #quit button
        for event in pygame.event.get():
            #assingning keys to movement
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change -= vel
                elif event.key == pygame.K_RIGHT:
                    x_change += vel
                elif event.key == pygame.K_DOWN:
                    y_change += vel
                elif event.key == pygame.K_UP:
                    y_change -= vel
                elif event.type == pygame.K_ESCAPE:
                    print ('escape')
                    game_exit = True
            if event.type == pygame.QUIT:
                 game_exit = True

            #stops vehicle from moving after key press
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    y_change = 0
        #moves vehicle
        y += y_change
        x += x_change
        #display colour
        game_display.blit(bg, (0,0))
        #spawns objects
        if loop_count >= 10:
            enemy3_startx += enemy_speed
            enemy3_starty += enemy_speed
            enemy3(enemy3_startx, enemy3_starty)

        if loop_count >= 15:
            enemy4_startx -= enemy_speed
            enemy4_starty -= enemy_speed
            enemy4(enemy4_startx, enemy4_starty)

        if loop_count >= 20:
            enemy5_startx -= enemy_speed
            enemy5_starty += enemy_speed
            enemy5(enemy5_startx, enemy5_starty)

        if loop_count >= 25:
            enemy6_startx += enemy_speed
            enemy6_starty -= enemy_speed
            enemy6(enemy6_startx, enemy6_starty)

        car(x,y)
        enemy(enemy_startx, enemy_starty)
        enemy2(enemy2_startx, enemy2_starty)

        score(loop_count)

        enemy2_startx += enemy_speed
        enemy_starty += enemy_speed
        if hit == True:
            game_loop = 0
#MAKES DISPLAY BOUNDARIES
#car boundaries
        if x > dis_width - car_width:
            x = 0
        elif x < 0:
            x = dis_width - car_width
        elif y > dis_height - car_height:
            y = 0
        elif y < 0:
            y = dis_height - car_height
#boundaries for enemy1
        if enemy_starty > dis_height:
            enemy_starty = 0 - enemy_height
            enemy_startx = random.uniform(0, dis_width - enemy_width)
            #loop_count will count the number of times enemy1 passes through the screen
            loop_count = loop_count + 1
            print(loop_count)
        # ex, ey, ew, eh, x, y, w, h
        collision(enemy_startx, enemy_starty, enemy_width, enemy_height, x, y, car_width, car_height)
        collision(enemy2_startx, enemy2_starty, enemy_width, enemy_height, x, y, car_width, car_height)
        collision(enemy3_startx, enemy3_starty, enemy_width, enemy_height, x, y, car_width, car_height)
        collision(enemy4_startx, enemy4_starty, enemy_width, enemy_height, x, y, car_width, car_height)
        collision(enemy5_startx, enemy5_starty, enemy_width, enemy_height, x, y, car_width, car_height)
        collision(enemy6_startx, enemy6_starty, enemy_width, enemy_height, x, y, car_width, car_height)
#boundaries for enemy2
        if enemy2_startx > dis_width:
            enemy2_startx = 0 - enemy_width
            enemy2_starty = random.uniform(0, dis_height - enemy_height)
#enemy3 boundaries
        if enemy3_startx > dis_width:
            enemy3_startx = random.uniform(0, dis_width)
            enemy3_starty = -24
#enemy4 boundaries
        if enemy4_startx < 0 - enemy_width:
            enemy4_startx = random.uniform(0, dis_width)
            enemy4_starty = 500
#enemy5 boundaries
        if enemy5_startx < 0 - enemy_width:
            enemy5_startx = random.uniform(0, dis_width)
            enemy5_starty = -24
#enemy6 boundaries
        if enemy6_startx > dis_width:
            enemy6_startx = random.uniform(0, dis_width)
            enemy6_starty = 500
        #record checker/ set
        global record
        roundnum = loop_count
        if roundnum > record:
            record = roundnum

        #updates screen after movements
        pygame.display.update()
        #FPS
        clock.tick(FPS)
#loops through code
if game_exit == True:
    pygame.quit()
game_loop()
print (f'your record is {record}')

it would mean allot you could find the error in my code.
if you find any other issues please let me know thanks.

A: The bit of code here is quite wrong. Try this in a while True: loop:
    for event in pygame.event.get():
            if event.type == QUIT:
             pygame.quit()
             sys.exit()
            pygame.display.update()

[The pygame.display.update bit is in a different place so delete it where it was and copy and past this in isntead.]


text:
Q: segfault in basic C mkstemp code It seems that I'm completely misusing mkstemp. However I use it, I always get a segfault. I compiled the most basic program below with gcc -ggdb -Wall -Werror main.c and ran it with ./a.out
#include <stdlib.h>

int main(int argc, char **argv) {
    mkstemp("XXXXXX");
    return 0;
}

This always returns the returncode 139 and it prints [1]   23532 segmentation fault  ./a.out on the terminal. (23532 always changes because it's the pid).
I tried:

*

*switching the flags of gcc (none at all, a lot of combinations of the previous flags, -Wextra and -O0)

*Changing the code by saving the resulting filedescriptor in a int, sleeping 5 seconds and closing the filedescriptor again. But I don't even reach the start of the sleep...

And now I'm out of ideas...

A: From the man page:

The last six characters of template must be "XXXXXX" and these are
         replaced with a string that makes the filename unique.  Since it will
         be modified, template must not be a string constant, but should be
         declared as a character array.

So you need to declare a character array:
char filename[] = "fileXXXXXX";
mkstemp(filename);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change meta title in prestashop module? I'm using prestashop 1.6 and one module is not editable in SEO&URL, to change is meta.
Actually, i have the default pretashop meta title.
How can i add a custom header.tpl for this module ?
Thank you for your help
Tony

A: Assuming you are talking about a module with a controller,
you can add in the base file /modules/mymodule/mymodule.php,
inside the method __construct(),
a object like this $this->controllers = array('controller_file_name');, where the controller_file_name is the file which generate the page in the front office.
Once made this, you will need to re-install the module and this added object will generate a new page in the SEO&URL where you could change all the metas (title, description and keywords).
You can see some examples of this modules in the bankwire, cheque and blocknewsletter.


text:
Q: how to change xml string value on fly I have an xml response string and I want to change a value inside and log it.
<xml>
<ns2:abcd>
<password>sample</password>
</ns2:abcd>

I want to change the password value into encrypted version.
I am have tried using XmlDocument.SelectSingleNode but was thinking is there any better way than this?

A: Btw you need ns2 namespace to be declared, otherwise your xml will not be valid. After adding namespace definition, you can parse and modify your xml with Linq to Xml:
XDocument xdoc = XDocument.Parse(xml);
var passwordElement = xdoc.XPathSelectElement("//password");
passwordElement.Value = Encrypt((string)passwordElement);
xdoc.Save(path_to_xml);

A: No - there is no better way than using proper XML classes.
XmlDocument or XDocument would be perfectly fine for this task. If you XML is very large you may want to look into streaming with XmlReader (unlikely necessary in your case).

A: You might also consider looking into xsd.exe. With xsd.exe, you can deserialize your xml into a type-safe object model. From there, it's easy to manipulate the data.


text:
Q: Idiomatic way to check std::chrono duration is less than 0 I know I can do this
if (timeLeft.count() < 0)

But I wonder what is the best way since I could also do:
if (timeLeft<std::chrono::seconds(0)) // or milliseconds or nanonseconds...

note: I assume both checks are the same, but I am not a chrono expert.
edit:full example:
#include<chrono>
int main(){
    const std::chrono::nanoseconds timeLeft(-5);
    if(timeLeft<std::chrono::seconds(0)){
        return 47;
    }
}

edit2: potential problem with std::chrono::seconds(0) is that novice programmer might assume it involves rounding although it does not.

A: One of the ways to express this is by using std::chrono::duration literals (https://en.cppreference.com/w/cpp/chrono/duration). It's short and clean:
#include<chrono>

int main(){
    using namespace std::chrono_literals;

    const auto timeLeft = -5ns;
    if(timeLeft<0s){
        return 47;
    }
}


text:
Q: Nothing being added to generic List Add method Code for Property in JobQuote class:
 public class JobQuote
{
// Properties
private List<string> _jobfilenames;
public List<string> JobFileNames
{
    get
    {
        if (_jobfilenames != null)
            return _jobfilenames;
        else
        {
            _jobfilenames = new List<string>();
            return _jobfilenames;
        }
    }

    set { _jobfilenames = value; }
}

Code for Property in User Control
public JobQuote quote
{
    get
    {
        if (ViewState["Quote"] != null)
            return (JobQuote)ViewState["Quote"];
        else
        {
            JobQuote newQuote = new JobQuote();
            return newQuote;
        }
    }
    set { ViewState["Quote"] = value; }
}

Code in try block of UserControl where the string is not being added to the generic list of strings:
try
        {
            string filename = System.IO.Path.GetFileName(FileUploader.FileName);
            quote.JobFileNames.Add(filename);
        }

What am I doing wrong?

A: You are reading from the viewstate but you never assign.
public JobQuote quote
{
    get
    {
        if (ViewState["Quote"] != null)
            return (JobQuote)ViewState["Quote"];
        else
        {
            // you only construct a new instance but you dont assign it to the viewstate
            JobQuote newQuote = new JobQuote();
            // add the following line to fix the problem
            // ViewState["Quote"] = newQuote;
            return newQuote;
        }
    }

This means that next time you refer to the quote property, a new JobQuote instance will be created rather than your old JobQuote instance being returned
A clean way for implementing this would be:
public JobQuote Quote
{
    get
    {
        JobQuote result = ViewState["Quote"] as JobQuote;
        if (result == null)
        {
            result = new JobQuote();
            ViewState["Quote"] = result;
        }

        return result;
    }
}

A: You are returning a new JobQuote instance every time. Try this:
public JobQuote quote
{
    get
    {
        if (ViewState["Quote"] != null)
            return (JobQuote)ViewState["Quote"];
        else
        {
            JobQuote newQuote = new JobQuote();
            ViewState["Quote"] = newQuote;
            return newQuote;
        }
    }
    set { ViewState["Quote"] = value; }
}

or:
public JobQuote quote
{
    get
    {
        if (ViewState["Quote"] == null)
            ViewState["Quote"] = new JobQuote();

        return (JobQuote)ViewState["Quote"];
    }
    set { ViewState["Quote"] = value; }
}


text:
Q: Openshift Origin Offline/Disconnected Installation I want to install openshift origin containerized installation(advanced installation) on machine without internet access.
I referred to this URL -> https://docs.openshift.com/enterprise/3.1/install_config/install/disconnected_install.html
But it still going to docker.io and registry.*.redhat.com.
Please suggest a possible approach to achieve the goal.

A: There is a way to accomplish this install.The updated documentation does list the steps.
Let me know if you are still looking for the steps.


text:
Q: How copyscape uses google API How copyscape uses google API?
The ajax api works only on browsers with javascript enabled, So this api is not used. The SOAP api is not used, because it is not allowed to be used for commercial use and no more than 100 queries are allowed per day.

A: Copyscape not uses Google api instead it uses Google search it does a simple curl request to http://www.google.com/search?q=Search Keywords here . Then uses regexp patterns to find title, descriptions and links and shows to user. But this strictly violates Google terms of service which can also get them ban, so they uses proxies(or any other ip hiding method) to hide their ip for each search

A: From their FAQ they have explained how they do it.

Where does Copyscape get its results?
Copyscape uses Google and Yahoo! as search providers, under agreed
  terms. These search providers send standard search results to
  Copyscape, without any post-processing. Copyscape uses complex
  proprietary algorithms to modify these search results in order to
  provide a ?plagiarism checking service. Any charges are for
  Copyscape's value-added services, not for the provision of search
  results by the search providers.
http://www.copyscape.com/faqs.php#providers

Analysis
CopyScape made us 100% sure that Google and Yahoo have special agreements. I am 80% sure that CopyScape are using a similar search solution (probably undisclosed but similar) to Google Enterprise Search provided by the search engines.
CopyScape does not do scraped results, but is fetching API based formats like json and xml. Which is good for the providers (Google and Yahoo) for bandwidth and response time improvements. I came up with this part due to my previous attempts to scrape google search results via python by phrase searches ("phrase matching"). Your scraping bot cannot and no known way to bypass 503 that google will respond after couple of hundred results (100 search intervals or 50 search intervals).
They obviously did not do some browser automation then fetching data between web drivers and programming languages like python. I have tried doing it and it gave similar results except that the automated searcher will need some manual intervention for the captcha which will then let you continue with the scraping. I also tried using some latest bypass which was patch in just minutes/seconds. Surely they did not do any automated scraping from search engines and if ever they are doing it. It will not work long term.
How they are using their special privilege?
Since they have paid off / have special terms they can now automate from the special APIs. They are either using Google Search Enterprise & Yahoo Search Marketing Enterprise or they have something more special solution.
Not Using List

*

*Regular / Free APIs (Not sure if google and yahoo made it free for them)

*Scrapers (Scrapy, Beautiful Soup, Selenium and Etc)

Using List

*

*Enterprise Level API

*Server Bash Scripts / Python Scripts / Ruby Scripts / PHP Scripts for scalabilities and such.

Hoping
I hope someone from CopyScape can leak information so that people won't be guessing and CopyScape should have more competition since there are only some plagarism checkers out there which are highly reliable and regarded (probably 1-10 only).


text:
Q: Como hacer un boton para eliminar en PHP que no redirija a otro PHP? estoy haciendo un proyecto para aprender mas y me trabe en una parte, lo que susede es que quiero un boton eliminar que al tocarlo no me recarge la pagina sino que solo elimine un turno.
Para mostrarles tengo codigo de mi proyecto se los paso aqui:
 <?php
if(!isset($_GET['id'])){
    header('Location: home.php');
}else{
    include('model/conexion.php');
    $id = $_GET['id'];

    $consulta = $con -> prepare("DELETE FROM turnos WHERE ID_TURNO=?;");
    $result = $consulta->execute([$id]);

    if($result == true){
        header('Location: home.php');
    }else{
        echo "Error de Eliminacion";
    }

  }

?>

Ese seria la parte del eliminar, y tambien paso lo que elimina:

                           <?php echo $dato->TRATAMIENTO ?>

                          &nbsp<?php echo $dato->ZONA ?>

                          &nbsp<?php echo $dato->EQUIPO ?>

                      <a href="eliminar_turno.php?id=<?php echo $dato->ID_TURNO ?>" class=" btn btn_color btn_eliminar ">
                        Cancelar

Ese codigo llama a un php que se llama "eliminar_turno.php" y obtiene la id y asi borra el turno deseado el tema es que cuando se borra la pagina se actualiza y no quiero que pase eso, si alguien sabe como hacerlo por favor expliqueme, muchas gracias, si necesitan algo mas estoy por aca.

A: La mejor manera será utilizando AJAX

<title>Elimnar</title>

<input type="button" href="javascript:;" onclick="realizaProceso(<?php echo $dato->ID_TURNO ?>)" value="Eliminar"/>

Resultado:

Recibimos los parametros en eliminar_turno.php

<?php
if(!isset($_POST['id'])){
    header('Location: home.php');
}else{
    include('model/conexion.php');
    $id = $_POST['id'];

    $consulta = $con -> prepare("DELETE FROM turnos WHERE ID_TURNO=?;");
    $result = $consulta->execute([$id]);

    if($result == true){
        echo "Eliminado";
    }else{
        echo "Error de Eliminacion";
    }

  }

?>

A: Te recomiendo que utilices Fetch con Javascript el cual te permite enviar una peticion asíncronas utilizando promesas y de forma que el código sea un poco más sencillo y aparte es el nuevo estandar de Javascript según el EcmaScript y por otro lado, por SEGURIDAD utiliza el metodo POST ya que por medio del metodo GET estas mostrando el codigo en la URL y cualquiera puede seguir escribiendo peticiones de eliminacion mientras que con POST el hilo va interno y así ejecutas la eliminación del dato sin recargar la pagina y sin exibir algun dato:
Este Seria el llamado a la funcion:
<input type="button" href="javascript:;" onclick="eliminarRegistro(<?php echo $dato->ID_TURNO ?>)" value="Eliminar"/>

Este seria la funcion:
function eliminarRegistro(id_eliminar){

var formData = new FormData();

formData.append('id', id_eliminar);

fetch('./eliminar_turno.php', {
  method: 'POST',
  body: formData
})
.then(response => response.text())
.catch(error => console.error('Error:', error))
.then(response => console.log('Exitoso:', response));
}

Aqui el php que recibe:
 <?php
if(!isset($_POST['id'])){
    header('Location: home.php');
}else{
    include('model/conexion.php');
    $id = $_POST['id'];

    $consulta = $con -> prepare("DELETE FROM turnos WHERE ID_TURNO=?;");
    $result = $consulta->execute([$id]);

    if($result == true){
        echo "Eliminado";
        return;
    }else{
        echo "Error";
        return;
    }

  }

?>

Como veras, en el php cambie que recibes por metodo post ya que es mas seguro y tambien cambie la salida colocandole return.
Espero que te haya podido ayudar.


text:
Q: How come there is no wp-content directory in wp theme I am using Mochhost.com as my Hosting. Recently I have downloaded a free wp theme from wordpress.org. I unzipped the theme and I uploaded to my site at http://thegoods.info into my root directory, that is, public_html  with Filezilla. Now my question is, I am unable to see the wp-content directory both in the Filezilla part as well as in my local machine. At first I thought I could not downloaded the theme properly from Wordpress.org. And for a double check I downloaded another free theme from Wordpress.org and I unzipped it and I saw the same thing, NO WP-CONTENT directory.
Previously I downloaded many wp themes from Wordpress.org and I purchased WP themes. But always there was this directory. I need to locate this directory in order to edit the file wp-config-sample.php file for entering my data bases there and rename this file as wp-confiq.php. To start this process I need this directory wp-content first.
Could you please help me to solve my issue. Would appreciate much for that.
Thanks
Kamrul
kochi97

A: wp-config-sample.php lives in your public_html directory.
Wordpress installation is normally called latest.zip and available at http://wordpress.org/latest.zip
If you are using Filezila, get that zip file, unzip locally and upload the contents of the zip file to your public_html directory.
Edit wp-config-sample.php, rename it to wp-config.php and point your browser to http://thegoods.info You should see the 5 minute install instructions.

A: I think that you are mistaken about how WordPress themes work, or what comes bundled with a theme. You can't just download the theme and drop it into the web root directory, which is what it sounds like you did. Your theme operates inside the context of the WordPress core. You need to download WordPress itself, and install it. That is the part that goes in the web root directory. Inside the WordPress files there should be a wp-content directory. After you have installed WordPress, then download your theme and put it in the wp-content directory.


text:
Q: Show/hide buttons based on a dropdown list Currently I have an aspx page that contains a dropdown list and four buttons.
Based on the selection made in the dropdown list then a combination of the buttons are displayed.
I currently have this implemented so that when the user makes a selection I am using AutoPostBack and the selectedChanged server side event to determine which buttons to display and then set the Visible property of these buttons in this method.
Due to the fact that this posts back I don't think its a nice solution as the whole page is posting back. I would prefer to do this using JSON.
I made the following attempt but it doesn't seem to work:
$(document).ready(function () {
            jQuery("#<%= MyDropdownList.ClientID %>").change(function () {
                 updateAvailableButtons(jQuery(this).val());
        });

    });

function updateAvailableButtons(selectedItemId) {
        jQuery("h2").html("selectedItemId:" + selectedItemId);
        jQuery.getJSON("MyPage.aspx/GetAvailableButtons?" + Id, function (data, textStatus) { debugger; });
    }

Server side:
protected void GetAvailableButtons(int selectedItemId)
    {
      //based on the id here then then I show hide certain buttons.
      button1.Visible = true;
      button2.Visible = false;
      button3.Visible = false;
      button4.Visible = false;
    }

I've never worked with JSON before so apologies if this is way off.

A: Similar task can be done using JavaScript.  The problem is that you'll need to use a html  control instead of an asp.net button control so that you can manipulate form the client side.


text:
Q: Determine time complexity of arithmetic progression I am novice in analysing time complexity.some one can help me with the time complexity of below algorithm?
public void test(int n)
{
  for(int i=1;i<=n;i=i+2)
    {
     for(int j=1;j<=i;j++)
     {}
    }
}

outer loop will run n/2 times.Inner loop will run (1+3+5+7+9...n) times.
what will be time  complexity of inner loop and how can we calculate sum of such arithmitic progression?

A: Assume n is odd. Then n = 2k + 1 for some k. Now
  1 + 3 + … + n
= 1 + 3 + … + 2k+1
= (1 + 3 + … + 2k + 1) + (1 + 1 + … + 1) - (1 + 1 + … + 1)
= (1 + 1) + (3 + 1) + … + (2k + 1 + 1) - (1 + 1 + … + 1)
= 2 + 4 + … + 2k+2 - (1 + 1 + … + 1)
= 2(1 + 2 + … + k+1) - (1 + 1 + … + 1)
= 2(k+1)(k+2)/2 - (k+1)
= k^2 + 3k + 2 - k - 1
= k^2 + 2k + 1
= (k+1)^2
= (n+1)^2/4

We can test a few terms...
n    f(n)    Series Sum
1    1       1 = 1
3    4       1 + 3 = 4
5    9       1 + 3 + 5 = 9
7    16      1 + 4 + 5 + 7 = 16

Looks like it checks out.


text:
Q: How to disable inline headphone controls on Windows 10/11 I have a pair of (3.5mm) headphones that work fine but send erroneous headphone control signals (i.e. raising and lowering the volume, skipping/pausing). Personally, I never use inline headphone controls anyway.
I'm pretty sure there isn't any official way to disable inline headphone controls on Windows, but is there a registry hack, or an external program that could do the same thing? Thanks!


text:
Q: Navigation Bar Glitches at start of refresh new pages I'm building a website (http://theastbury.terryslaughter.com).
Whenever you navigate to a new page or refresh the current page, the navigation bar glitches. The logo is larger and the menu appears (even though display: none). Then it resizes and the menu disappears.
I'm not sure if it's because the site is too slow or something. Any suggestions?

A: Browsers ready the code from top to bottom. Looking at your code you have built the nav before the call for the css.
Your start building the nav on line 15.
And your first call to an internal CSS thats not for google or external fonts is line 48.
Also your divs for your nav are in your head and not the body if I'm I'm reading everything correctly.

A: Also you have two navs here:
the one in your head at line 15
Then there is also the call to another nav which I assume is a native Wordpress nav  on line 1016 which starts with <-- site-branding -->


text:
Q: Can I log current using a voltage input and V=IR I have a sensor which produces a current proportional to the variable it is sensing. My data logger only accepts input as a varying voltage, which it then encodes in 8 bits (scaled linearly to volts). Can I somehow use this and a knowledge of the equation V=IR to allow me to  measure the current (and therefore the variable that the current is proportional to) with my datalogger? Or would I need to find a logger that can log current directly?

A: Yes.  Pass the current through a resistor to ground, then measure the voltage across that resistor with your data logger.

A: If the sensor is "happy" to provide a voltage output of say 1 to 5 volts then converting the current to voltage with a resistor and measuring it directly with an ADC that measures voltage is a good solution.
eg if maximum sensor output = 20 mA
 and maximum ADC voltage input is 5 volts
 you can convert max of one to the max of the other
 with a resistor such that
 R = V/I = Vimmax / Ioutmax
 In this case R = 5V/20 mA = 250 ohms
 This would be the MAXIMUM value of R that can be used. You can use any lower value for a correspondingly lower maximum voltage.
eg if you use a 100 ohm resistor.
 V at max reading = Imax x R = 20 mA x 100 ohms = 2 Volts.
 If your ADC has a max input voltage of say 5V then a 2V reading is only 40% of full scale and you are wasting possible resolution.
From above
 - Rmax = Vmax_ADC_input / I_max_sensor_output.

Low allowable max load voltage
In some cases the sensor has a limited amount of voltage rise that it can drive a load to and this may be far less than your ADC input max voltage. Ij such a case you would lose too much resolution by using it directly.
eg if allowable max voltage = 100 mV and Imax = 20 mA then R = V/I = 0.1/20mA = 5 ohms.
This satisfies tye sensor max allowable load voltage BUT if your ADC has a full scale range of say 5V then 0.1V is only 0.1/5 = 2% of the total range -> much resolution lost.
In such cases the normal approaoch is to amplify the voltage across the sense resistor. In this case a gain of 50 would produce 5V out at Imax = 20 mA with a 5 ohm sense resistor.
To provide precision gain in such cases it is common to use an "instrumentation" amplifier" which is just 1 or 2 or 3 opamps (cctc vary) with characteristics suited to this sort of application. More on that anon maybe.

A: Yes, if the sensor shares ground with your data logger then as Majenko says you can probably just connect the current source to a resistor, the other end to ground and measure the voltage across the resistor.
For instance let's say you ADC range is 5V (so 5V = 11111111) and you want to measure current from 0 to 100mA.
5V/0.1A = 50 ohms. Each ADC step would represent 100mA/256 = 0.39mA
Often a lower sense resistor is required, so some amplification may be a good idea (e.g. in the above example use 10 x gain and a 5 ohm resistor)
If you give a few more details (sensor model, what you are sensing, etc) then we can be sure of what is best.


text:
Q: Fundamental Units in Totally Real Cubic Fields How much is known about the fundamental units in totally real cubic fields? For example, Daniel Shanks has a family of totally real cubic fields for which the fundamental units are known; those with defining polynomial $x^3-ax^2-(a+3)x -1$. Does anyone know of other families of totally real cubic fields for which the fundamental units are known? I'm particularly interested in cubic subfields of cyclotomic extensions.

A: Here are two references that may be useful.

*

*Algebraic number fields with 2 independent units, 1931, by W. E. H. Berwick.

*The determination of units in totally real cubic fields, 1959, by H. J. Godwin.


text:
Q: missing FROM-clause entry for table in SQLAlchemy This is my query builder method:
def query_builder(search_parameter):
    query = BusinessOwner.query
    # query = query.select_from(BusinessOwnerTask)
    query = query.join(services, BusinessOwnerTask.services_id == services.c.id). \
        join(BusinessOwnerTask, BusinessOwnerTask.business_owner_id == BusinessOwner.id)
    query = query.filter(services.c.service_grade_id == search_parameter.service_grade)
    if len(search_parameter.name) > 0:
        query = query.filter(BusinessOwner.name == search_parameter.name)
    if len(search_parameter.service_types) > 0:
        query = query.filter(BusinessOwnerTask.services_id.in_(search_parameter.service_types))

    return query

This code has been run on sqlite3 ,However, when query.all() calls, it complains on postgres:

ProgrammingError: (psycopg2.ProgrammingError) missing FROM-clause
  entry for table "business_owner_tasks" LINE 2: FROM business_owners
  JOIN services ON business_owner_tasks.s...

I decided to add this:
query = query.select_from(BusinessOwnerTask)

It complains:

ProgrammingError: (psycopg2.ProgrammingError) table name
  "business_owner_tasks" specified more than once

What is my mistake?

A: I change query builder to this one:
query = db.session.query(BusinessOwnerTask, BusinessOwner, services) \
            .join(services, BusinessOwnerTask.services_id == services.c.id) \
            .join(BusinessOwner, BusinessOwner.id == BusinessOwnerTask.business_owner_id) \
            .filter(services.c.service_grade_id == search_parameter.service_grade)

        if len(search_parameter.name) > 0:
            query = query.filter(BusinessOwner.name == search_parameter.name)
        if len(search_parameter.service_types) > 0:
            query = query.filter(services.c.service_type_id.in_(search_parameter.service_types))

Tip:
It is better to first make your query on pure sql on pgAdmin or other tools. Then make your query on ORM tool


text:
Q: What happens to private vars at the end of a sub routine? I have a script that reads of a global config file using Config::Tiny. Based on selection variable my script chooses a sub routine for either SQLite, MySQL or PgSQL.
Right now the config file is read at the top of the script and variables are set outside of the sub routines. But considering the MySQL vars have nothing to do with PgSQL or SQLite I wanted to set private vars in the sub routines. The only thing I am wondering is what happens to the vars once the sub routine has ran its course? Do they get removed?

A: Since Perl 5 has no such thing as "private vars", I am going to assume you mean lexical variables declared with the my function.  At the end of the scope in which a lexical variable was declared, the reference count for that chunk of memory is decremented.  If this means the reference count goes to zero, then it gets garbage collected.  Since functions provide scope, then so long as you are not passing references to those variables to something that holds on to them, or using them in a closure, then they should be garbage collected.

A: Variables declared in subroutines will not exist after the subroutine returns.  Their memory will be released, and any referenced values will be eligible for garbage collection (assuming that nothing else references those values).


text:
Q: Azure iOS pipeline get failed after xCode 11.4 After updating the Xcode version to 11.4 or 11.4.1 or 11.5 getting following error. The pipeline is working fine on 11.3.1 version. Does anyone facing same issue?
xcrun: error: missing DEVELOPER_DIR path: /Applications/Xcode_11.5.app/Contents/Developer

Even if I set xCode version to default, it is picking xCode 11.3.1 whereas on Azure documentation it said default version is 11.4.1.
https://github.com/microsoft/azure-pipelines-image-generation/blob/master/images/macos/macos-10.15-Readme.md
Thanks for your help in advance.

A: In my test, when I used macOS-10.15 hosted agent to run, the default version of Xcode was 11.4.1.

You can check whether you use macOS-10.15 image in the pipleine log.


text:
Q: Tesseract OCR - TIFFReadDirectory: Warning, Unknown field with tag 37724 (0x935c) Used Tesseract to analyze a .tif image and encountered the errors below. Tried to Google but did not get a definite answer. Has anyone experienced these before?
Command: tesseract "source.tif" "destination" -l swe
https://github.com/UB-Mannheim/tesseract/wiki
Tesseract Open Source OCR Engine v3.05.00dev with Leptonica
TIFFReadDirectory: Warning, Unknown field with tag 37724 (0x935c) encountered.
TIFFFetchNormalTag: Warning, Incompatible type for "RichTIFFIPTC"; tag ignored.
Page 1
TIFFReadDirectory: Warning, Unknown field with tag 37724 (0x935c) encountered.
TIFFFetchNormalTag: Warning, Incompatible type for "RichTIFFIPTC"; tag ignored.

A: The warnings came from libtiff indicating discrepancies in the input TIFF image. They can be ignored, or use quiet option if you want to suppress them from printing to the console.
https://github.com/tesseract-ocr/tesseract/wiki/FAQ#how-can-i-suppress-tesseract-info-line


text:
Q: Is there a way to position a bootstrap modal popup in iframe near the clicked button? I am using an iframe to display a php page. I used a script within the iframe that sizes it to the documents height. This allows the user to scroll the main window without having dual scroll bars on the page. I am using a bootstrap modal within the iframe to display an image. The issue is that when clicked the modal popup is displayed at the top center of the iframe. However if the user had to scroll down the list prior to clicking the 'show image' button, they wont find the popup unless they know to scroll all the way back to the top.
I have searched relentlessly for a solution to this within this site and google with no clear understandable answer. Hoping one of you experts can enlighten me.
Here is my modal code:

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

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Here is the script:

Here is the iframe script used to get height of content to be displayed:

As stated previously, this code works but pops up the image at the top center of the iframe. I would really like it to either pop up near the button clicked or at least visible.

A: In my case, using Bootstrap 3.4, what I could make is to catch the show.bs.modal event and setup its position according the click. To avoid the glitch effect, I hide the modal and show it after move it.
I didn't find the way to parametrize the modal in its creation to set it up, instead of enforce it.
$('#theModalDiv').on('show.bs.modal', function (event) {
    const modalWidth = 600; // Because #attendeesModal has no lg nor sm size
                            // and by default, bootstrap modals has 600px width
    const target = $(event.relatedTarget);
    let newLeft = (document.getElementById('iframe-content-body').offsetWidth/2) - (modalWidth); // Centering the modal
    const modal = $(this); // Getting modal instance
    modal.css('opacity', '0'); // Hidding modal

    // After some time...
    setTimeout(() => {
        modal.offset({
            // ...setting new modal position
            ...target.offset(),
            left: newLeft,
        });

        // ...setting same top position as the click
        $('.modal-dialog').css('margin-top', 0);

        // ...displaying again the modal
        modal.css('opacity', '1');
    }, 500); // This value was taken with rule of thumb
});

I hope someone can find this usefull.


text:
Q: How can I replace 12 byte data from a local file? My App would download a file which the first 12 byte data was encrypted,so I have to read this file from Document and decrypt the first 12 byte data.
My first try was to read the whole file and decrypt it then write to file again. but if the file is too large , this will cost a lot of memory.
So ,Is there anyway to let me read the first 12 byte data and replace it?

A: This is a std way of doing in any language.
Read a file in chunk Replace in Buffer write in Temporary file delete the original file and rename temporary file as original file.
As far as objective C concerned i found a useful link
http://www.techotopia.com/index.php/Working_with_Files_in_Objective-C
goto this topic "Writing Data to a File"

A: Well Objective-C is based on C and hence all the functions including file-operation functions should work out-of-the-box. You can convert the NSString file-path to char array and perform the desired file operations with the help of the this link.

A: #include <stdio.h>

FILE *f = fopen("yourFileName", "rb");
if(f == NULL)
    ; // handle exception
int nBytesToRead;
char theBuffer[nBytesToRead];
size_t bytesRead = fread(theBuffer, 1, nBytesToRead, f);
// do with your bytesRead
fclose(f);


text:
Q: Delete \n charater with Python I have a list of sentences which have this "\n" character.
[("Types of Third\n-\nParties\n"),("Examples of third\n-\nparties"), ...]

I tried with the following code :
def remove_whitespace(sent_text):
    j=0
    for i in sent_text:
        sent_text[j]=i.rstrip("\n")
        j+=1

 remove_whitespace(sent_text)

But the \n character didn't disappear.
Any idea please?
Thanks

A: Using str.split & str.join
Ex:
data = [("Types of Third\n-\nParties\n"),("Examples of third\n-\nparties")]
for text in data:
    text = "".join(text.split("\n"))
    print(text)

Output:
Types of Third-Parties
Examples of third-parties

A: One quick solution is using str.replace.
In your case:
def remove_whitespace(sent_text):
    j=0
    for i in sent_text:
        sent_text[j]=i.replace("\n","")
        j+=1

A: You can use rstrip() function.
If text is coming with \n or \r, text.rstrip() takes these off.

A: You can also use list comprehension to remove these unwanted items.
input_list = [("Types of Third\n-\nParties\n"),("Examples of third\n-\nparties")]

def expunge_unwanted_elements(input_variable):
  cleaned =  [item.replace('\n', ' ').strip() for item in input_variable]

  # Do you want to remove the dashes?  If so use this one.
  # cleaned = [item.replace('\n', '').replace('-', ' ').strip() for item in input_variable]

  return cleaned

print (expunge_unwanted_elements(input_list))
# outputs
['Types of Third - Parties', 'Examples of third - parties']

# or this output if you use the other cleaned in the function
['Types of Third Parties', 'Examples of third parties']


text:
Q: Xenomai modules installation using Buildroot I would like to test Xenomai features with the latency test under a specified load but when I try to execute the command the follwing error shows up.
# ./latency -p 100
sh: ./latency command not found

The system has been built with Buildroot. In the /proc/xenomai folder, the version file contains:
$ cat /proc/xenomai/version
2.6.4

Here is the relevant part of the configuration file I have used to build the system:
-- Target Packages
   -- Real Time
      -- Xenomai Userspace
        (2.6.4) Custom Xenomai version
          [*]   Install testsuite
          [ ]   RtCan utilities
          [*]   Analogy libs and utils
          [*]   Native skin library
          [*]   POSIX skin library
          [ ]   VX-Works skin library
          [ ]   PSOS skin library
          [ ]   RTAI skin library
          [ ]   uiTron skin library
          [ ]   VRTX skin library

Is this configuration file correct? Where can I find all the test programs provided by Xenomai?
EDIT
there is no xenomai folder in usr/.
I've noticed in /usr/bin the following programs:
# ls /usr/bin | grep xeno
xeno-regression-test
xeno-test-run
xeno-test-run-wrapper

How can I use this files?
The only folder called xenomai is the one in the /proc
# ls /proc/xenomai
acct apc faults heap interfaces/ irq latency registry/
rtdm/ sched schedclasses/ stat timebases timer timerstat/
version
# cd /proc/xenomai
# ./latency -p 100
sh: /latency: Permission denied
# sudo ./latency -p 100
sudo: ./latency: command not found

EDIT2
The content of output/target/usr/bin does not contain the latency program:
userk@dopamine:~/Development/Linux/RaspberryPi/buildroot-2013.11-Copy2015/output/target/usr/bin$ l | grep latency
userk@dopamine:~/Development/Linux/RaspberryPi/buildroot-2013.11-Copy2015/output/target/usr/bin$

A: Well,
# ./latency -p 100
sh: ./latency command not found

Here you're trying to run latency, located in the directory where you're standing. (And I guess your standing in /root).
Try running
# latency -p 100

and see if that helps.
To help you, I made a test build with the Xenomai configuration shown below:
    [*] Xenomai Userspace                                                                                │ │
  │ │     ()    Custom Xenomai version                                                                                │ │
  │ │     [*]   Install testsuite                                                                                │ │
  │ │     [ ]   RTCan utilities                                                                                │ │
  │ │     [ ]   Analogy libs and utils                                                                                │ │
  │ │     [*]   Native skin library                                                                                │ │
  │ │     [*]   POSIX skin library                                                                                │ │
  │ │     [ ]   VX-Works skin library                                                                                │ │
  │ │     [ ]   PSOS skin library                                                                                │ │
  │ │     [ ]   RTAI skin library                                                                                │ │
  │ │     [ ]   uiTron skin library                                                                                │ │
  │ │     [ ]   VRTX skin library

This places latency in output/target/usr/bin/latency. (I.e. it's located in /usr/bin/latency on your target).

A: This is a possible workaround for the raspberry pi. SOURCE
wget http://download.gna.org/xenomai/stable/xenomai-2.6.4.tar.bz2
tar xjf xenomai-2.6.4.tar.bz2
cd xenomai-2.6.4
## Here you should invoke the script to prepare the kernel with the adeos patch but since I'm using Buildroot we can jump this step
mkdir raspPI
PATH=$PATH:insert_the_cross_compiler_path_here
./configure --host=arm-linux CFLAGS='-march=armv6' LDFLAGS='-march=armv6'
make
make DESTDIR=$(pwd)/raspPI install
cd raspPI/
raspPI$ tar cjf xenomai-rpi.tar.bz2 usr/xenomai/bin/ usr/xenomai/sbin/ usr/xenomai/lib/

*

*Finally copy the compressed archive to you raspberry pi using a ssh and untar it.
scp xenomai-rpi.tar.bz2 root@IP_Address_of_the_RPi:/
The archive will be copied in the root directory.
From the raspberry pi, uncompress xenomai-rpi.tar.bz2 to the root of the filesystem
tar -xvjf xenomai-rpi.tar.bz2
ls usr/xenomai/bin/
arith       cmd_write            insn_bits   latency               rtcansend    wf_generate           xeno-test
check-vdso  cond-torture-native  insn_read   mutex-torture-native  rtdm         wrap-link.sh          xeno-test-run
clocktest   cond-torture-posix   insn_write  mutex-torture-posix   sched-tp     xeno                  xeno-test-run-wrapper
cmd_bits    cyclictest           irqloop     regression            switchtest   xeno-config
cmd_read    dohell               klatency    rtcanrecv             wakeup-time  xeno-regression-test

*

*Or you can do it manually:
cd /usr/xenomai
raspPI/usr/xenomai$ scp bin/* root@ip_address:/usr/bin
raspPI/usr/xenomai$ scp sbin/* root@ip_address:/usr/sbin
raspPI/usr/xenomai$ scp lib/* root@ip_address:/usr/lib
You have now all the modules to test the Xenomai real time features!


text:
Q: Need more insights about this css selector

Hello World

Hello World

I'm wondering which is the different between this way to select:

*

*.thisOne{ background: red;}

*div[class*="thisTwo"] { background: green}
They do pretty much the same job, right? why is 2-selector more advance then?

A: Actually, they don't do the same thing. The attribute selector that functions identically to div.thisTwo is div[class~="thisTwo"]. Notice the use of ~ rather than *. Not to mention your .thisOne selector also lacks the div in front.
div[class*="thisTwo"] selects any div whose class attribute contains the string thisTwo, but it doesn't account for any spaces separating this string from other classes. It just looks for the string anywhere in the attribute value.
This means that it would match the following element, which div.thisTwo could not possibly match because it has only one class thisOne-thisTwo, which contains the string thisTwo, and not two separate classes thisOne and thisTwo:

A: No the don't. The first will select any element with class name thisOne. The second will select any div that its class contains the term thisTwo.


text:
Q: libqt5webchannel.so.5 missing or not found in Ubuntu 16.04 I am trying to create deb of QT 5.5 app which uses QT5 webkit and webkitwidgets in it. When I am trying to create deb with command "debuild -kMYGPGKEY" then it gives me below error.
/usr/bin/ld: warning: libQt5WebChannel.so.5, needed by /home/myusername/Qt5.5.0/5.5/gcc_64/lib/libQt5WebKit.so.5.5.0, not found (try using -rpath or -rpath-link)

/home/myusername/Qt5.5.0/5.5/gcc_64/lib/libQt5WebKit.so.5.5.0: undefined reference to `QAccelerometer::QAccelerometer(QObject*)'
/home/myusername/Qt5.5.0/5.5/gcc_64/lib/libQt5WebKit.so.5.5.0: undefined reference to `QRotationReading::x() const'

any many more these types of undefined reference errors.
From the error I found that libQt5WebKit is taking the reference libQt5WebChannel which is not found in my machine.
So if anybody has any idea about the issue or how can I install libqt5webchannel.so.5  in Ubuntu 16.04 then please let me know.
Thanks.

A: (Run into a similar problem with https://github.com/GPUOpen-Tools/CodeXL)
Solution :
sudo apt install libqt5webchannel5-dev
Explication
The good habit is to look onto https://packages.ubuntu.com/zesty/libqt5webchannel5-dev site with the missing file/library name and change "package names" into "package contents" at the bar search.

A: Building qt5webchannel :
git clone git://code.qt.io/qt/qtwebchannel.git
qmake-qt5
make
sudo make install

EDIT : Sorry, fails with Ubuntu16.04 :
No /usr/include/x86_64-linux-gnu/qt5/QtGui/QApplication ... That could be the reason for no qtwebchannel in Debian, Ubuntu : A less complete Qt5 ?


text:
Q: Clarification on interpreting Wald's test and Likelihood ratio tests I am running multinomial logistic regression analysis on my data.  The response variable is the number of calves produced each year (0,1, or 2).  I am trying to evaluate the influence of the X variables on the odds of producing a calf.  My X variables are predation risk (WR; continuous), age of mother (age; categorical or continuous), time (wolf; categorical).
First, I have 4 different age classification schemes (i only show 2) - I want to know which one of the age of mother would be "best" to use. I could use it as continuous variable - or as categories based on biological reasoning for senescence in older moose (old ladies don't invest in reproduction as much).  So, I thought I would use a likelihood ratio test.
library(mlogit)

modata.model1 <- mlogit(no.C ~ 1 | 1, data=modata, reflevel="1", na.action = na.omit)
modata.model2 <- mlogit(no.C ~ 1 | age, data=modata, reflevel="1", na.action = na.omit)
modata.model3 <- mlogit(no.C ~ 1 | age2, data=modata, reflevel="1", na.action = na.omit)

 lrtest(modata.model2,modata.model3)

Likelihood ratio test

Model 1: no.C ~ 1 | age
Model 2: no.C ~ 1 | age2
  #Df  LogLik Df  Chisq Pr(>Chisq)
1   4 -213.22
2   4 -207.57  0 11.309  < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

QUESTION: to interpret this output - there was a significant difference in the loglikelihood when we comparing the continuous age to a categorical age with 2 classes.  The loglik is smaller for model 1 and therefore it would be better to use? Or do I have that backwards?
Next I was going to use the Walds test to evaluate nested models.  To see if the addition of a variable was worth it.
modata.model7 <- mlogit(no.C ~ 1 | age+WR, data=modata, reflevel="1", na.action = na.omit)

modata.model8 <- mlogit(no.C ~ 1 | age+WR+wolf, data=modata, reflevel="1", na.action = na.omit)

Wald test

Model 1: no.C ~ 1 | age + WR
Model 2: no.C ~ 1 | age + WR + wolf
  Res.Df Df  Chisq Pr(>Chisq)
1    244
2    242  2 0.5828     0.7472

QUESTION: this tells me that there is no significant improvement when there is an additional variable of wolf added??  So, then I can use the smaller model or do I use the one with the smaller Res.DF?
In addition to confirming my interpretations of the results I have 2 side questions...
1)to get the null model for mlogit library - is my modata.model1 correct?  I want the intercept only model to compare against.
2) Hosmer and Lemshow suggest by getting Wald values to get significance levels for each coefficient - in mlogit, thats the same as using summary(model) and there they provide the t-values with p instead of needing to do an additional Walds test? (NOTE in the below model i use 2 category age class instead of continuous)
summary(modata.model8)

Call:
mlogit(formula = no.C ~ 1 | age2 + WR + wolf, data = modata,
    na.action = na.omit, reflevel = "1", method = "nr", print.level = 0)

Frequencies of alternatives:
    1     0     2
0.652 0.244 0.104

nr method
6 iterations, 0h:0m:0s
g'(-H)^-1g = 7.4E-06
successive function values within tolerance limits

Coefficients :
              Estimate Std. Error t-value Pr(>|t|)
0:(intercept)  0.38730    0.40144  0.9648 0.334657
2:(intercept) -2.40317    1.04546 -2.2987 0.021523 *
0:age21       -1.39607    0.43989 -3.1737 0.001505 **
2:age21        0.53952    1.07275  0.5029 0.615012
0:WR          -1.46584    0.64797 -2.2622 0.023686 *
2:WR          -0.19214    0.60856 -0.3157 0.752206
0:wolf1        0.56055    0.63292  0.8857 0.375797
2:wolf1        0.42642    0.72375  0.5892 0.555744
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Log-Likelihood: -203.11
McFadden R^2:  0.053606
Likelihood ratio test : chisq = 23.009 (p.value = 0.00079359)


text:
Q: How can I connect an Azure application using Windows Authentication to onpremise SQL DB How can I connect an Azure application using Windows Authentication to onpremise SQL DB.
I have a site to site connection established to a machine now I want to create an application using Windows Authentication and connect to on premise SQL DB and do all the DML operations.
How can I achieve this.
Thanks in Advance.
Regards,
Suresh


text:
Q: Verifying the number of times the method was called using Mockito? I am new to mockito...
What I am trying to do is to use mockito and System.print out the number of times that a certain method was called...
For example,
The numer of times that the Class.doSomething() was called: n times
I guess we need to use verify() or Invocations but I have been searching up about this for hours but have not found any solutions...
Can someone please help me with this?
Thanks!

A: *

*assume that you have a class Sample With method doSomehting

public class Sample {
    public void doSomething();
}

*in JUnit test case, verify the method was called n times using Mockito

@Test
public void testMockitoTimes {
    Sample sample = Mockito.mock(Sample.class);
    sample.doSomething(); .....
    Mockito.verfiy(sample, Mockito.times(n)).doSomething();
}

*there is a lot of link that you could refer, such as verify-a-method-is-called-two-times-with-mockito

A: I don't think you can print a message each time the method is called. You can add the log on the production code or use proxy on the method for add logging layer.
@Mock
private MockedObject mockedObject;

verify(mockedObject,times(2)).doSomething();


text:
Q: How to update Secrets (Without Deleting and Creating) in Openshift? I have a folder in my server that I want to update inside a cointaier in a pod. How do I do that without deleting the Secret?
I know that the following creates my secret:

oc create secret generic privkey --from-file=/opt/privkey

I know that the following deletes the secret:

oc delete secret generic privkey

Is there a way to do that without deleting?
I am fine if I have to delete the pod.

A: try this:
oc create secret generic privkey --from-file=/opt/privkey --dry-run -o yaml | oc replace -f -


text:
Q: Bug with iOS7 showing the soft keyboard with phonegap and Intel App Framework I use the excellent Intel AppFramework for the UI of my phonegap / cordova apps, but since iOS7, sometime, when I open the keyboard, the bottom menu goes up (it should not):
http://screencloud.net/v/9omt
And then, when I close the keyboard, the bottom menu stay in the middle of the screen:
http://screencloud.net/v/DgRf
It looks like the bug is in the hideAddressBar function. I disabled the function, and now, the menu always goes up, but at least, it always goes done when I close the keyboard.
(we use the 1.0 version. We plan to update soon, but we are in the middle of an urgent release)
Thanks in advance for any help or directions,

A: This solution worked for me. I had the following meta tag in my index.html:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

And I change it to this:
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, target-densityDpi=device-dpi" />

The most important attribute is height=device-height, it says that the view size will always be the size of the device.
Edit: there is a bug with the iPad in landscape and iOS7. The CSS sizes of the viewport are wrong...

A: I'm in the same boat as you and trying to figure out a working solution.  I am working with one of the main ios phoengap contributers over here: https://issues.apache.org/jira/browse/CB-3020
He posted an updated solution and 3.1 should be coming out soon with the patched fixes.
I'm still running into some issues and have the black bar at the bottom randomly showing on certain pages.
Head over to the cordova jira site and add in your testing details to help out.
Thanks!

A: While the Samuel's response should fix the problem, it will create other side effects. For example in Phonegap 3.3 adding height=device-height to viewport, you would get scroll in every screens (even when the elements on the page are not big enough to full the screen). In our case the only solution ,found here, was add a notification handler to the open keyboard on Phonegap which calls to a javascript function, and then hide the fixed footer on this function, besides hide/show the footer again in focus/blur functions. An example using jquery mobile is attached, but you could update it to use a different framework:
On javascript:
  $(document).on('focus','input, select, textarea',function() {
    if( device.platform=== 'iOS' && parseInt(device.version.substring(0,1)) >= 7){
        if($(this).attr('readonly')===undefined){
            $("[data-role=footer]").hide();
        }
    }
  });

  $(document).on('blur','input, select, textarea',function(){
    if( device.platform=== 'iOS' && parseInt(device.version.substring(0,1)) >= 7){
        if($(this).attr('readonly')===undefined){
            $("[data-role=footer]").show();
        }
    }
    setTimeout(function() {
        window.scrollTo(document.body.scrollLeft, document.body.scrollTop);
    }, 0);
  });

  function hideFooter(){
    if( device.platform=== 'iOS' && parseInt(device.version.substring(0,1)) >= 7){
        if($(this).attr('readonly')===undefined) {
            $("[data-role=footer]").hide();
        }
    }
  }

And in phonegap MainViewController.m:
- (id)init
{
    self = [super init];
    if (self) {
        // Uncomment to override the CDVCommandDelegateImpl used
        // _commandDelegate = [[MainCommandDelegate alloc] initWithViewController:self];
        // Uncomment to override the CDVCommandQueue used
        // _commandQueue = [[MainCommandQueue alloc] initWithViewController:self];
        }

    //fix for ios7 footer is scrolled up when the keyboard popsup.
    [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    return self;
}

-(void)keyboardWillShow:(NSNotification*)notification{
    if (IsAtLeastiOSVersion(@"7.0")){
        [self.webView stringByEvaluatingJavaScriptFromString:@"hideFooter()"];
    }
}


text:
Q: how to prevent user when opening a new tab,minimising,maximising in browser using javascript jquery I have to restrict the user of opening new tab,minimizing or opening another browser while running a web page.
Is there any way for me to make this happening?

A: One liner answer, you can't. You can control your page certain extend programmatically by restricting resize of the window or make it full screen  but you can't restrict users minimizing or opening another browser while running a web page.
Click here for details of browser full screen mode programmatically, this full screen mode provides an illusion of restricting of another browser opening by hiding the options. But that's not the case, once user exit from full screen everything will be back in original state, so users can perform minimizing or opening another browser or a new tab.


text:
Q: Intellij 14 ultimate version runs very slow with java jdk 1.8 I have searched some articles online says there are ways to optimize the speed with jdk 1.7, but by changing jvm memory size seems not working with jdk 1.8 version.
any solutions to this issue ? thanks.

A: Some things which you should consider for optimizing performance:
* Memory: this is the most important point IMHO, but you have written that you have changed the setting already. Are you absolutely sure your config has been picked up? E.g. there is separate config file for 64 / 32 bit.
* Disable plugins: Make sure everything you do not not need is disabled. This way IntelliJ also starts up faster.
See also: https://www.jetbrains.com/idea/help/tuning-intellij-idea.html
If this still does not help, please provide more information what exactly is very slow.


text:
Q: Is there a way to turn this into a loop? Is there a way to turn this into a loop, where the city names (berlin, munich, hamburg, cologne) are looped in the calculations as well as in the print? If so, how do i do it?
max_b = airquality_berlin['NO2'].max()
min_b = airquality_berlin['NO2'].min()

print(f"The inter-annual range of NO2-concentration in Berlin is: {max_b-min_b}\n")

max_b = airquality_munich['NO2'].max()
min_b = airquality_munich['NO2'].min()

print(f"The inter-annual range of NO2-concentration in Munich is: {max_b-min_b}\n")

max_b = airquality_hamburg['NO2'].max()
min_b = airquality_hamburg['NO2'].min()

print(f"The inter-annual range of NO2-concentration in Hamburg is: {max_b-min_b}\n")

max_b = airquality_cologne['NO2'].max()
min_b = airquality_cologne['NO2'].min()

print(f"The inter-annual range of NO2-concentration in Cologne is: {max_b-min_b}\n")

A: You'll be wanting to put your data in a data structure. For example, here is a way of doing it with a list of dictionaries.
cities = [
    {"name": "Berlin", "air_quality": airquality_berlin},
    {"name": "Munich", "air_quality": airquality_munich},
    {"name": "Hamburg", "air_quality": airquality_hamburg},
    {"name": "Cologne", "air_quality": airquality_cologne},
]
for city in cities:
    name = city["name"]
    max_b = city["air_quality"]["NO2"].max()
    min_b = city["air_quality"]["NO2"].min()
    print(f"The inter-annual range of NO2-concentration in {name} is: {max_b - min_b}")

A: If it's lazy to make an additional dictionary :)
airquality_berlin = pd.DataFrame({'NO2': [1, 2, 3, 4, 5]})
airquality_munich = pd.DataFrame({'NO2': [11, 12, 13, 14, 15]})
airquality_hamburg = pd.DataFrame({'NO2': [21, 22, 23, 24, 55]})

v = None
for v in locals():
    if v.split('_')[0] == 'airquality':
        print(f"The inter-annual range of NO2-concentration in {v.split('_')[1].capitalize()} is: "
              f"{locals()[v]['NO2'].max() - locals()[v]['NO2'].min()}")

Prints:
The inter-annual range of NO2-concentration in Berlin is: 4
The inter-annual range of NO2-concentration in Munich is: 4
The inter-annual range of NO2-concentration in Hamburg is: 34


text:
Q: Android Sqlite AsyncTask populate ListView Null Pointer I have a problem with populating my ListView with AsyncTask. Normally it work fine but it's extremely slow. So I implemented AsyncTask which should return the values and then the Adapter could use them to display in the ListView.
However if I run this it return nullPointerException on the values.
The both values and datasource are global variables so it should do any harm there. They both work when the Threads are not being used.
Could that be that the thread as it is asynchronous does not have the values created and therefore it goes to nullPointer, when should I be loading the values then?
        MyAsynch myAs = new MyAsynch();
        myAs.execute();

        MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);

   private class MyAsynch extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void...strings) { // run time intensive task in separate thread

            datasource = new ReadingsDataSource(getApplicationContext());
            datasource.open();
            values = datasource.getAllReadings();
            datasource.close();
            return null;
        }
    };

Here is the error:
08-20 12:21:32.107: E/AndroidRuntime(6896): FATAL EXCEPTION: main
08-20 12:21:32.107: E/AndroidRuntime(6896): java.lang.RuntimeException: Unable to instantiate application android.app.Application: java.lang.NullPointerException
08-20 12:21:32.107: E/AndroidRuntime(6896):     at android.app.LoadedApk.makeApplication(LoadedApk.java:482)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3952)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at android.app.ActivityThread.access$1300(ActivityThread.java:128)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at   android.os.Handler.dispatchMessage(Handler.java:99)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at android.os.Looper.loop(Looper.java:137)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at android.app.ActivityThread.main(ActivityThread.java:4514)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at java.lang.reflect.Method.invokeNative(Native Method)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at java.lang.reflect.Method.invoke(Method.java:511)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at dalvik.system.NativeStart.main(Native Method)
08-20 12:21:32.107: E/AndroidRuntime(6896): Caused by: java.lang.NullPointerException
08-20 12:21:32.107: E/AndroidRuntime(6896):     at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:362)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at android.app.LoadedApk.getClassLoader(LoadedApk.java:305)
08-20 12:21:32.107: E/AndroidRuntime(6896):     at android.app.LoadedApk.makeApplication(LoadedApk.java:474)
08-20 12:21:32.107: E/AndroidRuntime(6896):     ... 11 more

A: The reason is because you are trying to access your values when its empty, when you use AsyncTask the code in doInBackground is performed in background and you get call backs.
So your code should be like this
    private class MyAsynch extends AsyncTask<Void, Void, Void>{

    ProgressDialog pd;
    @Override
    protected void onPreExecute() {
     super.onPreExecute();
    pd=ProgressDialog.show(/*you context variable*/,/*Your Title*/,/* Your message while data   is loaded*/);
    }

            @Override
            protected Void doInBackground(Void...strings) { // run time intensive task in separate thread

                datasource = new ReadingsDataSource(getApplicationContext());
                datasource.open();
                values = datasource.getAllReadings();
                datasource.close();
                return null;
            }
        };

    @Override

    protected void onPostExecute(String result) {
   super.onPostExecute(result);
    pd.dismiss();
    // Give the data to you adapter from here,instead of the place where you gave it earlier
      MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
    }
  }


text:
Q: How to add a command to the zsh history from python I am writing a shell wrapper script (term-cheat) in python that can be used to find, collect and execute shell commands. I would love to add the executed commands to the shell history.
I tried several things like the following but did not succeed.
subprocess.Popen(['zsh', '-ic', 'print -s "$1"', '_', command_string])

A: You can append the executed command to the corresponding history file in the home folder of the executing user.
For bash it should be ~/.bash_history zsh may uses another file, but it should also be in the home directory.


text:
Q: android HTTP connection refused, Resetting device wifi fixes it but Good day, I have created an android scheduler for a private company with PHP as its back end. There are already tons of post similar to my problem but nothing quite like the one i have, and i have read that i must not post questions on those particular posts, thus created my own.
The login part of my system works on most cases, but there are times when the connection to the host is refused. Mostly when i leave my android device while debugging the system, running it again shows this error.
Connection to http://xx.xx.xx.xxx refused

I am using a free web hosting site, i have all user permissions on my manifest. As i said, it works 70% of the time. But there are times when i get the above error. Resetting my android device's wifi fixes this error. Is there a better way to fix this error? I am creating this program for a private company after all ... this kind of error, though only appears on rare occasions is not acceptable.
Thank you very much in advance.


text:
Q: Running Gretty project with Gradle Docker container Is it possible to run Gretty projects in Docker Gradle container?
Normally the Gretty task tomcatRun starts Tomcat app server and you can browse the app at http://localhost:8080/app-name. With Docker Gradle image the task is successfully started but the container is terminated immediately after that.
Steps for reproducing the issue:

*

*Install Docker.

*Clone https://github.com/haba713/hello_gretty.

*cd hello_gretty

*Install Gradle wrapper:
docker run --rm -u gradle -v "$PWD":/home/gradle/project -w /home/gradle/project gradle gradle wrapper

*Run the task tomcatRun: ./gradlew tomcatRun

*Browse http://localhost:8080/hello_gretty.

*Terminate the task by pressing enter in terminal.

*Run task tomcatRun with Gradle Docker image:
docker run --rm -u gradle -p 8080:8080 -v "$PWD":/home/gradle/project -w /home/gradle/project gradle gradle tomcatRun

*The task tomcatRun is started (takes some time) but for some reason the
container terminates immediately after that. Maybe the task was completed
without pressing any key.

I also created a Docker issue about the problem.

A: Adding -t or --tty to docker command keeps Tomcat running. Also add -i or --interactive if you want to stop Tomcat with "any key" as Gretty says: "Press any key to stop the server."
docker run --rm -u gradle -it -p 8080:8080 -v "$PWD":/home/gradle/project -w /home/gradle/project gradle gradle tomcatRun
Thank you David Maze for helping.


text:
Q: How to make the script stop at specified time? I have 100 list of software.
I have this code:
doubleClick("1380765362298.png")
wait(0.01)
#mouseDown(Button.LEFT)
#mouseUp(Button.LEFT)
while exists("1380774111845.png",10):
    click("1380774111845.png")
    wait(0.01)
    mouseDown(Button.LEFT)
    mouseUp(Button.LEFT)
    wait(2)
#except:
    #pass
    try:
        click("1380765740907.png")
        wait(3)
        waitVanish("1380772439126.png",FOREVER)
    except:
        pass
    try:
        click("1380769537610.png")
        wait(4)

    except:
        pass
    try:
        click("1380772563891.png")
        wait(2)
    except:
        pass
    try:
        type(Key.DELETE)
        wait(2)
    except:
        pass
    try:
        click("1380774317204.png")
        wait(1)
    except:
        pass
else:
    pass

In this code, I tried to make it loop until 10 but it wont work.
It will keep looping until all software have been run.
So how can I make it loop until 10 only?

A: Your while loop will execute as long as 1380774111845.png is on screen. If you only want it to execute 10 times, replace the while with a for loop:
for x in range(10):
   if not exists("1380774111845.png",10):
       break

Also, remove the final else/pass as it's unnecessary.


text:
Q: How to Edit email alerts Templates from Issue Tracker? Hi
I want to edit the email alerts format sent from a Issue Tracker.
I need to know which files I have to edit to customize the email alerts?
I use WSS 3.0
-Saumil

A: I recommend you read this first: Customizing Alert Notifications and Alert Templates in Windows SharePoint Services 3.0
SPAlertTemplateType.GenericList
The first alert template in Alerttemplates.xml. GenericList is used unless there is a match to one of other event types.
SPAlertTemplateType.DocumentLibrary
 Notification of changes in document libraries
SPAlertTemplateType.Survey
 Notification of changes in surveys
SPAlertTemplateType.Links
 Notification of changes in links
SPAlertTemplateType.Announcements
 Notification of changes in announcements
SPAlertTemplateType.Contacts
 Notification of changes in contacts
SPAlertTemplateType.Events
 Notification of changes in events
SPAlertTemplateType.Tasks
 Notification of changes in tasks
SPAlertTemplateType.DiscussionBoard
 Notification of changes in discussion boards
SPAlertTemplateType.PictureLibrary
 Notification of changes in picture libraries
SPAlertTemplateType.XMLForm
 Notification of changes in XML form
SPAlertTemplateType.DataConnectionLibrary
 Notification of changes in data connection libraries
SPAlertTemplateType.AssignedtoNotification
 Assigned to task / issue list notifications


text:
Q: Is it possible to upgrade angularjs atttribute directives to use in angular 4? I've been able to upgrade an angularjs element directive to be used in angular 4.
Here's a sample code:
[myScores.js]
angular.module('app.components.directives.myScores', [])
.directive('myScores', function() {
  return {
    scope: {
      score: '=',
    },
    template: '
>>> Your score is {{score}} <<<',
    link: function(scope) {
      console.log("in myScores", scope)
    }
  };
});

[myScores.ts]
import { Directive, ElementRef, Injector, Input, Output, EventEmitter } from '@angular/core';
import { UpgradeComponent } from '@angular/upgrade/static';

@Directive({
  selector: 'my-scores'
})
export class MyScoresDirective extends UpgradeComponent {
  @Input() score: number;

  constructor(elementRef: ElementRef, injector: Injector) {
    super('myScores', elementRef, injector);
  }
}

Notice I'm using UpgradeComponent to upgrade the myScores element directive.
I've tried the same on an attribute directive but got an error.  Is there a way to upgrade an attribute directive?
Here's my attempt of upgrading an attribute directive:
[makeGreen.js]
angular.module('app.components.directives.makeGreen', [])
.directive('makeGreen', function() {
  return {
    restrict: 'A',
    link: function(scope, element) {
      console.log("in makeGreen", scope)
      console.log("element", element)
      element.css('color', 'green');
    }
  };
});

[makeGreen.ts]
import { Directive, ElementRef, Injector, Input, Output, EventEmitter } from '@angular/core';
import { UpgradeComponent } from '@angular/upgrade/static';

@Directive({
  selector: '[makeGreen]'
})
export class MakeGreenDirective extends UpgradeComponent {
  @Input() count: number;
  @Output() clicked: EventEmitter<number>;

  constructor(elementRef: ElementRef, injector: Injector) {
    console.log("elementRef", elementRef.nativeElement)
    super('makeGreen', elementRef, injector);
  }
}

I get an error when loading a page that has something like:

Text should be green

I got this error:
Error: Directive 'makeGreen' is not a component, it is missing template.

A: A Attribute directive can totally have the Input property which can be passed to it from the tag where it's used : For ex:

Highlighted in orange

Also make sure your appModule/SharedModule imports it.

So the problem i see is with the way you are defining your structural
  directive. A structural directive doesn't have any template structure
  attached to it. It applies to any html tag where it's used.

For you case, i see you are extending the directive with Component class which is not acceptable to a Attribute directive :--
MakeGreenDirective extends UpgradeComponent {

You should keep the Attribute Directive separate from any Component. For Ex:
  import { Directive, ElementRef, Injector, Input, Output, EventEmitter } from
  '@angular/core';

  @Directive({
    selector: '[highlightThis]'
   })

 export class HighLightThisDirective {
 @Input() count: number;
 @Input() highlightColor: string;
 @Output() clicked: EventEmitter<number>;

 constructor(private elementRef: ElementRef, injector: Injector) {  }

 ngOnInit(): void {
   this.decorateMyTag();
 }

 private decorateMyTag(): void {
   console.log("highlightColor", this.highlightColor);
   this.elementRef.nativeElement.style.backgroundColor = this.highlightColor;
  }
}


text:
Q: AttributeError at /addtowatchlist/5: 'QuerySet' object has no attribute 'listings' Within my app, I'm allowing any given user to add an auction listing to their watch list, but no matter what I have tried, it does not seem to work and I keep getting the error in the title. I am simply trying to access the user thats making the request and adding the listing to their watchlist and redirecting them to the main page.
views.py
from .models import *

def add_to_watchlist(request, listing_id):

    listing = Listing.objects.get(id=listing_id)
    # Retrieving the user watchlist (where it always fails)
    watchlist = PersonalWatchList.objects.filter(user=request.user)

    # Fails here too
    if (watchlist.listings.all() == None) or (listing not in watchlist.listings.all()):
        watchlist.listings.add(listing)
        watchlist.save()
    else:
        messages.error(request, "Listing is already in your Watchlist.")
        return redirect(reverse('index'))

    messages.success(request, "Listing added to your Watchlist.")
    return redirect(reverse('index'))

models.py
class PersonalWatchList(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    listings = models.ManyToManyField(Listing, blank=True)

    def __str__(self):
        return f"Watchlist for {self.user}"

urls.py
from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("create", views.createListing, name="create"),
    path("view/<str:listing_title>", views.view, name="view"),
    path("addtowatchlist/<int:listing_id>", views.add_to_watchlist, name="add_to_watchlist")
]

Section of template used to add listing to watchlist

View

Watchlist

I have tried changing my logic around using try and except, but it still results in a very similar error. In my urls.py I have tried changing the path names to avoid them from overlapping, as the "view" and "add_*to_*watchlist" were similar before, but that change still has not worked. Before, in

watchlist = PersonalWatchList.objects.filter(user=request.user)

I used get() instead, and that wasn't working either. Any tips would be greatly appreciated!
Edit:
When I add listings to a given users watchlist through django admin, that works just fine, which I really don't understand how, but through the server itself it fails

A: To retrieve an individual user's watchlist, use get instead of filter:
watchlist = PersonalWatchList.objects.get(user=request.user)

Using the filter() method is returning a QuerySet (Multiple objects) as opposed to the single unique one you want.
The other issue is in your model definition. To use the default user class as a foreign key, you need to use
turning this:
user = models.ForeignKey(User, on_delete=models.CASCADE)

into this:
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Try this and comment your results.

A: I essentially had to change up my logic, as I came to understand that the reason this error was being thrown was because the User did not exist yet in the PersonalWatchList Model. Here is the updated workaround.
views.py updated
def add_to_watchlist(request, listing_id):
    user = request.user

    # Getting the listing that was clicked
    listing = Listing.objects.get(id=listing_id)

    # Retrieving the user watchlist (if it exists)
    try:
        watchlist_exists = PersonalWatchList.objects.get(user=request.user)
    except:
        watchlist_exists = None

    # If there isn't one for this user, make one
    if watchlist_exists == None:
        PersonalWatchList.objects.create(user=user)

    # Access that watchlist
    watchlist = PersonalWatchList.objects.get(user=user)

    # Comparing the listings already present in their watchlist to the one that was hit
    if (listing not in watchlist.listings.all()):
        watchlist.listings.add(listing)
        watchlist.save()
    else:
        messages.error(request, "Listing is already in your Watchlist.")
        return redirect(reverse('index'))

    messages.success(request, f"'{listing}' added to your Watchlist.")
    return redirect(reverse('index'))


text:
Q: Create and set the value of a twig variable, using index.loop in the variable name I need to define a twig variable name that can include an index.loop value within the variable name, so that I can later call this in another loop.
What I'm trying to do is something like:
{% for x in x.y.z %}
{% set myVar~index.loop = aValue %}
{% endfor %}

Later, I would be able to call:
{% if myVar2 == aValue %}
{{ display some stuff }}
{% endif %}

My problem is that I can't work out the correct syntax to define the variable (myVar~index.loop).
Any suggestions, greatly appreciated.
Thanks

A: There are two issues you need to address here:

*

*You would need to extend twig in order to create dynamic variables

*The special variable _context is not sent (directly) towards a loop, but is being stored in _context['_parent']

extending twig
class MyTwigExtension implements \Twig\Extension\ExtensionInterface {
    /**
     * Returns the token parser instances to add to the existing list.
     *
     * @return \Twig\TokenParser\TokenParserInterface[]
     */
    public function getTokenParsers() {
        return [];
    }

    /**
     * Returns the node visitor instances to add to the existing list.
     *
     * @return \Twig\NodeVisitor\NodeVisitorInterface[]
     */
    public function getNodeVisitors() {
        return [];
    }

    /**
     * Returns a list of filters to add to the existing list.
     *
     * @return \Twig\TwigFilter[]
     */
    public function getFilters() {
        return [];
    }

    /**
     * Returns a list of tests to add to the existing list.
     *
     * @return \Twig\TwigTest[]
     */
    public function getTests() {
        return [];
    }

    /**
     * Returns a list of functions to add to the existing list.
     *
     * @return \Twig\TwigFunction[]
     */
    public function getFunctions() {
        return [
            new \Twig\TwigFunction('set', [ $this, 'setValue'], [ 'needs_context' => true,]),
        ];
    }

    /**
     * Returns a list of operators to add to the existing list.
     *
     * @return array<array> First array of unary operators, second array of binary operators
     */
    public function getOperators() {
        return [];
    }

    /**
    * Set reference to $context so you can modify existing values
    * Test if key _parent is set. If true this means the function was called inside a loop
    **/
    public function setValue(&$context, $key, $value) {
        if (isset($context['_parent'])) $context['_parent'][$key] = $value;
        $context[$key] = $value;
    }
}

add extension to twig
$twig->addExtension(new \MyTwigExtension());

Now you can use the function set inside a template, e.g.
{% set foo = 'bar' %}
{% do set('my_var_'~foo, 'foo') %}
{{ my_var_bar }} {# output: foo #}

or inside a loop
{% for i in 1..10 %}
    {% do set ('my_var_'~i, i) %}
{% endfor %}

{{ my_var_6 }} {# output: 6 #}

As I said, the special variable _context, is not send directly to the function, even with needs_context set true. Twig copies the current contents of _context inside _parent so that the loop get it's own private scope of variables and you can't overwrite any original value from the _context


text:
Q: Days between dates in Azure DevOps work items by query What I would like to do
I am an Azure DevOps Services user.
Are there any ways to calculate the duration between dates in work items by Azure Boards query?
Or, are there any fields of days between dates?
For example, I would like to display a list of work items which duration between Activated Date and Created Date exceeds 5 days.
What I tried
I tried Activated Date > [Field] Created Date + 5 but result is
TF51005: The query references a field that does not exist. The error is caused by Created Date + 5.
I wonder if only supported macros like @Today or @StartOfDay are able to be used for calculation in query editor.
I read the following official references but I could not reach a solution.

*

*Query by date or current iteration

*Query fields, operators, and macros

*Lead time and cycle time widgets
If there are no solutions by query, another ideas are welcome.

A: This cannot be done by query. You will need to use rest api as workaround. But it is complicated and might not achieve the same effect as Query.
1, First you can use work item wiql api to query those items that [Microsoft.VSTS.Common.ActivatedDate] > [System.CreatedDate] to get the ids of workitems
2, Then you can use work item list api to list the fields details of those work items queried by above step.
3, Last use powershell scripts to filter those work items whose duration between Activated Date and Created Date exceeds 5 days
Please check below example in powershell scripts:

For {PAT} please check here to get a Personal Access Token to Authenticate below API calling

# query those items that [Microsoft.VSTS.Common.ActivatedDate] > [System.CreatedDate] and  get the ids of workitems
$qurl =  "https://dev.azure.com/{org}/{proj}/_apis/wit/wiql?api-version=5.1"

$WIQL_query = "Select [System.Id], [System.Title], [System.State],[Microsoft.VSTS.Common.ActivatedDate],[System.CreatedDate] From WorkItems Where [Microsoft.VSTS.Common.ActivatedDate] > [System.CreatedDate]"
$body = @{ query = $WIQL_query }
$bodyJson=@($body) | ConvertTo-Json

$pat = {PAT}

$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))

$result = Invoke-RestMethod -Uri $qurl -Headers @{authorization = "Basic $base64AuthInfo"} -Method post -ContentType "application/json" -Body $bodyJson

# GET THE WORKITEM IDS
$ids = $result.workItems | select id | foreach{ $_.id }
$id= '{0}' -f ($ids -join ",")

# use work item list api to list the fields details of those work items
$url = "https://dev.azure.com/{ORG}/{PROJ}/_apis/wit/workitems?ids=$($id)&api-version=5.1"

$result1 = Invoke-RestMethod -Uri $url -Headers @{authorization = "Basic $base64AuthInfo"} -Method get

# Filter those workitems whose duration between Activated Date and Created Date exceeds 5 days.
$result1.value.fields | where {[datetime]$_.'Microsoft.VSTS.Common.ActivatedDate' -gt ([datetime]$_.'System.CreatedDate').AddDays(5)}

Hope above helps!


text:
Q: How to generate a random string in MongoDB that is not in a collection? I know how to generate such a random string in MySQL:
select random_strings.random_string as pin
from (
  select lpad(conv(floor(rand() * pow(36, 6)), 10, 36), 6, 0) as random_string
) as random_strings
where random_strings.random_string not in (
  select pin
  from my_table
  where pin is not null
)
limit 1;

but I need to do so using MongoDB. How can I achieve that ?


text:
Q: What is the expectation value of the number operator when the vacuum has a VEV? The number operator N applied to a field whose vacuum has zero VEV gives $N|0>=0$. What if we apply it to the Higgs field?
The background of this question is that in popular scientific accounts, the Higgs field is sometimes described as a 'sea' of particles. I would like to clarify the meaning of this, and what is the physical interpretation of a non-zero VEV.

A: The vacuum with $\langle 0|h|0\rangle=v$ has a shifted expectation value but it is given by a similar Gaussian as the would-be $h=0$ vacuum. To shift expectation values in this way, you have to construct the so-called "coherent state". The $h=v$ vacuum is a coherent state, too.
However, this coherent state still preserves the space and time translational symmetries, so only $p^\mu=0$ physical Higgs bosons are added to this condensate. The physical vacuum may be imagined as a coherent state similar to this one:
$$ |0\rangle = \exp(C\cdot a^\dagger_{p=0}) |h=0\rangle $$
Much like all coherent states in quantum physics (harmonic oscillators of any dimension), it refuses to be an eigenstate of the number operator $N$, of course. If you Taylor-expand the exponentials, you will see that the coherent state is a linear superposition of states with different values of $N$ – with different powers of the creation operator.
However, you may still calculate the expectation value of $N$. You will find out that because $a^\dagger,a$ are normalized to the 3D delta-function, the expectation value of $N$ will scale proportionally to the three-dimensional volume of the region. So $\langle N \rangle \sim V$. To calculate the coefficient, one needs to do some maths and the result won't be too meaningful anyway because the $h=0$ state isn't an energy eigenstate for the physical choice of the potential, anyway. And even if you allowed different potentials to be used for the two vacuum states, the two Gaussian "wave functional" will probably have a different width as well so that one will be not just coherent but "squeezed" state constructed out of the other.
But one may still "morally" assign an order-of-magnitude estimate to the coefficient. By dimensional analysis, a power of the electroweak scale is the only dimensionful constant that may enter. Therefore,
$$\langle N \rangle = K\cdot V\cdot m_{ew}^3 $$
where $K$ is a numerical constant of order one and $m_{ew}$ is of order of the Higgs vev $v$ or Higgs mass $m_h$. There is roughly one Higgs boson in the condensate per "electroweak volume"; the latter is roughly a cube with side $10^{-18}$ meters.
One must emphasize that the coherent state construction above may be expanded in terms of real particles. We are talking about states in the Hilbert space so of course all of them belong to the "Fock space" which is only made out of real particles. It makes no sense to say that we're adding "virtual particles". Virtual particles are just additions to a particular "process" (a Feynman diagram), not additions to a state in the Hilbert space! And they're short-lived while the Higgs condensate is static and infinitely long-lived.
The addition of the Higgs condensate that shifts the vev is equivalent to adding a new "linear" vertex to to the Feynman rules of the original theory. This linear vertex only has 1 external leg. It may be attached by Higgs propagators to other vertices, e.g. the cubic Yukawa vertex, and this propagator looks like an external leg and produces mass terms for the fermions (in the example of the Yukawa vertex) out of the Yukawa cubic vertex. Similarly for other interactions.

A: If a field $\phi(x)$ has a nonzero VEV $v$, the field whose Fourier components define the creation and annihilation operators is $\phi(x)-v$, which has a zero VEV, and again $N|0\rangle=0$.
An interpretation in terms of the original $\phi$ is highly ill-defined and cutoff-dependent, and cannot be given a sensible physical meaning, although formally, it looks like a sea of indefinitely many virtual particles.


text:
Q: Excel Formula that Match the Year and Quarter then Paste the Result I have been using a Microsoft Excel formula that matches the Year and Quarter in Sheet1 then copies the required cell value and then paste that value into Sheet2 COl"B".
My formula is not dynamic it just works for year 2020 not for further years available in Sheet1 that are 2021 and 2020
I have tried to create something that works for my but could not. I have attached a Google Sheet please have look into it.
Your help will be highly appreciated.
https://docs.google.com/spreadsheets/d/1VgFn2Rpw3PAG_pBg1-YWfTexGuHHzzqiGBiUQDbpwLE/edit#gid=758402044

A: In C14 of Sheet2 try:
=IF(MOD(ROW(),3)=0,LOOKUP(2,1/((Sheet1!B$2:B$15=C$1+INT(COUNT(C$13:C13)/4))*(Sheet1!C$2:C$15=MOD(COUNT(C$13:C13),4)+1)),Sheet1!E$2:E$15),"")


text:
Q: div left and div right not floating side by side in container here's jsFiddle
#wrapper {
    margin:1px;
    height:auto;
    width:auto;
    float:left;
    clear:both
}
#wrapperR {
    margin:1px;
    height:auto;
    width:auto;
    float:right;
    clear:both;
}

in my page it looks like this
  L
   R

but i want it to look like    LR
I would like for the  and all its content to remain left while
  remains right and side by side.
I've added clear:both; to both divs, i've even created a .clear{clear:both;} and i've adjusted the widths and paddings and margins, but I still can't float them side by side.
I'm wondering what I am over looking.
Thanks!

A: Remove clear:both from:
#wrapperR {
margin: 1px;
height: auto;
width: auto;
float: right;
clear: both; /* REMOVE THIS LINE*/
}

jsFiddle example
The clear:both rule here means that this element will be placed below any floated elements before it.

A: errrr. surely clear:both is your problem? that will stop them from being side to side.
also try displaying them inline-block:
display:inline-block

A: Place these mod on your css:
#wrapper{margin:1px; height:auto; width:auto;float:left;}
#wrapperR{margin:1px; height:auto; width:auto; float:right; }
#column_l {
    width: 60%;
    margin: 0;
    padding: 0;
    background-color: transparent;
    float:left;
}
#column_r {
    width: 40%;
    margin: 0;
    margin-right:5px;
    float: left;
    background-color: transparent;
    position: absolute;
    left:60%;

}

Removing clear:both from wrapper and column_[l|r]
If you want your right column more higher ("attached to the menu"), you must play with the attribute top: -X px

A: #wrapper p {
   position : relative;
   float: left;
}

And adjust your text to have place for floating


text:
Q: Why do at least half of all random orderings generate a binary space partition of size $n+4n\ln n$ in the random binary space partition algorithm? Let $S$ be a finite ordered set of non-intersecting finite line segments in the plane. Let's randomly shuffle the elements of $S$ such that each possible permutation of those elements has equal probability of appearance.
Suppose we choose the first element $s_1$ of $S$, split the plane by the infinite extension $\ell=\ell(s_1)$ (called a splitting line) of $s_1$ into a half-plane $\ell^+$ above and $\ell^-$ below $\ell$ and recursively continue this process for both of the subsets of $S$ induced by $\ell^+$ and $\ell^-$.
The splitting lines may cut segments into fragments. The process described above continues until there is only one fragment in the interior of each region induced by the surrounding splitting lines. The result is called binary space partition. I hope the following figure will illustrate the result of this process:
$\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;$

We can show that $$\Pr\left[t\text{ is cut when }\ell(s)\text{ is added as the next splitting line}\right]\le\frac 1{\operatorname{dist}_st+2}$$ for all $s\in S$ and $t\in S\setminus\left\{s\right\}$ where $$\operatorname{dist}_st:=\begin{cases}\text{# segments }u\in S\text{ between }s\text{ and }t\text{ with }\ell(s)\cap u\ne\emptyset&\text{, if }\ell(s)\cap t\ne\emptyset\\\infty&\text{, otherwise}\end{cases}$$ for $s\in S$ and $t\in S\setminus\left\{s\right\}$.

$\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;$

Thus, $$\operatorname E\left[\text{# cuts generated by }s\right]\le\sum_{t\in S\setminus\left\{s\right\}}\frac 1{\operatorname{dist}_st+2}\le 2\ln n$$ for all $s\in S$ and the expected total number of generated fragments is bounded by $n+2n\ln n$ (since we start with $n$ segments).

Question: Why can we conclude that

*

*a binary space partition of size ($:=$ number of generated fragments) $n+2n\ln n$ exists?

*at least half of all random orderings lead to a binary space partition of size $n+4n\ln n$?

Both statements can be found in Computational Geometry: Algorithms and Applications by Mark de Berg, below the proof of Lemma 12.1 and I absolutely don't understand why they are true.

A: The statements in the book are correct if you interpret "of size" to mean "of size at most". Taken literally, they are clearly false.