SYMFONY2 Sluggable minimal configuration

Question: I installed StofDoctrineExtensionsBundle identical with that link.
In contrast, page renders very slowly, because about 5 minutes. I you need only  sluggable funcionality in the user entity (FOSUSERBUNDLE). I think it schould work faster without some elements.
What is the minimum configuration to run only sluggable with this package. Are all mappings are needed (watch link)?
I need config.yml example.
EDIT
After adding listener my config.yml looks:
    ...
    orm:
        default_entity_manager: default
        auto_generate_proxy_classes: "%kernel.debug%"
        entity_managers:
            default:
                connection: default
                mappings:
                    AppBundle:  ~
                    gedmo_translatable:
                        type: annotation
                        prefix: Gedmo\Translatable\Entity
                        dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity"
                        alias: GedmoTranslatable # (optional) it will default to the name set for the mapping
                        is_bundle: false
                    gedmo_translator:
                        type: annotation
                        prefix: Gedmo\Translator\Entity
                        dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translator/Entity"
                        alias: GedmoTranslator # (optional) it will default to the name set for the mapping
                        is_bundle: false
                    gedmo_loggable:
                        type: annotation
                        prefix: Gedmo\Loggable\Entity
                        dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Loggable/Entity"
                        alias: GedmoLoggable # (optional) it will default to the name set for the mappingmapping
                        is_bundle: false
                    gedmo_tree:
                        type: annotation
                        prefix: Gedmo\Tree\Entity
                        dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity"
                        alias: GedmoTree # (optional) it will default to the name set for the mapping
                        is_bundle: false

...
stof_doctrine_extensions:
    class:
        sluggable:      ~
...

My Entity with slugg:
namespace AppBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;

/**
 * Profile
 *
 * @ORM\Table(name="profile")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ProfileRepository")
 */
class Profile
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=150, nullable=true)
     */
    private $name;
     /**
     * @Gedmo\Slug(fields={"title", "name"})
     * @ORM\Column(length=128, unique=true)
     */
    private $slug;
    /**
     * @var string
     *
     * @ORM\Column(name="city", type="string", length=150, nullable=true)
     */
    private $city;

    /**
     * @var string
     *
     * @ORM\Column(name="voivodeship", type="string", length=50, nullable=true)
     */
    private $voivodeship;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    private $description;

    /**
     * @var string
     *
     * @ORM\Column(name="category", type="string", length=100, nullable=true)
     */
    private $category;

     /**
     *
     * @ORM\OneToOne(targetEntity="User", cascade={"persist"})
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=true)
     */
    protected $user;
    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Profile
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set city
     *
     * @param string $city
     *
     * @return Profile
     */
    public function setCity($city)
    {
        $this->city = $city;

        return $this;
    }

    /**
     * Get city
     *
     * @return string
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * Set voivodeship
     *
     * @param string $voivodeship
     *
     * @return Profile
     */
    public function setVoivodeship($voivodeship)
    {
        $this->voivodeship = $voivodeship;

        return $this;
    }

    /**
     * Get voivodeship
     *
     * @return string
     */
    public function getVoivodeship()
    {
        return $this->voivodeship;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Profile
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set category
     *
     * @param string $category
     *
     * @return Profile
     */
    public function setCategory($category)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * Get category
     *
     * @return string
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * Set user
     *
     * @param \AppBundle\Entity\User $user
     *
     * @return Profile
     */
    public function setUser(\AppBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \AppBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
     /**
     * Get slug
     *
     * @return string
     */
     public function getSlug()
    {
        return $this->slug;
    }
}

Now site did not generate. Refreshed database and nothing helped
Answer: You only need to activate the sluggable listener :
    # app/config/config.yml
stof_doctrine_extensions:
    class:
        sluggable:      ~

And create your slug property :
<?php
namespace Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="articles")
 * @ORM\Entity
 */
class Entity
{
    ...

    /**
     * @Gedmo\Slug(fields={"username"})
     * @ORM\Column(length=128, unique=true)
     */
    private $slug;

    ...
}

Comment: After adding listener nothing changed. I completed the question of my files
Comment: You only need what I wrote. Please remove every listener in mappings ...
Comment: And don't forget to remove all not wanted SQL tables that was created with your wrong configuration (normaly 4).
Answer: I have modified listener definition from Alsatian's answer and it's working now.
# app/config/config.yml
stof_doctrine_extensions:
default_locale: en
orm:
    default:
        tree: false
        timestampable: false
        sluggable: true
        translatable: false


How to separate text into two different parts (positive/negative) without hardcoded rules?

Question: The task is simply explainable but I imagine very hard. I have a large (1000+) recordings from a questionnaire in which people are asked to describe some of their good and bad personality traits and also what traits they would like to gain/work on.
The problem is that they are given one answer box for this. Some people start with listing their good, some with their bad ones, some list only their bad, some list only their good.
When I read them I can separately them very easily, but because there is not much structure I am having trouble with building a simple rule based algorithm.
Three examples:
One thing that I would to improve is my social ability. I find it hard approaching people and starting a conversation with a stranger. Also I am quite lazy sometimes. One thing that I am very proud of is my perseverance as well as my loyalty to my pets.

I am not a person with great perserverance, this is something I must work on. Sometimes I can be very lazy and I do not study the subject enough. I have trouble getting started with learning and then I keep pushing it forward, until I get into a time crunch and then I get stressed out and the quality of my work suffers. One thing that I am happy with is my ability to connect with people and I consider myself a very social person.

I am less satisfied with how much of a perfectionist I am. This can sometimes get in the way during work assignments because they will then take me too long. Besides that, I am a good listener and am empathetic with people.

I have written an algorhitm that basically checks for words such as improve, satisfied, change and then classify what follows either as negative or positive until a word is met that negates this and registers everything as positive from that point on.
However, things still keep escaping or being misclassified. Negation is part of the problem as well as people who do not use words such as improve, satisfied but just write down some good and then some bad personality traits such as this:
I work very hard and make a lot of progress when I zoom in on something. I am a family man and love my partner.

I think that I sometimes can be too stubborn for my own good. I feel that my perseverance is not what it used to be.

These things then do not trigger anything on the algorithm (which is currently about 22% of all cases). All in all, I'm hoping for a better approach. I could manually tag a few hundred and then have a model extract the rest but I'm not sure if this is a good idea and where even to begin. Does anyone here have any recommendations?
Cheers! Appreciate all help because I am stuck in the mud :p :(
This will be part of a pipeline so doing it manually is not an option. One obvious option is to separate the good and bad parts from the questionnaire but for this task it is also not an option. I
Comment: I suggest to sit on it for a day and do it by hand, or get an intern to do it.
Answer: This is an NLP problem, and while there has been much progress in recent years, those problems are still considered quite hard.
In particular, your task sounds like sentiment analysis. The basic idea is to separate the text into sentences and then assign a sentiment (e.g. "positive" or "negative") to each of them.
Furthermore, your approach seems to be a rule-based method. There are already a couple of rule-based methods developed for this task. You might want to look into those. To start, see here or here.
But you could also think about applying some sentiment analysis machine learning model. This would be a supervised learning problem and for training, you would need many sentences that are already labeled with "positive" and "negative".
And, if you want to use the state-of-the-art deep learning models, you will need a lot of such labeled data. This might be a problem in your situation.
Fortunately, this is a very common problem, so you might benefit from some pre-trained sentiment models. Those are models that have been trained on large datasets and only need some fine-tuning with your data to adapt them to your problem. And for fine-tuning you don't need much data, so you might want to give it a try.
I think a good start for learning about sentiment analysis with deep neural networks is this post. See also here, or here.
If the deep learning approach is not for you, maybe because of the complexity and the computational costs (buying GPU hardware or cloud computing resources), you could still go for training an ML model, but a classic one. A useful library would be the python NLTK library.
Comment: Hi Frank! Thanks for the great response :) I hadn't thought about splitting everything up in individual sentences and then classifying these sentences. That's a good idea for an alternative approach. A problem with using a pre-trained model is that the responses are not in English but in dutch and I have trouble finding pretrained models for the dutch language unfortunately.


Como agrupar dois índices numa tupla?

Question: Quero agrupar dois índices que são recebidos de posições que são resultados de if's/elif's
def MakeListOfFreeFields(board):
    n_rows = len(board)
    n_cols = len(board[0])
    tfields = ()

    for row in range(n_rows):
        for column in range(n_cols):
            if board[row][column] == '1':
                tfields += ([row],[column])
            elif board[row][column] == '2':
                tfields += ([row],[column])
            elif board[row][column] == '3':
                tfields += ([row],[column])
            elif board[row][column] == '4':
                tfields += ([row],[column])
            elif board[row][column] == '5':
                tfields += ([row],[column])
            elif board[row][column] == '6':
                tfields += ([row],[column])
            elif board[row][column] == '7':
                tfields += ([row],[column])
            elif board[row][column] == '8':
                tfields += ([row],[column])
            elif board[row][column] == '9':
                tfields += ([row],[column])
    print(tfields)

O resultado desse print é:
([0], [0], [0], [1], [0], [2], [1], [0], [1], [1], [1], [2], [2], [0], [2], [1], [2], [2])

E eu gostaria que fosse:
([0][0], [0][1], [0][2], [1][0], [1][1], [1][2], [2][0], [2][1], [2][2])

Answer: Se o seu intento é recuperar uma lista de tuplas que representam as coordenadas do tabuleiro que nao estão preenchidas, segue um código equivalente capaz de solucionar o seu problema:
def MakeListOfFreeFields(board):
    ret = []
    for x, row in enumerate(board):
        for y, col in enumerate(row):
            if not col.isdigit():
                ret.append((x, y))
    return ret

tabuleiro = [
    ['1',' ','3'],
    [' ','5',' '],
    ['7',' ','9']
]

saida = MakeListOfFreeFields(tabuleiro)

print(saida)

Saída:
[(0, 1), (1, 0), (1, 2), (2, 1)]

Simplificando o seu código usando uma função geradora:
def MakeListOfFreeFields(board):
    for x, row in enumerate(board):
        for y, col in enumerate(row):
            if not col.isdigit():
                yield (x, y)

tabuleiro = [
    ['1',' ','3'],
    [' ','5',' '],
    ['7',' ','9']
]

saida = list(MakeListOfFreeFields(tabuleiro))

print(saida)

Saída:
[(0, 1), (1, 0), (1, 2), (2, 1)]

A saída que você está esperando representa um tabuleiro vazio, veja só:
def MakeListOfFreeFields(board):
    for x, row in enumerate(board):
        for y, col in enumerate(row):
            if not col.isdigit():
                yield (x, y)

tabuleiro = [
    [' ',' ',' '],
    [' ',' ',' '],
    [' ',' ',' ']
]

saida = list(MakeListOfFreeFields(tabuleiro))

print(saida)

Saída:
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Como agrupar dois índices numa tupla?


Change data type varchar to timestamp along with null values in PostgreSQL

Question: Change data type varchar to timestamp along with null values in PostgreSQL
I have a column with empty rows and few with timestamp rows. How to convert that into timestamp data type in PostgreSQL?
Comment: Do you need to alter that column's data type to timestamp ?
Comment: show a sample data in that column,You need to provide more info.
Comment: what did you try? did you get any errors?
Answer: You need a USING clause to turn the empty strings into null.
ALTER TABLE ...
  ALTER COLUMN mycol
    TYPE timestamp
    USING (...conversion expression...)

Without seeing the input data it's hard to say exactly what that expression must be, but it probably involves nullif or case expressions and the to_timestamp function and/or a CAST to timestamp.


Windows Command - Delayed Expansion Syntax to Echo The VALUE of a Variable That Contains Another Number Variable

Question: I am trying to echo the VALUE of a variable whose name contains another variable ($project!$project_number!_control) while using delayed expansion. I can't figure out the syntax to do this.  Here's the code:
@echo off
setlocal enabledelayedexpansion
set $loop_counter=
for %%g in (1,2,3,4,5,6,7,8) do (
    set /a $loop_counter+=1
    if !$loop_counter! gtr 4 (
        echo.
        rem echo $loop_counter = !$loop_counter!
        set /a $project_number=!$loop_counter!-4
        echo $project_number = !$project_number!
        set $project!$project_number!_control=Project Description # !$loop_counter!
        echo $project!$project_number!_control = !$project!$project_number!_control!
    )
)
echo.
pause
echo.
set
echo.
pause

The line of code I'm having the problem with is the last line in the for loop:
echo $project!$project_number!_control = !$project!$project_number!_control!

Specifically, it's the code to the right of the equal sign that echoes the VALUE of the $project!$project_number!_control variable that I'm having trouble with.  The set command (that is run after the pause command in the code above) clearly shows that the values "Project Description #5," "Project Description #6," "Project Description #7," and "Project Description #8" were assigned correctly to the corresponding project1_control, project2_control, project3_control, and project4_control, variables.
Can someone please tell me what syntax to use to display the VALUE of the $project!$project_number!_control variable?
Thanks In Advance For The Help!
Answer: The solution to this problem is that the $project!$project_number!_control variable must undergo double expansion in order to return its value.  Exclamation marks cannot be used more than once with a variable when delayed expansion is enabled as I had done in my original code, below:
!$project!$project_number!_control!

Instead or the exclamation marks placed at the beginning and end of the variable as shown above, double percent signs (%%) should be placed at the beginning and end of the variable as follows:
%%$project!$project_number!_control%%

When delayed expansion takes place this statement will expand to:
%$project!$project_number!_control%

As can be seen in the expanded variable code above, the VALUE of the variable is still not returned.  To do that a SECOND expansion must take place.  To execute a second variable expansion, the call statement is placed in front of the echo statement at the beginning of the last line of code in the for loop.  The corrected last line of code in the for loop is:
call echo $project!$project_number!_control = %%$project!$project_number!_control%%

When the code executes with the corrected line of code everything works as expected.  The entire corrected code listing is now:
@echo off
setlocal enabledelayedexpansion
set $loop_counter=
for %%g in (1,2,3,4,5,6,7,8) do (
    set /a $loop_counter+=1
    if !$loop_counter! gtr 4 (
        echo.
        rem echo $loop_counter = !$loop_counter!
        set /a $project_number=!$loop_counter!-4
        echo $project_number = !$project_number!
        set $project!$project_number!_control=Project Description # !$loop_counter!
        call echo $project!$project_number!_control = %%$project!$project_number!_control%%
    )
)
echo.
pause
echo.
set
echo.
pause

I hope this helps someone who has been struggling with using WIndows Command numbered variables.  Remember, the call statement is the key to executing a second expansion when delayed expansion is enabled.


Erro: cannot convert from double to float

Question: Por que float não é aceito para os números 0.197 e 0.185?
Código:
float salBruto, salLiquido;

Scanner ent = new Scanner (System.in);
System.out.println("Informe o seu salário:");
salBruto = ent.nextFloat();

if (salBruto >= 1500 & salBruto <=2500) {
    salLiquido = salBruto + (salBruto * 0.197);
} else {
    if (salBruto > 2500 & salBruto <= 5000) {
        salLiquido = salBruto + (salBruto * 0.185);
    } else {
        if (salBruto < 1500 & salBruto > 5000) {
            salLiquido = salBruto;
        }
    }
}

ent.close();

Answer: Por padrão no java, os números literais com ponto flutuante são considerados pela JVM como do tipo double. Você precisa explicitar que aquele número é float, pois o range de valores do tipo double é maior do que o tipo float, e a JVM não faz o cast automático neste caso.
Apenas adicione um f ao lado do número literal, pois dessa forma você está informando de forma explicita que aquele valor literal também é um tipo float:
float salBruto, salLiquido;

Scanner ent = new Scanner (System.in);
System.out.println("Informe o seu salário:");
salBruto = ent.nextFloat();

if (salBruto >= 1500 & salBruto <=2500) {
    salLiquido = salBruto + (salBruto * 0.197f);
} else {
    if (salBruto > 2500 & salBruto <= 5000) {
        salLiquido = salBruto + (salBruto * 0.185f);
    } else {
        if (salBruto < 1500 & salBruto > 5000) {
            salLiquido = salBruto;
        }
    }
}


HDMI CEC command for shutdown not working on Android

Question: I am sending HDMI CEC command to Power on and Standby my LG LED TV 2015 make. The device is a Amlogic S922x based SBC running Android 9. The Power On commands work but the Standby commands don't. Can someone tell me what is wrong with this?
Power ON command (works):
echo 0x40 0x04 > /sys/class/cec/cmd
Power OFF command (does not work):
echo 0x40 0x36 > /sys/class/cec/cmd
Output of
echo 0x40 0x36 > /sys/class/cec/cmd && sleep 0.1 && cat /sys/class/cec/dump_reg
<code>AO_RTI_PWR_CNTL_REG0: 0x00004200
AO_CEC_GEN_CNTL: 0x00000000
AO_CECB_CLK_CNTL_REG0:  0xd02db2dc
AO_CECB_CLK_CNTL_REG1:  0x0000a007
AO_CECB_GEN_CNTL:   0x0000710a
AO_CECB_RW_REG: 0x02010300
AO_CECB_INTR_MASKN:0x0000003f
AO_CECB_INTR_STAT: 0x00000000
CEC MODULE REGS:
CEC_CTRL      = 0x03
CEC_MASK      = 0x00
CEC_ADDR_L   = 0x10
CEC_ADDR_H   = 0x00
CEC_TX_CNT   = 0x05
CEC_RX_CNT   = 0x02
CEC_LOCK      = 0x00
CEC_WKUPCTRL = 0x10
RX buffer: 04 83 00 e0 91 00 00 00 00 00 00 00 00 00 00 00
TX buffer: 4f 84 10 00 04 00 00 00 00 00 00 00 00 00 00 00
</code>
Comment: how to send command from amlogic based device to tv via hdmi cec ?
Answer: Try 0xF0 0x36 instead of 0x40 0x36.
Get codes from here: https://www.cec-o-matic.com/
Looks like 0x40 is when source is "playback 1". If you set the source to "unregistered" the result code for standby is 0xF0 0x36. Worked for me on Amlogic and Samsung TV.


upload xml to mysql php - Insert No value in table

Question: Here is .xml format :
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><?xml-stylesheet type="xsl" href="calls.xsl"?>
<calls count="500">
<call number="+919257035805" duration="0" date="1377691732581" type="3" readable_date="28/08/2013 17:38:52" contact_name="(Unknown)" />
<call number="+919257035805" duration="38" date="1377691747866" type="2" readable_date="28/08/2013 17:39:07" contact_name="(Unknown)" />
</calls>

Here is .php script
if ($_FILES[xml][size] > 0) {
$file = $_FILES[xml][tmp_name];
$xml = simplexml_load_file($file);
    $count = 0;
foreach ($xml->call as $call) {
$number = mysql_real_escape_string($call->number);
$duration = mysql_real_escape_string($call->duration);
$type = mysql_real_escape_string($call->type);
$readable_date = mysql_real_escape_string($call->readable_date);
$contact_name = mysql_real_escape_string($call->contact_name);

mysql_query("INSERT INTO call_log (number, duration, type, readable_date, contact_name ) VALUES ('$number', '$duration', '$type', '$readable_date', '$contact_name')") or die ("Error in query: $insert. ".mysql_error());

    }

//redirect
    header('Location: upload_sql.php?success=1?inserts=' . $count . ''); die;

}

But this script dose not add any value to Table......completely blank
Answer: You are trying to read attribute values the wrong way. You need to use array call:
$number = mysql_real_escape_string($call['number']);
$duration = mysql_real_escape_string($call['duration']);
$type = mysql_real_escape_string($call['type']);
$readable_date = mysql_real_escape_string($call['readable_date']);
$contact_name = mysql_real_escape_string($call['contact_name']);

When you use $call->number SimpleXMLElement object tries to get child node <number> which does not exist in <call>.
One other thing, what is field type of readable_date in DB?
If it is VARCHAR then no problem, but if TIMESTAMP or DATETIME during insert mysql will convert to 0000-00-00 00:00:00 which is wrong so you should first convert it to proper DB datetime format:
It is easier to convert already present UNIX timestamp $call['date'] using date() function than convert $call['readable_date']
$readable_date = date('Y-m-d H:i:s', (int) $call['date']);

But since it seems to me your date and readable_date do not match same dates you may need to properly convert it:
$readable_date = convertDate($call['readable_date']);

Function for conversion:
function convertDate($in)
{
   preg_match('#^(\d{2})/(\d{2})/(\d{4}) (\d{2}):(\d{2}):(\d{2})$#', $in, $matches);
   return $matches[3] . '-' . $matches[2] . '-' . $matches[1] . ' ' .
        $matches[4] . ':' . $matches[5] . ':' . $matches[6];
}


Trying to grok Linux quotas, where is the data stored?

Question: So all the tutorials and documentation for the Linux quota system has left me confused. For each filesystem with quotas enabled/on where is the actual quota information stored? Is it filesystem metadata or is it in a file?
Say user foo creates a new file on /home. How does the kernel determine whether user foo is below their hard limit? Does the kernel have to tally up quota information on that filesystem each time or is it in the superblock or somewhere else?
As far as I understand, the kernel consults the aquota.user file for the actual rules, but where is the current quota usage data stored? Can this be viewed with any tools outside repquota and the like? TIA!!
Update:
Thanks for the help. I had already read that mini-HOWTO. I am pretty clear on the usage of the user space tools. What I was unclear on is whether the usage data was ALSO in the file that stored per-user limits and you answered this with a yes.
From what I can tell, rc.sysinit runs quotacheck and quotaon on startup. The quotacheck program analyzes the filesystem, updates the aquota.* files. It then makes use of quota.h and the quotactl() syscall to inform the kernel of quota info.
From this point forward the kernel hashes that information and increments/decrements quota stats as changes occur. Upon shutdown, the init.d/halt script runs the quotaoff command RIGHT before the filesystems are unmounted. The quotaoff command does not appear to update the aquota.* files with the information the kernel has in memory. I say this because the {a,c,m}times for the aquota.user file are only updated upon a reboot of the system or by manual running the quotacheck command. It appears - as far as I can tell - that the kernel just drops it's up-to-date usage data on the floor at shutdown. This information is never used to update the aquota.* files. They are updated during startup by quotacheck(rc.sysinit). Seems silly to me since that updated info had already been collected by the kernel. So...in conclusion I am still not entirely clear on the methods. ;)
Answer:
For each filesystem with quotas enabled/on where is the actual quota information stored?

See e.g. the quotaon manpage. There will be files named .quota* in the filesystem root directory, which contain the necessary information (.quota.user,.quota.group, .quota.ops.user, .quota.ops.group).

Say user foo creates a new file on
  /home. How does the kernel determine
  whether user foo is below their hard
  limit? Does the kernel have to tally
  up quota information on that
  filesystem each time or is it in the
  superblock or somewhere else?

No, the kernel continually tracks fs usage, so it does not need to recalculate that on each allocation (which would be prohibitively expensive). It will do the calculation once when quotas are enabled, and then update that. The initial calculation is performed by quotacheck.

As far as I understand, the kernel
  consults the aquota.user file for the
  actual rules, but where is the current
  quota usage data stored? Can this be
  viewed with any tools outside repquota
  and the like? TIA!!

Quota information is stored in .quota* (see above). I'm not aware of any tools to generate quota usage reports, apart from repquota. But you should be able to generate most reports using/scripting repquota. Or you'll have to hack the source...
BTW:
The Quota mini-HOWTO give a good overview over the Linux quota system. It's a bit dated, but the fundamentals have not changed much.
Comment: Thanks, updated post. Wouldn't mind it if you or someone else could clarify on the updated info in the post.
Answer: From reading through your update it seems that you're wondering about why all the quota info the kernel has would be tossed when the machine is shut down instead of written to the aquota.* files.
Well, the kernel doesn't update the file on the fly since this would be expensive in terms of time.  Basically once quotas are enabled the kernel tracks usage in case a soft/hard limit is reached and it has to do something, this means that it's tracking this every time it has to allocate any fs blocks for any user/group on the system.  If it then had to update the aquota.* files while attempting to allocate fs blocks you could see where this would end up causing problems on even moderately busy systems, and it's not needed since the kernel is watching this for you and will log any transgressions for you, so you know to come run quotacheck.  Even the quota calculation can cause issues, which is why you have the tunable sysctl - dquot-max - and the reporting sysctl - dquot-nr - more info can be seen here:
http://www.mjmwired.net/kernel/Documentation/sysctl/fs.txt
As for the placement of quotacheck during the init process and not the halt process, it's all about time and how you think of things.  Usually when you halt a server you want it to go down, fast.  Not spend a bunch of time tabulating quotas, we're a lot more accustomed to init's taking longer.  Also, think of this process as init setting up the initial quota counts when the system started, rather than cleaning up as it's shutting down.  What if the FS's were mounted on another system without quotas enabled then restarted normally, you'd want to know where you're starting from everytime, and since you're going to init after every halt that's where it's setup.
Hope that helps.
Comment: I wasn't saying the kernel should update the file on each and every change, that would OBVIOUSLY be too expensive (that would make atime updates look good). I was confused though as to why the kernel can't update the file when the system is being shutdown, one operation. Now obviously the kernel isn't in the business of modifying system files directly, but if a syscall existed to dump the up-to-date quota information then a userspace quota utility could be called on system shutdown and possibly eliminate the need for time consuming quotacheck runs on boot.


mysql select with order by using filesort no index used

Question: Sorry fot long post but this is really strange and I am close to give it up. 2 tables:
CREATE TABLE `endu_results` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `base_name` varchar(200) NOT NULL,
 `base_nr` int(11) DEFAULT NULL,
 `base_yob` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`),
 KEY `endu_results_206a6355` (`base_name`),
 KEY `endu_results_63df4402` (`base_nr`),
 KEY `base_yob` (`base_yob`)
 ) ENGINE=InnoDB AUTO_INCREMENT=3424028 DEFAULT CHARSET=utf8;enter code here

and 2nd:
CREATE TABLE `endu_resultinterest` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `result_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `endu_resultinterest_3b529087` (`result_id`),
  CONSTRAINT `result_id_refs_id_19e24435` FOREIGN KEY (`result_id`) REFERENCES `endu_results` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48590 DEFAULT CHARSET=utf8;

There are about 2mln records in endu_resultstable and less then 100K i endu_resultinterest. I have slow query:
explain select base_yob from endu_resultinterest
inner join endu_results
on (endu_results.id = endu_resultinterest.result_id)
order by endu_results.base_yob;

1   SIMPLE  endu_resultinterest index   endu_resultinterest_3b529087    endu_resultinterest_3b529087    4   NULL    47559   Using index; Using temporary; Using filesort

The question is: Why mysql is using this index: endu_resultinterest_3b529087 - but it should use base_yob - this is where sorting is requested ?
To test it further I have manaully created 2 additional identical tables endu_testresults and endu_testresultintrest and filled those with some records:
CREATE TABLE `endu_testresults` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `base_yob` int(11) DEFAULT NULL,
 `base_name` varchar(200) NOT NULL,
 `base_nr` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`),
KEY `endu_testresults_a65b2616` (`base_yob`),
KEY `endu_testresults_ba0ab39c` (`base_name`),
KEY `endu_testresults_d75ba04d` (`base_nr`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;

So I go again for explain:
explain select base_yob from endu_testresultinterest
inner join endu_testresults
on (endu_testresults.id = endu_testresultinterest.result_id)
order by endu_testresults.base_yob;

and suprise suprise:
 1  SIMPLE  endu_testresults    index   PRIMARY    endu_testresults_a65b2616    5   NULL    19  Using index

Index sort column base_yob (endu_testresults_a65b2616) is now used.
 Why is that in one case index is used and in other I got 'using filesort;using temporary ?  Does size matters ? I will try to copy records from one to another but do not get it with indexes. MySql is 5.6.16
Answer: Short answer:  Because it is faster.
Long answer...
Your EXPLAINs seem to be incomplete -- I would expect 2 lines in each.
The first table is 20 (70?) times as big as the second.  The optimizer picked the smaller table to start with.  Hence it is initially doing 1/20th the amount of work.  The sort that comes later (ORDER BY ...) is much less work than if it had to do 20 times as much work to start with.
The output is only 48K rows, correct?  And that is how many rows in the 2nd table, correct?
Your test tables did not have the same bigger/smaller ratio, did they?  Hence the different EXPLAIN.


Odd-degree hyperellptic curve ramified at infinity

Question: Let $C$ be the projective curve with the affine model given by the equation $Y^2=F(X)$, where $F$ is a polynomial in $x$ with degree $d$ over a field $k$ with characteristic not equal to 2. When $d$ is odd, why is $C$ ramified at the point at infinity?
Answer: Hurwitz's formula says
$$   2g(C)-2=2\cdot (2g(\mathbb P^1)-2)+ \mid Ram\mid   $$
Hence the number $ \mid Ram\mid $ of ramification points is even and since there are only $d$ in the affine part, there must be one at infinity too.


Variation of parameters method for differential equations.

Question: Change the variable $x=e^t$ and then find the general solution for  the following differential equation
$2x^2y''-6xy'+8y=2x+2x^2lnx$
Here's my take so far. It seems a little suspicious that i can factor out 2 and x first.
$x^2y''-3xy'+4y=x(ln(x)+1)$ and if we factor out $x^2$ now we end up with $y''-\frac{3}{x}y'+\frac{4}{x^2}y=\frac{xlnx+1}{x}$ (1) Therefore substituting $x=e^t$ (1) now becomes
$y''-\frac{3}{e^t}y'+\frac{4}{e^(2t)}y=\frac{e^tt+1}{e^t}$ We need constant coefficients in order to use the variation of parameters method am i right? Please help.
Comment: You are to find a completely new equation for $u(t)=y(e^t)$. It happens but is largely wrong that $u$ gets also named $y$. A strict distinction of coordinate variables and functions between these variables can also help. // Or apply the solution mechanism for Euler-Cauchy DE.
Comment: Related: https://math.stackexchange.com/questions/4340285/solve-x3yxy-y-x-lnx/4340286#4340286
Comment: Thank you so much guys!
Answer: After change the variable $x=e^t$ we get
$$y''-4y'+4y=te^{2t}+e^t$$
Then
$$y=\frac{t^3e^{2t}+6e^t}{6}+(C_1+C_2t)e^{2t}=$$
$$=\frac{x^2\ln^3x+6x}{6}+(C_1+C_2\ln x)x^2$$
Comment: Thank you very much!!!


If $G$ is a finite group, then every element in the group has a finite order which is at most equal to $|G|$

Question: If $G$ is a finite group, then show that every element in the group has a finite order which is at most equal to $|G|$.
My attempt:
Let $|G|=m$
and let $a\in{G}$ so $\text{Order}(a)=\min\{n\in{N}\mid a^n=e\}$.
Now let's consider the set $S=\{a^0,a^1,a^2...a^{|G|}\}$
and since $S$ contains $m+1$ elements that all $\in{G}$ (by law of composition $a*a$) so there must be two elements which are equal i.e $a^k=a^l$.
Hence all elements in $G$ have finite order at most equal to $m$.
Is this a valid proof?
Thanks
Comment: You've proven that $a^k = a^l$ for distinct $k$ and $l$, but you still need to show that $a^n = e$ for some $n$. Can you find $n$ from $k$ and $l$?
Answer: Your definition of order of an element doesn't even make sense. The order of $a$ is the smallest $k$ such that $a^k=e$. And, since you used a definition which doesn't make sense, your proof doesn't make sense.After the edition, the proof is still not valid because you were supposed to prove that $a^k=e$ for some natural $k$, but you didn't.
Comment: @Rivaldo No, you can use the division algorithm to prove that the order of an element divides the order of the finite group.  Your stated problem is to show that in a finite group, each element has finite order.  What you wrote (in the edited version) is almost correct; the idea (pigeonhole principle) is correct. You only need to say that you can choose $0 \leq l < k \leq |G|$ such that $a^l = a^k$.  Then multiply so that $a^m = e$ for some $m > 0$.  What should $m$ be?
Comment: @RobertBell m=k-l? thanks for help
Comment: Yes, that's correct! You're welcome.
Comment: edited definition, my bad. Didn't really use it in proof just stated it...
Comment: hmm, is it to do with something as follows: suppose a$\in{G}$ and has order n, so n can be written as n=mq+r  for m,r$\in{z}$ , 0<r<m and |G|=m, $a^{mq+r}=a^r$


Prove that if $\dfrac{ax^2+2bx+c}{\alpha x^2+2\beta x+\gamma} (\alpha\neq 0)$ has $3$ inflection points, then all of them lie on one line?

Question: Prove that if the rational function $f(x)=\dfrac{ax^2+2bx+c}{\alpha x^2+2\beta x+\gamma} (\alpha\neq 0)$ has three inflection points, then all of them lie on one line? (All the parameters are real numbers.
It's an exercise problem. And there is a hint of this problem:

Firstly consider the case $a=0, \alpha=1$. Prove that if $b=0$ or $x^2+2\beta x+\gamma=0$ has real roots, then $f(x)$ would not have $3$ inflection points.

Here's my question:

I don't know how to prove the case "$x^2+2\beta x+\gamma=0$ has two real roots".
How to prove the general case if we have prove the case $a=0,\alpha=1$?
Comment: Try partial fractions if the denominator has real roots.
Comment: If $f''(c)=0$ and $f'''(c)\not=0,$ that is sufficient to show that $c$ is an inflection point. As for your quadratic, use information about the discriminant to see how many roots of what kind you have.
Comment: Recall that a quadratic equation has 2 real roots iff $\Delta=b^2-4ac>0$. Plug it in and you will get moving.
Comment: @Empy2 I tried this, let $x^2+2\beta x+\gamma=(x-d)(x-e)$, then $\dfrac{2b+c}{(x+d)(x+e)}=2b\dfrac{x+d}{x+e}+\dfrac{c-2bd}{x+d}$, I didnot see anything useful here.
Comment: I don't think you did the partial fraction decomposition correctly, but it does strike me as useful that $g(x)= \frac p{x+q}$ has no points of inflection.
Comment: This question is relevant, though certainly not a duplicate: https://math.stackexchange.com/questions/286541/three-inflection-points-are-on-a-line?rq=1.
Answer: For your second question, notice that ...
$$  \begin{align} f(x)&=\dfrac{ax^2+2bx+c}{\alpha x^2+2\beta x+\gamma}
\\&=\frac a \alpha \Bigg(  1+\dfrac{ \big( \frac ba - \frac \beta\alpha \big)x + \big(  \frac ca - \frac \gamma\alpha   \big) }{   x^2+\frac\beta\alpha x + \frac\gamma\alpha}   \Bigg )
\\
& = \frac a \alpha  \big (1+g(x) \big)   \end{align}$$
where $g(x)$ is a rational function satisfying the requirements of your hint.


Exponent of group-2

Question: Let be G a group (no abelian) . I want to prove that a certain subgroup K of G has limited exponent. Suppose that there exists a normal subgroup N (possibly different of K) of G with limited exponent. Can I pass to the quotient G/N and to assume without loss of generality we assume that N=1 to show that K has limited exponent?
Comment: The fact that the trivial group has bounded exponent is not very interesting, and hence the fact that $G$ has a normal subgroup of bounded exponent tells you nothing about $G$. What exactly are you actually trying to do?
Comment: How is that going to help you at all, if $N=1$?  Then passing to the quotient does nothing.
Comment: The standard way of saying it in English is "bounded exponent", not "limited exponent".
Answer: You keep talking about "assuming without loss of generality that $N=1$". The fact is that the extra hypothesis that $G$ has a normal subgroup of bounded exponent is vacuous. It gives you absolutely no extra information because every group has a normal subgroup of bounded exponent, namely, the trivial subgroup.
It is true that:

If $G$ is a group, $N$ has bounded exponent, and $KN/N$ (the image of $K$ in the quotient $G/N$) has bounded exponent, then $K$ has bounded exponent.

Which seems to be what you are trying to argue (note that this is not the same as "assuming without loss of generality that $N$ is trivial").
To see the statement above is true, note that $KN/N\cong K/(K\cap N)$. So $K/(K\cap N)$ is of bounded exponent, so there exists $n\gt 0$ such that $k(K\cap N)$ is of exponent $n$ for all $k\in K$. Since $N$ is of bounded exponent, there exists $m\gt 0$ such that for all $n\in N$, $n^m = 1$.
Now let $k\in K$. Then $(k(K\cap N))^m = K\cap N$; so $k^m\in K\cap N$. Since $k^m\in N$, then $(k^m)^n = 1$. Therefore, $k^{nm}=1$ for all $k\in K$, and $nm$ does not depend on $k$. So $K$ is of bounded exponent.
Comment: Thank you!
I understood your observations.

Exponent of group-2


What are some drawbacks/benefits of using ctools?

Question: What is the purpose of ctools?
Are there any drawbacks in using ctools for one's programming needs?
Also, what are some benefits to using ctools? From the project page it seems to just be a large collection of random tools.
Answer: Discovered the best place to learn this is actually from a lecture from drupalcamp austin in 2010 by Erik Summerfield.
http://vimeo.com/17957123
That's just a start. Otherwise going through example ctools integrated modules has helped as well. The fact is (at this moment) documented use case examples are limited.


Multi-core CPUs - Por que minha aplicação não utiliza todos os núcleos do processador?

Question: Tenho uma duvida que não consigo encontrar uma resposta convincente.
Há uma aplicação desenvolvida em Delphi 7, e em uma rotina extremamente complexa (que demora cerca de 2 horas) reparamos que só é utilizado para a mesma o primeiro núcleo do processador, no caso um Intel Core-i7 (8 núcleo), e os demais núcleos permanecem ociosos (pelo menos é que o monitor de recursos do Windows demonstra).
A respeito disso tenho vários questionamentos, sendo os principais os seguintes:

Por que isso ocorre?
Isso é um problema do Delphi 7, ou do Delphi?
Isso pode ser resolvido utilizando Delphi 7?
Outras tecnologia como .net e Java, já estão preparadas para utilizar de forma eficiente Multi-core CPUs?
No caso de outras tecnologia como .net e Java. É necessário fazer algo na aplicação ou isso já ocorrerá de forma automática e gerenciada pelo Framework?
Comment: Até onde sei você tem que dividir em multi threads para que cada uma seja rodada em um núcleo, e talvez ainda tenha que fazer algo mais além disso. Não sou expert em threads, mas com certeza se puser uma única pra thread para rodar ela não se dividirá em vários núcleos, pois não tem como o processador fazer paralelismo do seu código se seu código está todo, digamos, sequencial.
Comment: Na sua aplicação tem várias threads ou apenas uma?
Comment: Para usar todos os CORES, sua programação tem que ter sido pensada para isso. Mesmo em .Net deve-se usar bibliotecas e técnicas específicas para tirar proveito de todos os núcleos
Comment: É necessário que você modifique sua aplicação utilizando threads de sistema para que sua aplicação utilize mais de um core. Isso não é uma limitação ou problema do Delphi.
Comment: Como  o @Math comentou, tu já tentou rodar esse processo demorado em mais de uma thread? http://stackoverflow.com/questions/9630686/delphi-7-how-to-implement-multi-threading
Comment: @Math, somente uma unica theads, mas se trata de um processo único, que não poderia ser divido em threads. Mas uma mesma thead não poderia mandar instruções para todos o núcleos do processador?
Comment: Relacionado: http://pt.stackoverflow.com/q/1946/101
Answer: Algoritmo Serial vs Algoritmo Paralelo
Para conseguir resolver seu problema, vc vai precisar alterar seu algoritmo.
Hoje o que você tem é uma aplicação que executa toda sua lógica em uma única thread que será executada por um único processador. A isso chamados de algoritmo serial ou sequencial.
O que significa dizer que toda sua lógica é executada de maneira sequencial. Você teria que reescrever parte da sua aplicação dividindo-a em subtasks - subtarefas, e entregá-las a threads - este seria o algoritmo paralelo. Um adendo não é possível paralelizar todo o seu algoritmo, você apenas consegue dividir até um certo ponto.
O número de threads deve ser o número de processadores disponíveis e para cada thread você submete suas tasks. Cada thread é executada por um processador. Não confunda computação paralela com programação concorrente.

Outras tecnologia como .net e Java, já estão preparadas para utilizar
  de forma eficiente Multi-core CPUs?

Java sempre proveu APIs e frameworks para programação concorrente e computação paralela.A partir do Java 1.5 um framework chamado Executor Framework foi adicionado. Ele oferece diversas classes utilitárias, interfaces, métodos para a fabricação de Pools de Thread e métodos de submissão de tasks.
Já no Java 1.7 ganhamos o Fork/Join framework. Ao qual permite que você programe um algoritmo definindo Thresholds de processamento, que são limites, quando esse limite é atingido você querbra a tarefa em dois - Fork. Uma vez que ela é executada e que as outras tarefas são completadas, você faz o jois delas para o resultado final. Interessantemente, este framework implementa um algorítimo chamada work-stealing. Trata-se de uma técnica onde quando uma thread termina de executar sua task ela rouba a task de outra thread que ainda não terminou sua execução.
Last but not least
Se assumir o projeto de migrar um novo modelo de execução, recomendo que você estude a lei de Amdahl's que prediz o máximo de tempo que é possível se optimizar um programa utilizando múltiplos processadores.
Fontes:
Algoritmo serial: https://en.wikipedia.org/wiki/Sequential_algorithm
Algoritmo paralelo: https://en.wikipedia.org/wiki/Parallel_algorithm
Computação paralela: https://en.wikipedia.org/?title=Parallel_computing
Comment: Vale apena mencionar que embora Java permita a computação paralela e concorrente, nada é mágico e você precisa aprender a utilizar várias threads e etc... O mesmo é possível no Delphi.
Comment: tem tb uma abstração em cima de thread, que á o modelos de Atores - Actors Model, simplifica bastante. O Framework Akka pode ajudar.

https://en.wikipedia.org/wiki/Actor_model
Answer: Explicando uma forma BEM simplificada as diferenças entre os modelos de execução:
Multitasking:

Vários processos em um núcleo.
Rodam de forma concorrente.

Multiprocessing:

Vários processos em vários núcleos.
Rodam de forma paralela

Multithreading:

Um processo usando várias threads.
Computação é dividida entre os núcleos
PS: (Rodará em paralelo ou não, depende do seu código e do hardware)


Return column names instead of table names in SQLite after join

Question: I have such query
SELECT "sq0"."_backward_relation_key","team"."name","team"."id"
FROM "team"
JOIN (SELECT "event_id" "_backward_relation_key","team_id" "_forward_relation_key" FROM "event_team" WHERE "event_id" IN (2))
"sq0" ON "sq0"."_forward_relation_key"="team"."id"

In postgres it returns column names in such way:
_backward_relation_key | name | id

But in sqlite it returns them in such fashion
sq0 | team | team

Is there any way to change sqlite behaviour to make it similar to postgres without changing query itself?
Comment: This bug was fixed a long time ago. Update your SQLite.
Comment: Can you also tell us where/how you are running your query?  The obvious workaround is to use aliases.
Comment: This query is generated in runtime by python and run into sqlite3 driver. I could use aliases, but the point is that this query can be generated for different table in runtime and want to keep it universal enough and aliases aren't working for it
Answer: No - The only way you can guarantee that column names will be what you want in SQLite is to use aliases.


i want to print number from 1 to n but after running this code, error "core dumped" occured

Question: i want to print number from 1 to n but after running this code, error "core dumped" occured.
I know code works well if i change self to n but why not self ???
n = int(input("?"))

def again_book(self):
    if n > 0:
        again_book(self - 1)
    print(self)

again_book(n)

Comment: because `n` is never changed so it is always greater than 0
Comment: You should say `if self > 0:`
Comment: (a) `self` is not a good name for your own arguments (b) don't do iterative things  recursively.
Answer: Your code is not working because you are never changing the n variable. In your function you're checking if n > 0 and it will always be
Here is a fix:
n = int(input("?"))

def again_book(self):
    if self > 0:
        again_book(self - 1)
    print(self)

again_book(n)

Another way of doing it is using a while loop:
n = int(input("?"))
x = 0

while x < n:
    print(x)
    x += 1

Answer: I think you can use list comprehension
[num for num in range(num_limit)]
Answer: Self is used when you have to pass object itself.
further you can read from here


Rehearsal Letters: Skipping I, J, O?

Question: Sometimes in orchestral scores, rehearsal letters I, J, or O may be skipped.  For example, Tchaikovsky's Piano Concerto No. 1 does not have a rehearsal letter J.  What is the reason?
Comment: J, 1 and I are often mistaken so are removed from various sets (not just in music), as are 0 and O.
Comment: Maybe I and O could be mistaken for 1 and 0 which could mean something else? That doesn't seem to hold for J though.
Comment: Does Russian even have those letters?
Comment: I and J were the same letter until a couple of centuries ago, and the tradition of using only one of them has persisted beyond the recognition of J as a separate letter.
Comment: @Tim of course not.  But Russian composers are generally quite capable in the Latin alphabet as well as the Cyrillic.  Regardless, the rehearsal letters seem likely to have been assigned by the.publisher.
Comment: @Tim Russian did have 'I' in the past, before the spelling reforms of the early 20th c. And 'J' exists in many neighboring languages like Ukrainian and Serbian.
Answer: Omitting either I or J appears to be fairly commonplace. Gardner Read's Music Notation: A Manual of Modern Practice says that "the letters I or J are usually omitted, the consecutive lettering going from H to J or from I to K" (p. 43). G. Schirmer's internal style guide, The G. Schirmer/AMP Manual of Style and Usage (3rd edition), says of rehearsal marks "[w]e use the alphabet from A-Z with the exception of the letter J, which we skip because of its close resemblance, in many fonts, to the letter I, before starting over again with 'AA.'"
As for O, the story is not as simple. The Wikipedia article on rehearsal letters says that it may be skipped (along with I and J), but none of its references which are available to me at the moment (I don't have Del Mar's Anatomy of the Orchestra and J. V. Horn's The Community Orchestra doesn't seem to exist!) say anything about O.
I honestly don't recall ever seeing O skipped; if someone could provide an example I might have more to say. I don't know why it would be skipped. It does often look like 0, but I can't imagine a measure number 0 occurring far enough into a piece of music to come after rehearsal N (or at all).
Comment: Ditto for runways and taxiways!  https://aviation.stackexchange.com/q/66845/31425
Comment: This reasoning reminds me of the recent gene renaming because of "Excel messes up our data" ( https://www.theverge.com/2020/8/6/21355674/human-genes-rename-microsoft-excel-misreading-dates ). As in, here: instead of using a proper font, where each and every letter is legible and distinguishable, a workaround is applied. Fascinating :)
Answer: Doktor Mayhem had pretty much answered this question:

J, 1 and I are often mistaken so are removed from various sets (not just in music), as are 0 and O.

Rehearsal Letters: Skipping I, J, O?


Somar coluna de tempo no SQL SERVER

Question: Tenho uma coluna do tipo time em uma tabela. Com registros como:
00:02:15
00:09:47
00:00:25
...

Preciso, no meu select, buscar a soma desses minutos em formato time. Exemplo de retorno: 00:12:27
Tentei de diversas formas sem sucesso.
Answer: Você pode fazer da seguinte forma:
create table t1 (id int, t time)

insert into t1 values (1,'00:00:25.0000000')
insert into t1 values (1,'00:12:20.0000000')

insert into t1 values (2,'00:00:02.0000000')
insert into t1 values (2,'00:00:10.0000000')

SELECT ID, CAST(DATEADD(MILLISECOND,SUM(DATEDIFF
(MILLISECOND,0,CAST(T AS DATETIME))),0) AS TIME) FROM t1
GROUP BY ID

Veja funcionando no SQLFiddle
Comment: Devo dizer que fiquei confuso entre os `casts`, `dateadd` e `sum`
Answer: Você pode usar uma combinação de DATEADD e DATEDIFF para calcular a diferença do intervalo em horas, e CAST ao final para converter para o format TIME assim:
select CAST(DATEADD(ms, SUM(DATEDIFF(ms, '00:00:00.000', hora)), '00:00:00.000') as time)

Exemplo:
declare @t table (hora time)
insert into @t values ('00:02:15')
insert into @t values ('00:09:47')

select CAST(DATEADD(ms, SUM(DATEDIFF(ms, '00:00:00.000', hora)), '00:00:00.000') as time) from @t

Note que o segredo é somar a diferença entre a hora '00:00:00' e a hora do campo do banco.
Baseado nessa reposta do SO em inglês: https://stackoverflow.com/questions/19535718/sum-total-time-in-sql-server
Answer: O jeito mais simples de fazer o que deseja é:
SELECT
    ID, CONVERT(TIME,DATEADD (ms, SUM(DATEDIFF(MILLISECOND, 0, T)), 0)) AS TIME
FROM
    T1
GROUP BY
    ID

Somar coluna de tempo no SQL SERVER


Bingo variant- Minimum no of boxes

Question: We play $5$ line bingo but in a different way.
We take a $5×5$ grid, fill it randomly with numbers from $1$ to $25$.
Then the players call out numbers they want and when you get $5$ full lines crossed out (including vertical,horizontal or/and  diagonal) you win the game.
I was wondering what would be the minimum number of boxes a player needs to cross out to win the game.
By figuring it out manually, I believe it would be $16$. Similarly for a $4×4$ grid it would be  $11$ and for a $6×6$ grid it would be $24$.
(For an $n × n$ grid you need $n$ full lines crossed out to win)
Is there some way to do this mathematically? And can we extend this to other $n × n$ grids?
If there is a way, will it change depending on whether n is even or odd because of the nature of the diagonal line intersecting and not intersecting in case of odd and even grids respectively?
Perhaps for even grids the series resembles A293414 https://oeis.org/A293414
Comment: I edited the question.... The 5×5 grid needed 16 boxes not 17..
Answer: For the $5\times 5$ grid, the minimum is $16$:
o o o o o
. o . o .
. o o . .
. o . o .
o o o o o
For grid sizes $1$ thru $12$:
$$1,3,6,11,16,24,32,43,54,68,82,99$$
Possibly related to OEIS A087099
Comment: But how would this work?

Bingo variant- Minimum no of boxes


How can I force my model to predict the samples that are close to zero?

Question: I have a large amount of inventory data and I am trying to predict when the inventory gets low using one component of the change in inventory (yes I know this doesn't describe inventory very well by itself). It seems that the tendency of models is to try to predict around the mean of the data and reduce local variance (like variance on a daily scale versus yearly scale). This daily variance is what I care about though. Is there a certain loss function or method I can use to focus my predictions on these values that are near zero?
Comment: Your question is still very unclear. Please do what you can to explain what you're doing (including what your data are) and what you want to achieve. You should aim to edit your question so that people don't need to read comments to figure out what you want.
Comment: You are going to have to be more specific.  Do you have sample data that we could look at?  What do you want your response variable to be?  The amount of time until the inventory is low?
Comment: I am using past sales data to predict the next days inventory, but what I actually care about is low inventory. My dependent variables are whatever manipulations of sales I can imagine might be relevant (finite difference, various sums). Someone might have a more creative way of looking at this, but I just want to be able to train a model with a focus on the inventory data 'close' to zero.
Comment: I agree that some more information could help. In a first and crude try, you could howecer define "low" inventory as a dummy and see what predicts this variable in a simple random effects discrete choice model. You could play around with lags and forwards (maybe seasonal effects?) to see what happens. Again, this is a very crude way of dealing with the issue. I advise you to post at least a snippet of your data (or structure).
Comment: I apologize for the difficulty interpreting what I am looking for, I wasn't entirely sure myself. From what I can tell though the two answers given were almost perfect. Is there any way to implement these using Python's sklearn? I've looked around a little, but I'm not sure if there is a method I can use with a custom loss function. I could just code up my own linear regression if I don't have any other options.
Answer: I'm guessing that your current loss function is quadratic error?  Actual inventory $a$ minus estimated inventory $e$ squared?  So your loss is $L=(a-e)^2$?  Plot that for values of $a$ and $e$.  Your question basically says that you're not happy with the loss function.  You want higher loss when $a$ is low.
How about:
\begin{align}
L = \frac{(a-e)^2}{1+a}
\end{align}
This corresponds to a reweighting scheme as described by @fcoppens.
However, modifying the loss is more general than just running least squares with reweighting. You could also have, for example
\begin{align}
L = \frac{e}{a} - \log e
\end{align}
This is also much stronger as $a \to 0$, (I felt it might be too strong).  This corresponds to an exponential model.
Maybe the best of both worlds is:
\begin{align}
L = \frac{e+1}{a+1} - \log (e+1)
\end{align}
You probably want higher loss when $e$ is low too since that indicates a false positive "low inventory warning", but you don't mention this in your question.
Comment: it's more than 'corresponds' I think; OLS has a quadratic loss function (which is your numerator) and you have choosen specific weights for my weight vector $w$ namely inversely proportional to (1+inventory), so it's more like 'a special case of' what I propose, with particular weights.
Comment: @fcoppens I said "a reweighting scheme", as in one of many posssible ways of reweighting.  However, generally modifying the loss is more than general than just running least squares with reweighting.  I'll explain further in my answer.


Como receber e lidar com Notificações "IPN" do PagSeguro PHP

Question: Queria saber como faço para lidar com as notificações do PagSeguro e salvar elas em LOG.txt
fiz oque esta nesta print http://prntscr.com/k08zyo
mais não funcionou..
Answer: Jheyson boa noite.
Eu trabalhei muito com o pagseguro, e sempre quando precisava pegar a resposta e guardar em um log eu usava o file_put_contents
Comment: Não preciso necessariamente salvar em log quero pegar a resposta e tirar algumas informações dela por isso optei por salvar ela como log
Comment: Ah sim, entendi, você pode fazer o seguinte, entra no sandbox, pega o notificationCode e coloca direto no seu código, e claro não use o POST, assim você vai conseguir ver exatamente como vem o retorno, caso não consiga me avise que dou um exemplo para você.
Comment: O problema real é que o post não esta nem chegando ao mesmo site fiz o teste e não chega, na minha conta do PagSeguro esta tudo configurado o link de notificação
Comment: Esse é o problema, você está esperando chegar alguma coisa no seu site, e no caso o ideal seria você simular o que está chegando, que é o que estou propondo.

Ao invés de colocar $_POST['notificationCode'], coloque o notificationCode que pegou no sandbox, e pronto, vai ter todos os dados que vão chegar em seu site.

Mas o porque que não está chegando o POST, ai já não sei, teria que ver como você está fazendo o checkout.
Comment: O problema é que o próprio pagseguro não envia, fiz o teste colocando para quando o URL de notificação tiver qualquer acesso ele me envia um e-mail, fiz uma compra com outra conta e não chegou nada, acredito que pode ter algo errado não sei dizer oque é e nem o porque do post não chegar


Construct the src in a javascript tag from node fields

Question: I have a drupal 7 instance where I would like to create nodes that call reports from a separate site using javascript.
Currently I construct the HTML tags myself which look something like this:

Note that there are a bunch of parameters in the url shown in square brackets: [VALUE]
What I want to do is have a node creation interface for admin users that allows them to set all of the parameter values and constructs that URL, then constructs a string using those parameters and uses it as the node's output when viewed.
I haven't been able to find any kind of module for this, maybe I am describing it wrong - or maybe it's a very rare use-case.  Any ideas would be wonderful, even if it's 'hire a developer, this has never been done before'.
Comment: Well there's definitely no module for it. Does it need to be in the head tag?
Comment: Nope, just in the body (with filters turned off) as I want to be an integral part of the page.  A friend has offered to help, I may use this as a project to learn how to make modules, though I don't know how often it would be used.
Answer: You can do this in a node.tpl.php file in your theme or to be specific to one content type.
Duplicate the default node.tpl.php file found in /modules/node/ and rename it to node-NODETYPE.tpl.php NODETYPE being the machine name of the node which you can find at structure -> content types, in the CMS.
Install the devel module and enable it, then do a dpm($node); in your copied node.tpl.php file to get the variables you need. Of course you would need to have a custom theme so it doesn't get overridden on an update.
To do this in a module you'd need be somewhat familiar with hooks.
And since the dpm is called after the output is rendered you need to reload the page twice.
Don't forget to clear cache after you add in the node.tpl.php to your theme.
Comment: Thanks that's very helpful!  I can't upvote yet, but I will hold off 'accepting' the answer until I've seen it work.
Comment: Thanks for the edit. And thanks Darvenen. Just add a comment if you need some more help but really this is a well documented process "getting node values in node.tpl.php"
Comment: I'm halfway there - I only stopped because my work day ended =)
So far the advice has been very sound.


Is there an equivalent of Struts token validation in Spring

Question: I am seeing duplicate form submission issues in spring. Wanted to implement what is already there in Struts, token validator to check for duplicate requests.
In my form currently, when the user submits a form, instead of submitting and redirecting the page, it makes 2 JSON calls for validation and then submits the form, creating scope for duplicate form submission.
I wanted to use tokens to validate each request
Answer: Not directly, I think, but:

http://explodingjava.blogspot.com/2009/03/spring-mvc-synchronizer-token.html

IMO the post-redirect-get or simple JS disable of submit may be enough, unless you're explicitly trying to handle back-button issues and your form page is cached.
Comment: Yeah. Back button is one of the issues. Some users with slow internet connection are able to hit the back button and resubmit. Could form page cache be an issue? Could back button auto-trigger auto-submit of the form. We are seeing weird issues, wherein users report pressing back button. However we see duplicate records created at the same timestamp (down to even smallest second)
Comment: @SmilesinaJar That's why you do post-redirect-get, so hitting the back button doesn't resubmit (although browsers usually pop up a dialog).


How to find matrix from general solution?

Question:
Find a $2 \times 3$ system (two equations with three unknowns) such that its general solution has form $\begin{pmatrix}1\\1\\0 \end{pmatrix}+s\begin {pmatrix}1\\2\\1\end{pmatrix},\ s \in \Bbb R.$

I tried thinking that $s\begin {pmatrix}1\\2\\1\end{pmatrix}$ is solution to kernel of asked matrix, and tried matrix $\begin {pmatrix}1&-1&1\\1&-1&1\end{pmatrix}$, but it also includes $\begin{pmatrix}1\\1\\0 \end{pmatrix}$ in its kernel!
Answer: Let $$A\mathbf{x}=\mathbf{b}\tag{1}$$ be the system in matrix form, where $A$ is the coefficient matrix for the asked system in matrix form. Where
$\mathbf{x}=\begin{pmatrix}x_1\\x_2\\x_3\end{pmatrix}$
Notice that $\ker(A)=\{k\mathbf{v}|k\in\mathbb{R}\}$, where
$\mathbf{v}=\begin{pmatrix}1\\2\\1\end{pmatrix}$
You can take any matrix $A$ as above, for instance
$$A=\begin{pmatrix}2&-1&0\\0&1&-2\end{pmatrix}$$
since $\mathbf{x}=\begin{pmatrix}1\\1\\0\end{pmatrix}$ is a particular solution we have $\mathbf{b}=\begin{pmatrix}2&-1&0\\0&1&-2\end{pmatrix}\begin{pmatrix}1\\1\\0\end{pmatrix}=\begin{pmatrix}1\\1\\0\end{pmatrix}$. Hence the system
$$\begin{pmatrix}2&-1&0\\0&1&-2\end{pmatrix}\begin{pmatrix}x\\y\\z\end{pmatrix}=\begin{pmatrix}1\\1\\0\end{pmatrix}$$
satisfies the problem.
Comment: The result vectors are only two dimensional.
Answer: One can translate the first two components of $u= (x,y,z)^T= (s+1, 2s+1, s)^T$ into the following system $Au=b$, the third component stays free and acts as $z=s$:
$$
x = s + 1 = z + 1 \iff x - z  = 1 \\
y = 2s + 1 = 2 z  + 1 \iff y - 2 z = 1 \\
$$
Or written as augmented matrix
$$
(A\mid b) =
\left(
\begin{array}{rrr|r}
1 & 0 & -1 & 1 \\
0 & 1 & -2 & 1 \\
\end{array}
\right)
$$
Comment: What I could understand is since we need only one free variable, we have put pivot in first two columns and found third column by solving $
\left(
\begin{array}{rrr}
1 & 0 & m \\
0 & 1 & n \\
\end{array}
\right)(1\ 2\ 1)^T=(0\ 0)^T$ and then fourth column by multiplying this matrix by $(1\ 1\ 0)^T$  Am I right?
Comment: I added some more detail how the equation of the solution, a line with position vector and $s$ times direction, was directly translated into an ihomogenous system with one free variable $z$.


Armazenar / Carregar tipos genéricos no Redis com C#

Question: Cenário
Criei uma função usando AOP para fazer Cache de informações, quando o método é chamado eu armazeno no Redis utilizando o cache.StringSet, porém quando preciso capturar de volta o valor do Redis preciso que volte do mesmo tipo que eu recebi, não sei se estou fazendo da forma correta serializando e armazenando a string, mas quando eu retornar do Redis cache.StringGet preciso que seja do mesmo tipo quando o objeto foi inserido.
Lembrando que os objetos podem variar, podem ser de N tipos diferentes.
Código
public sealed override void OnInvoke(MethodInterceptionArgs args)
{
    var cache = RedisConnectorHelper.Connection.GetDatabase();
    var result = cache.StringGet(args.Method.Name);

    if (result.HasValue)
    {
        args.ReturnValue = result;
        return;
    }

    base.OnInvoke(args);
    cache.StringSet(args.Method.Name, Serialize(args.ReturnValue));
}

private string Serialize(object obj)
{
    return JsonConvert.SerializeObject(obj);
}

Answer: Contornei o problema com a seguinte solução:
No método de entrada onde tenho o Aspecto mudei os tipos para dynamic.
Sendo assim a entrada e saída é genérica, utilizando object também funcionou.
Por enquanto manterei dessa forma.
[RedisCacheableResult]
public List<dynamic> ReturnCustomer()
{
    var lstCustomer = new List<dynamic>();

    var customer = new Customer
    {
        Id = 1,
        Name = "Acme Inc",
        Email = "email@example.com"
    };

    var customer1 = new Customer
    {
        Id = 2,
        Name = "Marvel Inc",
        Email = "email@example.com"
    };

    lstCustomer.Add(customer);
    lstCustomer.Add(customer1);

    return lstCustomer;
}

No Deserialize utilizo:
private static dynamic Deserialize(string data)
{
    return JsonConvert.DeserializeObject<List<dynamic>>(data, Settings);
}

Segue a solução publicada no GitHub:
https://github.com/thiagoloureiro/TestaCache
Issues, pullrequests, stars e forks são bem vindos :)


Codable with string array

Question: This question is more of an aesthetic one. I have a simple Codable with a string array. I use it to encode and decode a plist:
struct Favorites: Codable {
  var favorites: [String]
}

The one thing that bothers me about this is when I e.g. add an element to the array, I have to do this:
favorites.favorites += [phrase]

Is there something I can do to prevent having to write the double favorites.favorites?
Comment: You could use `.append(contentsOf:` function. -> [documentation](https://developer.apple.com/documentation/swift/array)
Comment: Not sure you understood my question? I've clarified it now.
Comment: Is there a reason you need `Favorites` in the first place, instead of encoding/decoding a `[String]` directly?
Comment: @Alexander I'm such an idiot! :P I thought I always had to use `Codable` but I can just use existing types. I guess that's the real answer here.
Answer: If you want to avoid writing favorites two times, you can add subscript to your Favorites struct and also add mutating method to add items in your array.
struct Favorites: Codable {
    var favorites: [String]

    subscript(index: Int) -> String {
        favorites[index]
    }

    mutating func addItem(_ item: String) {
        favorites.append(item)
    }

    mutating func addItems(_ items: [String]) {
        favorites.append(contentsOf: items)
    }
}

Now your can access your favorites array as with instance of Favorites struct using subscript like this.
var favorites = Favorites(favorites: ["Apple"])
print(favorites[0]) // print Apple
favorites.addItem("Banana")
print(favorites[1])// print Banana

Comment: Ah, yes, of course! That also helps me understand the basics of Swift a bit better. Thank you so much.

Codable with string array


If $AB\parallel DC$, $BC\parallel AD$, and $AC\parallel DQ$, find $\Bbb X$ in terms of the areas $\Bbb A$, $\Bbb B$, and $\Bbb C$.

Question:
If $AB\parallel DC$, $BC\parallel AD$, and $AC\parallel DQ$, find $\Bbb X$ in terms of the areas $\Bbb A$, $\Bbb B$, and $\Bbb C$.

Please, I wrote a lot of relations, but I just need to prove that
$\overline{AC}\cap\overline{BQ}=P\implies BP=PQ$.  If I prove this, I will get $\Bbb X=\Bbb A+2\Bbb B+\Bbb C.$
For context, if $BP=PQ$, then $\triangle BPC$ and $\triangle CPQ$ have equal area.  Let $\overline{BP}\cap\overline{CD}=R$.  Then, we can show that $\triangle APR$ and $\triangle BRC$ have equal area.  If $S=\overline{AQ}\cap\overline{CD}$, then we can see that $\mathbb{X}-\mathbb{A}-\mathbb{B}$ is the area of $\triangle ARS$.  It is not difficult to show that the area of $\triangle ARS$ is $\mathbb{B}+\mathbb{C}$.
Comment: @Piquito  That is because the location of $Q$ is irrelevant, as long as $CD$ intersects $BQ$ and $AQ$ internally.  The equality $\Bbb X=\Bbb A+2\Bbb B+\Bbb C$ holds regardless.
Comment: And I couldn't proof this.
Comment: You have a parallelogram $ABCD$ and a diagonal $AC$. Then you have a parallel passing by $D$ but you say nothing about the position of the point $Q$. Edit your problem.
Answer: Well, $ABCD$ is a parallelogram so $AC$ bisects $BD$. Using this and $AC\parallel DQ$ we obtain $BP=PQ$.
Comment: Why? The position of point $Q$ is not fixed.
Comment: @Piquito Just look at the triangle $BDQ$. Line $AC$ is parallel to $DQ$ and bisects $BD$. Hence it also bisects $BQ$.
Answer: Here is a solution to the problem.  Let $[S]$ denote the area of a shape $S$.  Define $P=AC\cap BQ$, $M=BQ\cap CD$, and $N=AQ\cap CD$.  The line $DQ$ meets the line $AB$ and $BC$ at $E$ and $F$, resp.  The line passing through $M$ parallel to $AC\parallel DQ$ meets $AN$ at $R$.

Since $QA$ is a median of $\triangle QBE$ and $DM\parallel MD$, $QN$ is also a median of $\triangle QMD$.  Therefore $\Bbb C=[DNQ]=[MNQ]$.
Thus $\Bbb B+\Bbb C=[MNQ]+[CMQ]=[CNQ]$.  Because $MN=ND$ and $RM\parallel DQ$, we easily see that $RN=NQ$.  Thus $[CNR]=[CNQ]=\Bbb B+\Bbb C$.  This shows that
\begin{align}[ARC]&=[ANC]-[CNR]\\&=[APMN]+[PMC]-[CNR]\\&=\Bbb X+\Bbb A-\Bbb B-\Bbb C.\end{align}
Because $RM\parallel AC$, we get $[ARC]=[AMC]$.  As $AB\parallel CD$, we have $$[AMC]=[BMC]=[BPC]+[PMC].$$  Since $P$ is the midpoint of $BQ$ as proven by timon92, we have $$[BPC]=[QPC]=[PMC]+[CMQ]=\Bbb A+\Bbb B.$$  Thus
$$[AMC]=[BPC]+[PMC]=(\Bbb A+\Bbb B)+\Bbb A=2\Bbb A+\Bbb B.$$  Thus,
$$\Bbb X+\Bbb A-\Bbb B-\Bbb C=[AMC]=2\Bbb A+\Bbb B,$$
or
$$\Bbb X=\Bbb A+2\Bbb B+\Bbb C.$$

Here is how to use coordinate geometry to solve this problem.  WLOG, we can assume that $ABCD$ is a unit square: $A=(0,0)$, $B=(0,1)$, $C=(1,1)$, and $D=(1,0)$.  Let $Q=(1+t,t)$ where $0\le t\le 1$.
Then $AQ$ is given by
$$y=\frac{t}{1+t}x.$$
So $N=\left(1,\frac{t}{1+t}\right)$.  Therefore
$$\Bbb C=[DNQ]=\frac12 \cdot\frac{t}{1+t}\cdot t=\frac{t^2}{2(1+t)}.$$
The line $BQ$ is given by
$$y-1=-\frac{1-t}{1+t}x.$$
Therefore
$$M=\left(1,\frac{2t}{1+t}\right).$$
Hence
$$\Bbb B=[CMQ]=\frac12\cdot \left(1-\frac{2t}{1+t}\right)\cdot t=\frac{t(1-t)}{2(1+t)}.$$
We also have
$$P=\left(\frac{1+t}{2},\frac{1+t}{2}\right).$$
Hence
$$\Bbb A=[CPM]=\frac12\cdot\left(1-\frac{2t}{1+t}\right)\cdot\left(1-\frac{1+t}{2}\right)=\frac{(1-t)^2}{4(1+t)}.$$
Now
$$\Bbb X+\Bbb A=[ANC]=\frac12\cdot\left(1-\frac{t}{1+t}\right)\cdot 1=\frac{1}{2(1+t)}.$$
Hence
$$\Bbb X=\frac{1}{2(1+t)}-\frac{(1-t)^2}{4(1+t)}=\frac{1+2t-t^2}{4(1+t)}.$$
If $\Bbb X=a\Bbb A+b\Bbb b+c\Bbb C$, then
$$1+2t-t^2=a(1-t)^2+2bt(1-t)+2ct^2=a+(-2a+2b)t+(a-2b+2c)t^2.$$
That is, $a=1$, $b=2$, and $c=1$.


Primitive Root mod 26 and 25?

Question: I would live to calculate the primitive roots modulo 26 and modulo 25.
My approach:
26 is not a prime number.
But 26=2*13 are Prime numbers.
So I calculated the primitive roots of them:
Result for 2: 1
Result for 13: 2,6,7,11
So what are the primitive roots of 26?
For 25 I know that 25=5*5. But I dont know how it helps.
Comment: A primitive root modulo $q$ is, by definition, an element of (multiplicative) order $\phi(q)$. What is $\phi(26)$, and what integers have order $\phi(26)$ modulo $26$? (Hint: there are four residue classes of primitive roots modulo $26$, and $7$ is one of them.) Same with $25$: what is $\phi(25)$...?
Comment: For $25,$ see http://math.stackexchange.com/questions/992688/primitive-root-mod25
Comment: I tried it as Greg Martin suggested. My result: primitive roots of 26 are: 7,11,15,19 and primitive roots of 25 are 2,3,8,12,13,17,22,23. Is that right? phi(25) = 20 and phi(26) = 12.
Answer: If ord$\displaystyle_pa=d$ and ord$_2a=1$ if $a$ is odd and $p$ is an odd prime
we can prove that ord$_{2p}a=$lcm$(d,1)=d$
So, if ord$_pa=\phi(p)=p-1$ or ord$_{2p}(a+r\cdot p)=p-1=\phi(2p)$ if $a+r\cdot p$ is odd
, where $0\le r<p$
More specifically, if $a$ is a primitive root $\pmod p$
Case $\#1:$ if $a$ is odd and  $a$ will be a primitive root $\pmod {2p}$
Case $\#2:$ Else i.e., if $a$ is even, $a+p$ will be a primitive root $\pmod {2p}$
Comment: For the sake of completeness: if $a$ is a p.r. mod $p$ and $a^{p-1}\not\equiv1\pmod{p^2}$ then $a$ is a p.r. mod each $p^k$. If $a^{p-1}\equiv1\pmod{p^2}$, replace $a$ by $a+p$ s.t. $(a+p)^{p-1}\not\equiv1\pmod{p^2}$ and $a+p$ is a p.r. mod each $p^k$.

Primitive Root mod 26 and 25?


How do I download a form table in CSV or Excel format?

Question: I have a form whose class extends FormBase. The form has a table that gets populated with information.
Basically I'm trying to download the table into a CSV or Excel file. I've seen some old posts for Drupal 6 but I haven't found anything for Drupal 8.
How can I achieve this?
Answer: You can use the Forena module. Here is a quote from that page:

... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

So if you'd install Forena in your site, then these are the steps for creating such CSV files are:

a custom SQL query (where you have the full power of SQL at your fingertips, and various extra features related to it provided by Forena, such as using report parameters, conditional SQL, etc).
a custom report (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).
saving the report in (eg) CSV format, using one of the typical hyperlinks to do so in a report.

For an online demo (prior to installing/testing Forena), checkout these links:

Reporting samples, about data stored in some SQLite database, and including things like drill down reports, creating charts (using the PHP SVG Graph library), etc.
Forena Documentation, which you also get in your own site after installing the module).

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.


How multi layer neural network classify data without extracting features?

Question: In CNN we have convolution layer and pooling layer for feature extraction. How the features are extracted in Fully connected neural network? Secondly CNN has more expressive power and and number of learn able parameters are also less in this case. I want to know that if CNN are so perfect then why we use fully connected neural networks?
Comment: Convolutional layers are useful if the input is either image and/or temporal based, e.g. data adjacent to each other are likely "related". Fully connected layer does not have that kind of assumption.
Comment: If you find an answer somewhere, please post it here.
Answer:
In the case of classification, neural networks learn a coordinate system for the target classes which is a nonlinear mapping of the inputs. See: Can't deep learning models now be said to be interpretable? Are nodes features? These are "features" in the sense that they are an abstraction from the input, but they're not really interpretable as some latent phenomenon about the input.
CNNs aren't perfect. For example, small modifications to the image can dramatically shift the classifier's disposition. But CNNs are only useful when the input has some sort of structure to it; for an image, that structure is that nearby pixels comprise an important shape, texture or edge. For a time-series, the structure is that yesterday is more similar to tomorrow than last year. FCNs are useful when the data is "tabular" in format, recording different measurements for an observation which are not related (spatially, temporally, or otherwise).
Comment: what do you mean by CNN is useful when nearby pixels are probably representing the same object?Can you please explain it a bit more? And can we say that we don't learn features in Multi layer network?
Comment: In a natural image, nearby pixels are correlated. CNNs are good at learning filters to detect edges, textures and other structure. These are aggregated up across different image patches. The link in the post develops interpretation of FCN features in more detail.


Disconnected vertical lines with Latex table using booktabs package

Question: I want the vertical lines in my table disconnected like in the example below.

My attempt is getting me vertical lines like in the second table shown below, how can I reproduce the lines like in the example?

This is my code to generate my table
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{multirow}
\usepackage{array}
\usepackage{makecell}
\usepackage[table,xcdraw]{xcolor}
\usepackage{booktabs}
\usepackage{arydshln}

\begin{document}
\begin{table}[h]
\begin{center}
\setlength{\tabcolsep}{8pt}
\renewcommand{\arraystretch}{1.0}
\begin{tabular}{c|cccc}
\toprule
classes  & abs\_rel & a1    & a2    & a3    \\ \midrule
Road    & 0.138               & 0.851          & 0.917          & 0.946 \\ %\hline
Vehicle & 0.135               & 0.855          & 0.920          & 0.948 \\ %\hline
Lane    & 0.135               & 0.855          & 0.920          & 0.947 \\ %\hline
\bottomrule
\end{tabular}
\end{center}
\end{table}
\end{document}

Comment: I've suggested an edit to your question, trying to make it more concise. You're saying, you're using the booktabs package, please expand your code to be a fully working example we can just copy into our local environment to test things. This includes all relevant packages and things like /begin and /end document.
This will make the question easier to understand and answer.
Comment: Do I understand correctly, that you're interested in the disconnected vertical lines?
Comment: Yes, i'm interested in the disconnected vertical lines...
Comment: @yelin2 Are you sure you want to replicate a table in which someone made an error and used the booktabs package incorrectly?
Comment: @samcarter_is_at_topanswers.xyz I haven't been familiar with the booktabs package for a long time yet, so there is still a lot I don't know. If I am misusing the booktabs package, could you tell me which part I am doing wrong? Thank you.
Comment: The person who produced the table with the vertical gaps misused booktabs. I wouldn't recommend to replicate this table. It would look very amateurish if you did this, like you don't know now your way around latex. Make a nice looking table instead.
Comment: If I see the table in your first image, I immediately think "somebody couldn't be bothered to read the booktabs documentation", even before actually looking at the content of your table. Do you want to provoke this reaction from your readers or do you want them to focus on what you are trying to tell them?
Answer: You can replicate the incorrect usage of booktabs with vertical lines if you refrain form loading the arydshln package. This package would fix some of the incompatibilities of booktabs with vertical lines.
However please consider carefully if you really want your table to look like you made an error in coding it. It will look as if you don't know your latex.
\documentclass{article}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{multirow}
\usepackage{array}
\usepackage{makecell}
\usepackage[table,xcdraw]{xcolor}
\usepackage{booktabs}
%\usepackage{arydshln}

\begin{document}
\begin{table}[h]
\begin{center}
\setlength{\tabcolsep}{8pt}
\renewcommand{\arraystretch}{1.0}
\begin{tabular}{c|cccc}
\toprule
classes  & abs\_rel & a1    & a2    & a3    \\ \midrule
Road    & 0.138               & 0.851          & 0.917          & 0.946 \\ %\hline
Vehicle & 0.135               & 0.855          & 0.920          & 0.948 \\ %\hline
Lane    & 0.135               & 0.855          & 0.920          & 0.947 \\ %\hline
\bottomrule
\end{tabular}
\end{center}
\end{table}
\end{document}

Comment: @yelin2 Yes! If you want your table to look professional, I would use `\begin{tabular}{@{}lcccc@{}}`. This will remove the vertical lines and a left aligned first column will look much more calm as the ragged look of a centred column.
Comment: Thank you, I solved the problem by not loading the arydshln package. Then, is it common not to use vertical lines when using the booktabs package?
Comment: Thank you for your help! I won't use booktabs package to draw vertical lines. I will try to use `{@{}lcccc@{}}` as you suggested!
Comment: @yelin2 You're welcome! Your table will look so much better without the vertical line!
Answer: Here's an answer just for completeness. If your goal is to have the same gaps across the table, stick to booktabs.
However, custom gaps can be created without loading booktabs as long as they are added before tabular starts creating a new row. Essentially gaps become a part of a rule, not a part of rows/cells. It is achieved by a TeX primitive \noalign{}; it can only be used between rows! For instance, one can place the following line between rows
% ...
\hline \noalign{\vskip 3pt}
% ...

and get the 3pt skip below the \hline which breaks the vertical bar. Since you have added makecell package, \Xhline{<<rule size>>} is also available. Combined with \noalign{\vskip <<size>>} and you can have custom gaps with custom rules.
Here's the example where I made a convenient macros: \Gap and parametrised \XGap{<<size>>.
\documentclass{article}
\usepackage{makecell}
\NewExpandableDocumentCommand\XGap{m}{\noalign{\vskip #1}}
\NewExpandableDocumentCommand\Gap{}{\XGap{3pt}}

\begin{document}
\begin{table}[h]
  \begin{center}
    \setlength{\tabcolsep}{8pt}
    \renewcommand{\arraystretch}{1.0}
    \begin{tabular}{c | *4{c}}
      \Xhline{0.8pt} \XGap{1pt}
      classes & abs\_rel & a1    & a2    & a3    \\
      \Gap \hline \Gap
      Road    & 0.138    & 0.851 & 0.917 & 0.946 \\
      Vehicle & 0.135    & 0.855 & 0.920 & 0.948 \\
      Lane    & 0.135    & 0.855 & 0.920 & 0.947 \\
      \XGap{1pt} \Xhline{0.8pt}
    \end{tabular}
  \end{center}
\end{table}
\end{document}

The macros can be stack, repeated after each row and used with negative skips to achieve some special effects. For instance, consider this table
\begin{table}[h]
  \begin{center}
    \setlength{\tabcolsep}{8pt}
    \renewcommand{\arraystretch}{1.0}
    \begin{tabular}{c | *4{c}}
      \Xhline{0.8pt} \XGap{1pt}
      classes & abs\_rel & a1    & a2    & a3    \\\Gap
      \hline \Gap
      Road    & 0.138    & 0.851 & 0.917 & 0.946 \\\Gap
      Vehicle & 0.135    & 0.855 & 0.920 & 0.948 \\\Gap
      Lane    & 0.135    & 0.855 & 0.920 & 0.947 \\\Gap\XGap{-2pt}
      \Xhline{0.8pt}
    \end{tabular}
  \end{center}
\end{table}


Como gerar um programa executável em python

Question: Comecei a ver linguagens de programação a um certo tempo, atualmente estou aprendendo Python, JavaScript e outras.
E gostaria de saber como que posso gerar um programa independente do interpretador? Quero dizer, gerar um executável.
Comment: Desculpa, sou novo nesse fórum! Não tinha ideia do que colocar nas tags e coloquei essas daí. Minha dúvida é: como criar um executável em python, por exemplo, que abra fora do editor.
Comment: @RafaelRibeiroSilva O que você quer dizer com "abrir fora do editor"? Não tá fazendo sentido pra mim.
Comment: @MarceloBoni É isso mesmo!
Answer: Dependendo do aplicativo programas como cx_Freeze e PyInstaller costumam ser boas opções para gerar executáveis:
Cx_Freeze
http://cx-freeze.readthedocs.io/en/latest/
PyInstaller
https://pyinstaller.readthedocs.io/en/v3.3.1/
Comment: Ok. Muito obrigado!