text:
Q: The sticky menu prevents the correct scrolling to the text I have image that when user click on element on the image it scrolls down to text.
I have problem , because i have a sticky menu on the top of my website.
How can i solve problem with scroll exacly to text with include stickymenu on me website?
HTML code to example ( without sticky menu) looks like :
<!DOCTYPE html>

<map id="map_ID" name="map">
<area shape="rect" coords="81,79,171,117" href="#1954" />
<area shape="rect" coords="142,146,334,204" href="#1954" />
<area shape="rect" coords="81,235,254,481" href="#1954" />
<area shape="rect" coords="255,234,378,407" href="#1958" />
<area shape="rect" coords="255,514,338,545" href="#1958" />
<area shape="rect" coords="315,427,483,466" href="#1958" />
<area shape="rect" coords="381,229,593,405" href="#1986" />
<area shape="rect" coords="595,243,799,403" href="#1995" />
<area shape="rect" coords="619,513,699,543" href="#1995" />
<area shape="rect" coords="678,430,821,463" href="#1995" />
<area shape="rect" coords="803,243,1058,412" href="#2001" />
<area shape="rect" coords="885,83,965,117" href="#2001" />
<area shape="rect" coords="935,143,1078,167" href="#2001" />
<area shape="rect" coords="1062,243,1288,410" href="#2009" />
<area shape="rect" coords="1135,429,1372,485" href="#2009" />
<area shape="rect" coords="1081,513,1167,541" href="#2009" />
<area shape="rect" coords="1292,236,1494,408" href="#2015" />
<area shape="rect" coords="1345,85,1424,115" href="#2015" />
<area shape="rect" coords="1389,147,1553,204" href="#2015" />
<area shape="rect" coords="1468,511,1548,546" href="#2018" />
<area shape="rect" coords="1498,225,1853,464" href="#2018" />
<area shape="rect" coords="1516,463,1643,486" href="#2018" />
<area shape="rect" coords="1419,411,1495,464" href="#2018" />
<area shape="rect" coords="1422,222,1494,232" href="#2018" />
<area shape="rect" coords="473,87,550,114" href="#1986" />
<area shape="rect" coords="521,147,679,186" href="#1986" />
</map>

Odkrycie bakterii Lactobacillus acidophilus Er-2 317/402.Prof. Levon Akopovich Erzinkyan – naukowiec i wynalazca, dr n. technicznych i biologicznych, twórca Mikrobiologii Technicznej w Armenii – przeprowadza analizę smółki swojej wnuczki, pod kątem obecności bakterii kwasu mlekowego i odkrywa wyjątkowy szczep, wyróżniający się niezwykłą żywotnością i odpornością na antybiotyki, żółć i kwas.

Pierwsze zastosowanie bakterii Lactobacillus acidophilus Er-2 317/402.Wnuczka prof. Erzinkyana trafia do szpitala z powodu ciężkiej infekcji jelitowej. Gdy dziewczynka nie reaguje na leczenie szpitalne, a lekarze rozkładają ręce, nie dając jej szans na przeżycie, prof. Erzinkyan wprowadza do jej leczenia bakterie Lactobacillus acidophilus Er-2 317/402. Dziewczynka zdrowieje, a szczep, który podano zostaje nazwany od jej imienia – Narine. Rok później Rząd Armenii wprowadza ten probiotyk jako obowiązkowy dodatek do mleka na oddziałach neonatologicznych i w przedszkolach. Dzięki niemu mleko staje się wartościowym zamiennikiem naturalnego pokarmu, a karmione nim dzieci nie chorują na schorzenia przewodu pokarmowego, mają lepszą odporność, fizjologię i metabolizm.

Czarnobyl, rekomendacja WHO.Po wybuchu elektrowni jądrowej w Czarnobylu, Lactobacillus acidophilus Er-2 317/402 Narine, zostaje włączony do leczenia osób z dysbiozą. Wyniki badań pokazały, że bakteria przyczynia się do normalizacji flory jelitowej i poprawy stanu zdrowia leczonych osób. Pozytywne wyniki terapii zwracają uwagę Organizacji Zdrowia, która rekomenduje stosowanie szczepu Narine w tak ekstremalnych sytuacjach.

Powstanie zakładu przy Instytucie.Na początku lat 90-tych, młody dr, Dilanyan Edward Karlenovich, staje przed groźbą  poważnej operacji. Chcąc jej uniknąć, chwyta się ostatniej deski ratunku – zaczyna przyjmować Narine w postaci jogurtu (jedynej, dostępnej w tamtym czasie formie). Szybkość i efektywność działania "leku" na tyle go zdumiewa i fascynuje, że postanawia poświęcić się badaniom nad tą niezwykłą bakterią. Otwiera pierwszy na świecie zakład produkujący tabletki z oryginalną bakterią Narine. Zakład Vitaway LLC znajduje się w najbliższym sąsiedztwie Instytutu, w którym od początku przechowywany jest szczep.

Badania w Japonii.Japońscy mikrobiolodzy z Institute Pasteur de Kyoto, przeprowadzają serię badań nad bakterią Lactobacillus acidophilus Er-2 317/402 Narine, odnosząc się do badań z 1987 roku, w których wykazali, że bakteria Narine indukuje produkcję interferonu – naturalnej substancji wytwarzanej przez komórki organizmu, odpowiedzialnej za wytwarzanie przeciwciał w celu zwalczania infekcji.

Ujawnienie informacji o stosowaniu Narine przez radzieckich astronautów.W Wielkiej Brytanii, na jaw wychodzą informacje o stosowaniu Lactobacillus acidophilus Er-2 317/402 Narine przez radzieckich astronautów. Wcześniej, ujawnienie osiągnięć naukowych dotyczących szczepu Narine, nie było możliwe, ponieważ stanowiły one tajemnicę wojskową i były regulowane przez KGB.

Otwarcie zakładu produkcji i innowacji w Japonii.Japończycy postanawiają wprowadzić produkty z bakterią Narine na swój rynek. W porozumieniu z armeńskim Vitaway LLC otwierają w Tokio zakład produkcyjny. Niestety mimo wielu przeprowadzonych badań nad bakterią i podjętych prób produkcji, nie odnoszą sukcesu. W końcu postanawiają zamawiać Narine bezpośrednio z Armenii i tak jest do dzisiaj.

Powstanie polskiej marki NARUM.Michał Toczyłowski, prawnik i przedsiębiorca, szukając ratunku, dla jednego ze swoich synów, u którego zdiagnozowano zwiotczenie mięśni (skutek pewnych działań medycznych), trafia w rosyjskiej literaturze medycznej, na wzmiankę o niezwykłej bakterii Narine. Po wielomiesięcznych poszukiwaniach udaje mu się w końcu nawiązać kontakt z producentem w Armenii. Po doświadczeniu na sobie i najbliższych, niezwykłego działania probiotyku, postanawia sprowadzić te produkty na rodzimy rynek. Tworzy markę Narum i rozpoczyna współpracę z producentem z Armenii.

JSFiddleDemo
Without this sticky menu it works perfect. But how can i do that to scroll good with sticky menu there?
Link  to my website with sticky menu : https://mynarum.com/o-nas

A: The site is scrolling correctly. It must be quite annoying with the navbar...
What you could do is place an empty tag such as div, p, h1, etc and give it the proper id so the page scrolls less.

To 1
To 2

-

Super important text that is blocked by navbar...

A: One thing which you can do is give a class to items of your body which are hiding under menu and calculate the height(margin+ padding+ height) of your fixed menu bar and add padding(padding-top = equal to height of menu bar) on all the elements.


text:
Q: PHP pagination does not change the values on page I have used the php pagination tutorial: http://www.phpeasystep.com/phptu/29.html. And as it said it was easy I did not expect any problems. However, I have encountered one. Now I know for the best results you should see my source code so I shall provide it. The problem is that it queries fine and only displays certain data on the page if the member is right and limits it to only a few per page... However it does not change values when I try to change to see more comments on the next page.
        <?php
        /*  $dbLink = mysql_connect("localhost", "sco0100_james", "creeper");
            mysql_query("SET character_set_results=utf8", $dbLink);
            mb_language('uni');
            mb_internal_encoding('UTF-8');
        */

        include('config.php');  // include your code to connect to DB.

        $tbl_name="commenttable";  //your table name
        $adjacents = 3;

    /*
    First get total number of rows in data table.
    If you have a WHERE clause in your query, make sure you mirror it here.
    */

        $query = "SELECT COUNT(*) as num FROM $tbl_name";
        $total_pages = mysql_fetch_array(mysql_query($query));
        $total_pages = $total_pages[num];

        /* Setup vars for query. */
        $targetpage = "profile.php?id=$id"; //the name of this file
        $limit = 3;             //how many items to show per page
        $page = $_GET['page'];

        if($page)
            $start = ($page - 1) * $limit;
                           //first item to display on this page
        else
            $start = 0;    //if no page var is given, set start to 0

        /* Get data. */
        $sql = "SELECT id, name, comment, member1, member2 FROM $tbl_name WHERE member2='".$id."' ORDER BY id ASC LIMIT $start, $limit";
        $result = mysql_query($sql);

        /* Setup page vars for display. */
        if ($page == 0)
            $page = 1;  //if no page var is given, default to 1.

        $prev = $page - 1;  //previous page is page - 1
        $next = $page + 1;  //next page is page + 1
        $lastpage = ceil($total_pages/$limit);
                    //lastpage is = total pages / items per page, rounded up.
        $lpm1 = $lastpage - 1;  //last page minus 1

    /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case
                    we want to draw it more than once.
    */

        $pagination = "";

        if($lastpage > 1)
        {
            $pagination .= "
";

            //previous button
            if ($page > 1)
                $pagination.= "previous";
            else
                $pagination.= "� previous";

            //pages
            if ($lastpage < 7 + ($adjacents * 2))
                            //not enough pages to bother breaking it up
            {
                for ($counter = 1; $counter <= $lastpage; $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "$counter";
                    else
                        $pagination.= "$counter";
                }
            }

            elseif($lastpage > 5 + ($adjacents * 2))
                             //enough pages to hide some
            {
                //close to beginning; only hide later pages
                if($page < 1 + ($adjacents * 2))
                {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
                    }

                    $pagination.= "...";
                    $pagination.= "$lpm1";
                    $pagination.= "$lastpage";
                }

                //in middle; hide some front and some back
                elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
                {
                    $pagination.= "1";
                    $pagination.= "2";
                    $pagination.= "...";

                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
                    }

                    $pagination.= "...";
                    $pagination.= "$lpm1";
                    $pagination.= "$lastpage";
                }

                //close to end; only hide early pages
                else
                {
                    $pagination.= "1";
                    $pagination.= "2";
                    $pagination.= "...";

                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
                    }
                }
            }

    //next button
    if ($page < $counter - 1)
        $pagination.= "next";
    else
        $pagination.= "next";
        $pagination.= "
\n";
}

    while($row = mysql_fetch_array($result))
    {
        $cname= $row['name'];
        $comment= $row['comment'];
        echo $cname . '
' . '
' . $comment . '
' . '
' . '
';
    }
?>

    <?=$pagination?>

I suspect the problem could be my $targetpage which opens different data for the profile depending on which id it has for each different user. But I do not know how to correct this, or if this is even the problem... can anyone see whats wrong? (FIXED)

A: Yes, $targetpage is incorrect:
 $targetpage = "profile.php?id=$id";

will produce something like profile.php?id=42. You then use that string in your urls:

which gives you the actual generated HTML:

This is incorrect. a query string should have only a SINGLE ?. You need to use & for subsequent parameters, e.g.:

                      ^--- &, not ?

A: Your SQL query should contain a TOP and a LIMIT value, so they you select the range (page) that you intended.  Something similar to this:
$items_per_page = 10;
$query = "SELECT TOP $items_per_page * FROM table LIMIT ". $items_per_page * $REQUEST['page'];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is $F[x]/\langle x^3-1\rangle$ a field? Let F be a field.
Is $F[x]/\langle x^3-1\rangle$ a field?
I know $x^3-1 = (x-1)(x^2+x+1)$. How can I use this to show the above is a field or not?
I am using the above to deduce $\langle x^3-1\rangle$ is maximal or not in $F[x]$.

A:
I am using the above to deduce $\langle x^3-1\rangle$ is maximal in $F[x]$.

This is impossible. Just note that the factorization you mention gives you ideals properly containing this one. Generally, a reducible polynomial cannot yield a prime ideal.

A: You're declaring $x\ne x^2 \ne x^3\ne x$ and $x$ is a cube root of $1$.  The underlying set of this "field" is $\{a+bx+cx^2 : a,b,c\in F\}$.  In this "field" we have
$$
(x-1)(x^2+x+1) = x^3 - 1 = 1-1 = 0,
$$
so we're multiplying two nonzero things and getting zero.  If you can show that that cannot happen in a field, then you have to conclude that this is not a field.

A: Your factorization $x^3-1=(x-1)(x^2+x+1)$ tells you that $\langle x^3-1\rangle\subseteq \langle x-1\rangle$ (which is maximal, but it's irrelevant).
The two ideals are not equal, because $x^3-1$ does not divide $x-1$.

Consider the evaluation map at $a\in F$, defined over polynomials:
$$
v_a\colon F[x]\to F, \qquad v_a(p)=p(a)
$$
This map is a ring homomorphism and is obviously surjective, so its kernel is a maximal ideal. Since $a$ is a root of $p\in F[x]$ if and only if $x-a$ divides $p$, we have that $\ker v_a=\langle x-a\rangle$.


text:
Q: Django CSS Configuration doesn't show expected styling I'm new to Django, and I'm trying to use static files to color my website.
this is my directory hierarchy-

This is the HTML I'm trying to style, by using this code-

This is the CSS code I'm using-

This my settings.py-

No matter what I do, or if I refresh or restart the server completely- nothing happens.
I've watched so many articles and videos related to this, but I still can't figure out what am I doing wrong...
Would appreciate any help :-)

A: I usually add a STATICFILES_DIRS in my settings.py and it works
STATICFILES_DIRS = [
    BASE_DIR / 'to_excel/static'
]

A: The way you try to access the static files is correct. But you need to adjust your settings.py:
# djangotemplates/djangotemplates/settings.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
import os

STATIC_URL = 'static/'

# Add these new lines
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')


text:
Q: Error Spring React REST Controller Using Custom Class Response (WebFlux) I'm trying to build a Spring WebFlux project and realize the follow business logic:
1 - Call an external REST Api using WebClient and parse the Json results using the Models below. It is working OK
2 - To show the Mono results Mono<DeviceList> devices, I'm using the ResponseApi class and returning it, but it is NOT working
I'm getting the follow error:
Response status 406 with reason "Could not find acceptable representation"
Thanks

# Json Result
{
    "data": [
        {
            "id": "5bc3c0efe833d93f401bafa8",
            "name": "XXXXX",
            "group": "5b8fd1fa0499f54cfa7febb8",
            "description": "Geolocalizacao gps",
            "payloadType": "None",
            "contract": "5bc08be5e833d93f40e1f936",
            "keepAlive": 0
        }
    ]
}

# Controller
public class DeviceController{
    ...
    ...

    @RequestMapping(value = V1 + BASE_URL + "/devices/types", method = GET, produces = APPLICATION_JSON)
    public Mono<ServerResponse> getDeviceTypes(){
        Mono<DeviceList> devices = deviceService.findDeviceTypes();

        ResponseApi r = new ResponseApi();
        r.setMessage("Test");
        r.setCode("200");
        r.setStatus(200);
        r.setData(devices);

        return ok().body(Mono.just(r), ResponseApi.class);
    }
}

# Repository
public Mono<DeviceList> findDeviceTypes() {
    return webClient.get()
            .uri(DEVICE_TYPES_URL)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .bodyToMono(DeviceList.class);
}

# Model
public class DeviceList{

    @JsonProperty("data")
    private List<Device> data;

    public List<Device> getData() {
        return data;
    }

    public void setData(List<Device> data) {
        this.data = data;
    }
}

public class Device{

    @JsonProperty("id")
    private String id;

    @JsonProperty("name")
    private String name;

    @JsonProperty("group")
    private String group;

    @JsonProperty("description")
    private String description;

    @JsonProperty("keepAlive")
    private Integer keepAlive;

    @JsonProperty("payloadType")
    private String payloadType;

    @JsonProperty("contract")
    private String contract;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getKeepAlive() {
        return keepAlive;
    }

    public void setKeepAlive(Integer keepAlive) {
        this.keepAlive = keepAlive;
    }

    public String getPayloadType() {
        return payloadType;
    }

    public void setPayloadType(String payloadType) {
        this.payloadType = payloadType;
    }

    public String getContract() {
        return contract;
    }

    public void setContract(String contract) {
        this.contract = contract;
    }
}

@JsonRootName("data")
public class ResponseApi{

    @JsonProperty("status")
    private Integer status;

    @JsonProperty("code")
    private String code;

    @JsonProperty("message")
    private String message;

    @JsonProperty("data")
    private Object data;

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

A: You can get devices, then in non blocking way, map them to the ResponseApi like that:
@RequestMapping(value = V1 + BASE_URL + "/devices/types", method = GET, produces = APPLICATION_JSON)
public Mono<ServerResponse> getDeviceTypes(){
    return deviceService.findDeviceTypes()
            .flatMap(devices -> {
                ResponseApi r = new ResponseApi();
                r.setMessage("Test");
                r.setCode("200");
                r.setStatus(200);
                r.setData(devices);
                return ok().body(Mono.just(r), ResponseApi.class);
            });
}


text:
Q: I am using magento Login code in PopUp and code is not working I am using magento Login code which is to display in a Pop-Up and my code is not working, I wanted to know why it is not working? could anyone help me with this?
The following is my code I am trying with:
    <form action="<?php echo $this->getUrl('customer/account') ?>" method="post" id="login-form">

      <?php echo $this->getBlockHtml('formkey'); ?>

                            New ? Register

<?php echo $this->__('Login in to Your Account') ?>

                                 Close

Username

                            <input type="email" name="login[username]" value="<?php echo $this->escapeHtml($this->getUsername()) ?>" id="email" class="input-text required-entry validate-email" title="<?php echo $this->__('Email Address') ?>" />

Password

                            <input type="password" name="login[password]" class="input-text required-entry validate-password" id="pass" title="<?php echo $this->__('Password') ?>" />

                <?php echo $this->getChildHtml('form.additional.info'); ?>

                                Need help?

                                <button class="login_bttn" type="submit" title="<?php echo $this->__('Login') ?>" name="send" id="send2"><?php echo $this->__('Login') ?></button>

      </form>


text:
Q: Which iCloud tasks are done automatically? I use following method to sync my files with iCloud.
[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:fileURL destinationURL:destURL error:&error

I was wondering when I move a file to Ubiquitous Container How would it behave in another device?
will it be downloaded automatically?
what about deleting and editing files?
Does iCloud do above tasks itself or I should handle them manually?

A: Yes it would be downloaded automatically
But I still wonder about deleting and edidting


text:
Q: Meaning of $\int d^2T$ I was thinking about higher derivatives and was wondering if there is any meaning mathematically behind:
$$\int d^2T$$
where $T$ is a variable or a function, I don't think it matters. If we let $T=f(t)$ then we would get:
$$\frac{d^2T}{dt^2}=\frac{d}{dt}\left[\frac{dT}{dt}\right]$$
However I have still not found anything about if this exists, what it would represent?
Thanks in advance, sorry if this question is vague or unclear


text:
Q: Recorrer Array de fechas y separar secuencias consecutivas en PHP Tengo una array multidimensional de fechas y valores en PHP, el cual necesito separarlo en otro array por rangos consecutivos. Es decir que en el ejemplo debajo, hay dos valores con fechas y necesito separarlo en bloques de fecha consecutivas y su respectivo valor.
    array (
        0 =>
        array (
          'Fecha' => '2021-10-01',
          'Valor' => 10,
        ),
        1 =>
        array (
          'Fecha' => '2021-10-02',
          'Valor' => 10,
        ),
        2 =>
        array (
          'Fecha' => '2021-10-03',
          'Valor' => 10,
        ),
        3 =>
        array (
          'Fecha' => '2021-10-04',
          'Valor' => 10,
        ),
        4 =>
        array (
          'Fecha' => '2021-10-06',
          'Valor' => 10,
        ),
        5 =>
        array (
          'Fecha' => '2021-10-08',
          'Valor' => 10,
        ),
        6 =>
        array (
          'Fecha' => '2021-10-01',
          'Valor' => 20,
        ),
        7 =>
        array (
          'Fecha' => '2021-10-02',
          'Valor' => 20,
        ),
        8 =>
        array (
          'Fecha' => '2021-10-03',
          'Valor' => 20,
        ),
      )

El resultado esperado debería ser otro array multidimensional como el que se muestra debajo.  Separando las fechas en bloques de inicio fin y valor.
array (
    array (
      'FechaInicio' => '2021-10-01',
      'FechaFin' => '2021-10-04',
      'Valor' => 10,
    ),
    array (
      'FechaInicio' => '2021-10-06',
      'FechaFin' => '2021-10-06',
      'Valor' => 10,
    ),
    array (
      'FechaInicio' => '2021-10-08',
      'FechaFin' => '2021-10-08',
      'Valor' => 10,
    ),
    array (
      'FechaInicio' => '2021-10-01',
      'FechaFin' => '2021-10-03',
      'Valor' => 20,
    )
)

Desde ya muchas gracias.

A: Una forma de resolver esto sería usando un iterador, el cual te permitirá con mayor facilidad guardar una referencia del elemento previo y del que le sigue, para poder hacer las comparaciones.
Aquí un código funcional, asumimos que tu array inicial se llama $origin  (cámbialo por su nombre real).
He comentado lo que se ha ido haciendo, para que puedas entenderlo:
$obj = new ArrayObject( $origin );
$it = $obj->getIterator();
$i=0;
while( $it->valid() )
{
    #Referencia al elemento actual
    $current=$it->current();
    #Avanzamos el iterador
    $it->next();
    #Referencia al siguiente elemento
    $next=$it->current();

    #Si $outPut[$i] no existe lo creamos
    if(empty($outPut[$i])) {
        #Asignamos FechaInicio
        $outPut[$i]['FechaInicio']=$current['Fecha'];
    }

    #Creamos dos objetos DateTime para ver la diferencia en días
    $currentDate=new DateTime($current['Fecha']);
    $nextDate=new DateTime($next['Fecha']);
    #Creamos un intervalo entre las dos fechas
    $interval = $currentDate->diff($nextDate);
    #Verificamos si el intervalo es de más de un día
    if($interval->days > 1) {
        #Asignamos FechaFin y Valor y cambiamos de índice
        $outPut[$i]['FechaFin']=$current['Fecha'];
        $outPut[$i]['Valor']=$current['Valor'];
        $i++;
    }
}
var_dump($outPut);

Salida:
array(4) {
  [0]=>
  array(3) {
    ["FechaInicio"]=>
    string(10) "2021-10-01"
    ["FechaFin"]=>
    string(10) "2021-10-04"
    ["Valor"]=>
    int(10)
  }
  [1]=>
  array(3) {
    ["FechaInicio"]=>
    string(10) "2021-10-06"
    ["FechaFin"]=>
    string(10) "2021-10-06"
    ["Valor"]=>
    int(10)
  }
  [2]=>
  array(3) {
    ["FechaInicio"]=>
    string(10) "2021-10-08"
    ["FechaFin"]=>
    string(10) "2021-10-08"
    ["Valor"]=>
    int(10)
  }
  [3]=>
  array(3) {
    ["FechaInicio"]=>
    string(10) "2021-10-01"
    ["FechaFin"]=>
    string(10) "2021-10-03"
    ["Valor"]=>
    int(20)
  }
}


text:
Q: How can I get fields from one object and add them to another in Javascript? I have the following:
$scope.book1 = {
  a = 1,
  b = 2
}

I'm getting this from my database:
$scope.book2 = {
  title = 2,
  author = 'joe'
}

How can I update the book1 object with the data from book2 so that it has all four fields?
Note that my users are using IE9 and above. If it's possible I would like to use lodash but I'm not sure that's possible as I want the result to go into the book1 object and not to create a new object.

A: If you need to create your extend function
Object.prototype.extend = function(x) {
    for(i in x)
        this[i] = x[i];
};

$scope.book1.extend($scope.book2);

If you are using angularjs you can have a look at http://docs.angularjs.org/api/angular.extend

A: angular.extend($scope.book1, $scope.book2);


text:
Q: Get attributes for class and instance in python In python work next code:
class MyClass(object):
    field = 1

>>> MyClass.field
1

>>> MyClass().field
1

When I want return value for custom fields I use next code:
class MyClass(object):
    def __getattr__(self, name):
       if name.startswith('fake'):
           return name
       raise AttributeError("%r object has no attribute %r" %
                            (type(self).__name__, name))

>>> MyClass().fake
fake

But:
>>> MyClass.fake
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class MyClass has no attribute 'fake'

Ok, for classes I can use next code:
class MyClassMeta(type):
    def __getattr__(cls, name):
       if name.startswith('fake'):
           return name
       raise AttributeError("%r object has no attribute %r" %
                            (type(self).__name__, name))

class MyClass(object):
    __metaclass__ = MyClassMeta

>>> MyClass.fake
fake

But:
>>> MyClass().fake
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'fake'

To resolve this problem I use next code:
class FakeAttrMixin():
   def __getattr__(self, name):
       if name.startswith('fake'):
           return name
       raise AttributeError("%r object has no attribute %r" %
                            (type(self).__name__, name))

class MyClassMeta(type, FakeAttrMixin):
    pass

class MyClass(object, FakeAttrMixin):
    __metaclass__ = MyClassMeta

>>> MyClass.fake
fake

>>> MyClass().fake
fake

MyClass.fake will call __getattr__ with MyClass and fake arguments.
MyClass().fake will call __getattr__ with MyClass instance and fake arguments.
And it's ok if I implement __getattr__ logic only on my mixin and don't use self argument.
Can I write custom value resolving by class and instance more beautiful and why field value resolving for MyClass.field and MyClass().field with MyClass(object): field = 1 definition works different if compare with __getattr__ method? Because when I want get field it at first searching in instance, then in class, but I can't understand why __getattr__ works another way.
Similar questions: __getattr__ on a class and not (or as well as) an instance and Difference between accessing an instance attribute and a class attribute.

A: No, if you have to support both arbitrary attribute lookup on the class as well as the instance, then your only option is to implement a __getattr__ hook method on both the metaclass and the class, one each to support lookups on the class and the instance.
This is because special hook methods are always looked up on the type, so type(obj).__getattr__. Hence, for MyClass.fake the metaclass __getattr__ is used. See Special method lookup for new-style classes; I explained why this is in a previous answer.
The short reason is that in your case, MyClass.fake would translate into MyClass.__getattr__('fake') and __getattr__ is then an unbound method expecting two arguments (self and name), which would fail.


text:
Q: Best way to manage updates on an iOS client/server app I have a logistical question: I'm trying to figure out the best way to manage APIs getting out of sync with an app.  The best way to explain it is with an example:
Let's say MyApp Version 1.0 posts to a "submit_feedbacK" API that requires first_name, last_name, and email.
I then submit MyApp Version 2.0 to the App Store.  That version is designed to post first_name, last_name, gender, and email to the API.  All of these are required fields on the API.
The problem I have:
- If I update the API before the new App is live, it will break Version 1.0
- If I wait until Version 2.0 is live and remotely cripple 1.0, I have to time it correctly.
I'm going to guess that the 'right answer' is to maintain two different APIs.  But if both APIs post to the same live database, that makes things a bit awkward.
Does anyone have suggestions on how to model this?

A: This question may share some aspects with iOS consuming API design.
The right answer is definately to provide two APIs (at least for a short period of time while users adjust). You do not have to maintain two versions at the same time, as once a newer version is released you can maintain that one, and simply provide the old one for legacy users. The only real changes you may have to make to it are things like security patches or major issues. Major changes (such as you deciding to restructure your entire database) may lead to the old version not working any more, however update to newer API versions should be designed to allow previous versions to still function.
The other question I linked you to gives an answer about how you can have different version of your app access the correct version of the API.
Another note is that it may be easier for you (depending on what framework you're using) to design your APIs as engines or subapps, and simply mount them at different end points. I know that this is easily do-able in Rails by using Engines, and in Node with Express using app.use() with sub-applications.

A: I would use a webservice/http endpoint for the communcation with your app. If you preferer to maintain the same URL in all versions of the app, then include a version number in all the requests/posts to the server so it knows how to handle them. This will also make the development and tests easier as new versions can test against the new api on the server.
So on any function you can call in the webservice/server add a single variable with version number. a BYTE ought to be enough as I think you could start over and "kill support for v1.0" once you hit 256 versions of the same function (if ever).
Once the server receives a request/post with data, you can just code a simple switch/case structure in the server API so support works for both versions.
If they do similar, but eg. swaps the parametres or something, you can handle all these serverside and the BAL/DAL (n-tier structure) can be maintained on the server part of the solution.
Btw. my answer is not just for iOS or smartdevices, but merly a client/server approach for a "work-in-progress" production setup where everything has to be online, while still being under development and maintanance.
Hope it makes sense, otherwise, comment on it and I shall try to explain it further.

A: just FYI, I use CodeIgniter.  I'm using the REST Controller provided at https://github.com/philsturgeon/codeigniter-restserver.  I ultimated ended up settling on having different end-points for every version.  Basically I'd check out a new repository for each release and put it into a unique directory.  (i.e. http://www.mysite.com/1.0/api/method, http://www.mysite.com/1.1/api/method, etc)  Trying to maintain multiple versions of an API under one code-base just sounded too scary.  At least when I released a version, I would know it is locked in stone and I don't have to worry about breaking it.  (Note: I had to use a special .htaccess tweak to get multiple CodeIgniter instances running from the same domain.  I can share it if you like)


text:
Q: htaccess - restrict access unless from these 3 IP addresses I am trying to restrict my website whilst i am developing on it for all IP addresses except 3 in particular. In my htaccess file i have the following but I have just tried accessing on a different IP and it is not restricting it
## Restrict IP access
Order Deny,Allow
Deny from all
Allow from XX.XXX.XX.XXX
Allow from XX.XXX.XX.XXX
Allow from XX.XXX.XX.XXX

I've also tried the following which allows the first line but 403's the other 2 which suggests i can restrict/allow IP's it's just the code or order that is the issue?
<Limit GET POST>
 order deny,allow
 deny from all
 allow from XX.XXX.XX.XXX
 allow from XX.XXX.XX.XXX
 allow from XX.XXX.XX.XXX
</Limit>

A: Try to reload Apache Configuration and check configuration using apachectl. Use command as:
    apachectl configtest
Once done with that, restart apache server or reload configuration. Command is:
    service httpd reload
OR
    service httpd restart
Also make sure that mod_authz_host is enabled in Apache Configuration. If all fails, use IP Tables to control entries.


text:
Q: SVG в WPF, в image? Нужно отобразить svg в WPF. Нашел видео https://youtu.be/RHZXc62YWzE  где сказано что все ок просто юзайте IMAGE... но у меня чтото не работает. Может кто сталкивался ?

A: Возможно видео старое, сейчас в лоб не поддерживается SVG. Есть NuGet пакет SharpVectors. С ним просто используете в XAML SvgViewbox.


text:
Q: React Native Possible Unhandled Promise Error with axios I am trying to fetch two different api with axios and use it on different flatlist
I'm getting this error:
[Unhandled promise rejection: Error: Request failed with status code 429]
Possible Unhandled Promise Rejection (id: 28)
Here's the my code
 const [data, setData] = React.useState([]);
 const [data1, setData1] = React.useState([]);

 axios.all([
        axios.get('https://jsonplaceholder.typicode.com/nation'),
        axios.get('https://jsonplaceholder.typicode.com/state')
      ])
      .then(responseArr => {
        setData(responseArr[0].data);
        setData1(responseArr[1].data);
      });

  return (
      <View style={styles.container}>

            <View >
                <FlatList
                    data={data}
                    listKey="nation"
                    keyExtractor={item => item.id}
                    showsVerticalScrollIndicator = {false}
                    renderItem={({item}) => {
                        return (
                            <View>
                                <Text>{item.event_id}</Text>
                            </View>
                        )
                    }}
                />
            </View>

            <View style={{ marginTop: 30 }}>
                <FlatList
                    data={data1}
                    listKey="state"
                    keyExtractor={item => item.id}
                    showsVerticalScrollIndicator = {false}
                    renderItem={({item}) => {
                        return (
                            <View>
                                <Text>{item.venue_id}</Text>
                            </View>
                        )
                    }}
                />
            </View>

      </View>
  );
};

Thank for your help

A: You are receiving a HTTP 429 error code which means:

The HTTP 429 Too Many Requests response status code indicates the user has sent too many requests in a given amount of time ("rate limiting").

You are calling the API too many times, what's happening is:

*

*axios is called.

*setData() is executed and your state variable updates.

*The rerender is causing axios to run again.

*Congratulations, you're now in a loop!

Refactor your code to only run the API call at appropriate times. Something like this:
useEffect(() => {
   axios.all([
        axios.get('https://jsonplaceholder.typicode.com/nation'),
        axios.get('https://jsonplaceholder.typicode.com/state')
      ])
      .then(responseArr => {
        setData(responseArr[0].data);
        setData1(responseArr[1].data);
      });
}, []); // Ensure any dependencies are added here.

For good measure you should also handle the rejection, which is what the original error is mentioning.
axios.all().then().catch() - You're missing a catch statement.

For the question in the comments, you need to use back ticks when interpolating strings.
<Image
  source={{
    uri: `https://jsonplaceholder.typicode.com/nation/image/${item.nation_image}`
  }}
/>


text:
Q: How can I import modules onto Webpack? I have installed webpack to use with Flask. When my app.js file looks like this:
import "../styles/index.scss";
import "bootstrap/dist/js/bootstrap.bundle";
import "../components/sidebar";

window.document.addEventListener("DOMContentLoaded", function () {
  window.console.log("dom ready 12");
  console.log("Ggg");
});

everything works normally. But when I add
import "jquery/dist/jquery.min.js";

Then this file is not read anymore, eventhough the webpack watch process isn't throwing any errors. I know the file is not read because the console logs I run in it no longer appear in the browser console. Why is that?
Tried various variations of the import code:
import * as $ from 'jquery';
window.$ = $;

import * as $ from 'jquery/dist/jquery.min';
window.$ = $;

import * from "jquery/dist/jquery.min.js";

Etc. But I can't seem to find the right one.
EDIT:
I have also tried using the Provide Plugin (as suggested in the first Answer below, see my comment there), however to no avail.
This is how my webpack.common.js file looks like:
const glob = require("glob");
const Path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const WebpackAssetsManifest = require("webpack-assets-manifest");

const getEntryObject = () => {
  const entries = {};
  glob.sync(Path.join(__dirname, "../src/application/*.js")).forEach((path) => {
    const name = Path.basename(path, ".js");
    entries[name] = path;
  });
  return entries;
};
var webpack = require("webpack");

module.exports = {
  entry: getEntryObject(),
  output: {
    path: Path.join(__dirname, "../build"),
    filename: "js/[name].js",
    publicPath: "/static/",
    assetModuleFilename: "[path][name][ext]",
  },
  optimization: {
    splitChunks: {
      chunks: "all",
    },

    runtimeChunk: "single",
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    new CopyWebpackPlugin({
      patterns: [
        { from: Path.resolve(__dirname, "../vendors"), to: "vendors" },
      ],
    }),
    new WebpackAssetsManifest({
      entrypoints: true,
      output: "manifest.json",
      writeToDisk: true,
      publicPath: true,
    }),
  ],
  resolve: {
    alias: {
      "~": Path.resolve(__dirname, "../src"),
    },
  },
  module: {
    rules: [
      {
        test: /\.mjs$/,
        include: /node_modules/,
        type: "javascript/auto",
      },
      {
        test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
        type: "asset",
      },
    ],
  },
};

Relevant lines in my HTML code are:
{{ javascript_pack('app', 'app2', attrs='charset="UTF-8"') }}
<script>$('#my-select')</script>

manifest.json:
{
  "app.css": "/static/css/app.css",
  "app.js": "/static/js/app.js",
  "app2.js": "/static/js/app2.js",
  "entrypoints": {
    "app": {
      "assets": {
        "js": [
          "/static/js/runtime.js",
          "/static/js/vendors-node_modules_bootstrap_dist_js_bootstrap_bundle_js-node_modules_jquery_dist_jquery_js.js",
          "/static/js/app.js"
        ],
        "css": [
          "/static/css/app.css"
        ]
      }
    },
    "app2": {
      "assets": {
        "js": [
          "/static/js/runtime.js",
          "/static/js/app2.js"
        ]
      }
    }
  },
  "js/vendors-node_modules_bootstrap_dist_js_bootstrap_bundle_js-node_modules_jquery_dist_jquery_js.js": "/static/js/vendors-node_modules_bootstrap_dist_js_bootstrap_bundle_js-node_modules_jquery_dist_jquery_js.js",
  "runtime.js": "/static/js/runtime.js",
  "vendors/.gitkeep": "/static/vendors/.gitkeep",
  "vendors/images/.gitkeep": "/static/vendors/images/.gitkeep",
  "vendors/images/sample.jpg": "/static/vendors/images/sample.jpg",
  "vendors/images/webpack.png": "/static/vendors/images/webpack.png"
}

A: Unfortunately, jQuery is one of those plugins that get messed up in webpack's bundling process.
The recommended (and easiest) way to get jQuery working is to use the ProvidePlugin.
Inside your webpack.config.js, add the following block to the plugins array -
new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
});

If you don't have a plugins array, just add the array as follows -
... // other configurations
plugins: [
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
    });
],

Edit 1: Try using cacheGroups inside splitChunks as follows -
splitChunks: {
  cacheGroups: {
    vendor: {
      test: /node_modules/,
      name: "vendor",
      chunks: "all",
      enforce: true,
    },
  },
},

This will ensure that ONE vendor.js file is created - hopefully the manifest file and/or browser won't have a tough time importing that file.
Edit 2: Switch to url_for() to possibly fix it.
<script src="{{ url_for('static', filename='js/vendor.js') }}"></script>
<script src="{{ url_for('static', filename='js/runtime.js') }}"></script>
<script src="{{ url_for('static', filename='js/app.js') }}"></script>
<script src="{{ url_for('static', filename='js/app2.js') }}"></script>


text:
Q: Can't return namespace from SimpleXML I am creating a new xml document from scratch using a google defined format and SimpleXML. I'm having problems getting it to return namespaced tags. To test, I wrote this:
<?php

  $output_xml = new SimpleXMLElement('<?xml version="1.0" ?> <rss xmlns:g="http://base.google.com/ns/1.0" version="2.0"><channel></channel></rss>');

  var_dump($output_xml->getNameSpaces(TRUE));

which returns this:
array(0) {
}

What am I doing wrong? I'm running PHP version 5.3.3.

A: you haven't used any of the namespaces defined. if you add your "g" namespace to "channel" then you will get http://base.google.com/ns/1.0
$output_xml = new SimpleXMLElement('<?xml version="1.0" ?> <rss xmlns:g="http://base.google.com/ns/1.0" version="2.0"><g:channel></g:channel></rss>');

var_dump($output_xml->getNameSpaces(TRUE));


text:
Q: How to call angular service from SlickGrid custom editor How to call angular service from slickgrid custom cell editor.
Below link is mentioned that describes the slickgrid custom cell editor.
https://github.com/mleibman/SlickGrid/wiki/Writing-custom-cell-editors
function IEditor(args) {
    this.applyValue = function(item,state) {

    // Unable to get the service in the editor context.
    // this.testService is undefined.
    this.testService.getDetails(itemId).get(result =>{
       console.log(result );
    });
  };
}

I am facing an issue to get the service in the editor context. I tried with this and self but no success.

A: the second .this doesn't have the same context of the wrapper function. You should write it like this:
 function IEditor(args) {

  var that = this;
  this.applyValue = function(item,state) {

  // Unable to get the service in the editor context.
  // this.testService is undefined.
  that.testService.getDetails(itemId).get(result =>{
     console.log(result );
  });
 };
}

or if you are using ES6:
 function IEditor(args) {

  this.applyValue = (item,state) => {

  // Unable to get the service in the editor context.
  // this.testService is undefined.
  this.testService.getDetails(itemId).get(result =>{
     console.log(result );
  });
 };
}


text:
Q: Check if the user is moving the map in Bing Maps I'm trying to work with Bing Maps in WPF, but everything is confusing as searching online leads me to false hope. I'll search for something, but get the AJAX version instead of the WPF version. If anyone can point me to proper documentation or help with this issue then I will be forever in their debt.
I have a map in my WPF app that I would like to track when a user is scrolling. I tried tying the map to the DragEnter event, but that didn't do anything. My question is if there is an event that I can use to check if the user is panning or zooming through the map?
Thanks in advance.

A: The event ViewChangeOnFrame seems to do what you want.
See Handing Map Events
<m:Map ViewChangeOnFrame="MyMap_ViewChangeOnFrame" ...>

From MSDN

Assuming you have a TextBlock element named CurrentPosition defined in
  the XAML design code, you can track the current position of a map view
  while it is animating between locations. This code tracks the
  position, in latitude and longitude, of the northwest and southeast
  corners of the bounded map view.

void MyMap_ViewChangeOnFrame(object sender, MapEventArgs e)
{
    //Gets the map that raised this event
    Map map = (Map) sender;
    //Gets the bounded rectangle for the current frame
    LocationRect bounds = map.BoundingRectangle;
    //Update the current latitude and longitude
    CurrentPosition.Text += String.Format("Northwest: {0:F5}, Southeast: {1:F5} (Current)",
                bounds.Northwest, bounds.Southeast);
}


text:
Q: How to make real time notifications from DB to local computer I'm doing a web page, where you can sign to subscribe list, to get notifications about some news. Everything works, but i want to change something. When i enter an email, and submit it, i'm getting redirect to a new page (email.php), where I'm getting an alert that inform me, if email has been added to database where I store all emails. I want to do the same alert without refreshing page ( make alerts on the same site as we include email )
I've been doing this on AJAX, but I'm not very good at JavaScript ( I'm kinda new in JS ). I think I might did something wrong, but I couldn't see it.
Below is some code
//HTML
<form method="POST" action="email.php" name="email-db" id="email-db">
                    <input type="email" class="email" name="email" placeholder="Enter your email">
                    <button  type="submit" class="submit" >➤</button>
                </form>

//PHP
<?php
    $email = filter_input(INPUT_POST, 'email');
    if (!empty($email)){
        $host = "localhost";
        $dbusername ="root";
        $dbpassword ="";
        $dbname = "email";
        $alert1 = "<script type='text/javascript'>alert(\"Email has been written to subscribe list!\");</script>";
        $alertredirect = "<script type='text/javascript'>
           window.location = 'index.html'
      </script>";
        $alert2 = "<script type='text/javascript'>alert(\"Your email is already on our subscribe list!\");</script>";

        $conn = new mysqli ($host,$dbusername, $dbpassword , $dbname);
        if (mysqli_connect_error()){
            die('Connection problem('.mysqli_connect_errno().')'.mysqli_connect_error());
        }
        else{
            $sql = "INSERT INTO `email` (`email_id`, `email`) VALUES (NULL, '$email');";
            if ($conn->query($sql)){
                echo "$alert1";
                echo "$alertredirect";
            }
            else{
                echo "$alert2";
                echo "$alertredirect";
            }
            $conn->close();
    }}
?>

As you can see ( on email.php ) I did redirects - but as I said - all of this alerts need to happens on index.html - without refreshing or redirecting.
Thanks for support

A: *

*Change your submit button to a type=button so it doesn't submit the form and do a postback (there are other methods)

*Remove javascript/html from your php handler and return data, eg a simple true/false

*add a js click event handler that calls $.ajax,
eg:
$("button.submit").click(function() {
    $.ajax({
        type: "POST",
        url: your_url,
        data: { email: $(".email").val() },
        success: function(result) {
            alert(result ? "Email saved" : "Already exists");
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error(errorThrown);
        }
    });
});

A: <form method="POST" action="email.php" name="email-db" id="email-db">
 <input type="email" class="email" name="email" placeholder="Enter your email">
 <button  type="submit" class="submit" >➤</button>
</form>
let form = document.querySelector("form");
form.addEventListener("submit", (event)=>{

   // This will help you to diable the defaut property of the form, And stops refresing on the submit

   if(event && event.preventDefault){
      event.preventDefault();
   }

   let formData = new FormData(form)

   //This code will iterate data from the input elements from your form
   let postData = {};

   for(let [key, val] of formData.entries()){
    if(val) postData[key] = val;
   }

   postData(event.target.action, postData)
  .then(data => console.log(JSON.stringify(data)))
  .catch(error => console.error(error));
})

function postData(url = '', data = {}) {
  // Default options are marked with *
    return fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, cors, *same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
            'Content-Type': 'application/json',
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrer: 'no-referrer', // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(response => response.json()); // parses JSON response into native Javascript objects
}

After this will post data to the server for your use and then you send data back to you call.

A: This should work perfectly for you:
FRONT-END (JAVASCRIPT)
In the front-end, you can use AJAX to send your request like this:
$(document).ready(function(){
      $('#email-db').on('submit', function(){
           let email = $('.email').val();
           $.ajax({
              url: "email.php"
              type: 'post',
              data: { 'email': email },
              success: function(response){
                 alert(response);
              }
           });
       });
}

SERVER-SIDE (PHP)
In the server-side, you can use PHP to return your alert message
<?php
    if (isset($_POST['email']) && !empty($_POST['email'])) {
        $host = 'localhost';
        $dbusername = 'root';
        $dbpassword = '';
        $dbname = 'email';
        $alert1 = 'Email has been written to subscribe list';
        $alert2 = 'Your email is already on our subscribe list';
        $conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
        if (mysqli_connect_error()) {
            die('Connection problem('.mysqli_connect_errno().')'.mysqli_connect_error());
        } else {
            $sql = "INSERT INTO `email` (`email_id`, `email`) VALUES (NULL, '$email');";
            return $conn->query($sql) ? $alert1 : $alert2;
        }
    }
?>


text:
Q: Создать торрент файл У меня есть сервер Apache на котором лежит картинка. Нужно создать торрент файл, который начал бы раздачу этой картинки.
Мне не нужен торрент трекер. Я просто хочу раздавать файл с сервера.

A: Самый простой способ: создать .torrent файл с помощью клиента на своем компьютере (имея копию файлов с сервера на компьютере) и указать веб-сид.
В программе qBittorrent это делается так:

После этого файл будет доступен к скачиванию через торрент с сервера с помощью .torrent файла, а так же будет распространятся в сети DHT и позже пользователи смогут скачивать файл у других пользователей сети, которые уже скачали файл.

A: Делать такие вещи с помощью скриптовых языков несколько странно, ведь есть специально предназначенные для этого программы. Например:
sudo apt install ctorrent

Затем:
ctorrent -t -u udp://tracker.open-internet.nl:6969/announce -s example.tar.torrent example.tar

Эту команду можно завернуть в exec() если совершенно необходимо делать из PHP.
Это половина задачи. Вторая половина - раздавать этот файл. Для этого не нужен PHP, а нужно настроить консольный клиент:
sudo apt install rtorrent screen

Затем:
screen rtorrent example.tar.torrent

И Ctrl+A D чтобы вернуться в консоль. Ваш файл раздается на весь интернет.
Можно научить rtorrent автоматически подхватывать .torrent файлы из какого-то каталога, начиная раздачу. Кроме того, для rtorrent есть множество видов веб-GUI на любой вкус и цвет.
В итоге можно сделать так чтобы для каждого из файлов в каталоге создавался .torrent, затем автоматически раздавался. Apache здесь нужен лишь чтобы показать список .torrent файлов. PHP не нужен вообще.
Пожалуйста, четкий порядок действий, от создания торрент файла, до раздачи его по сети - прямо перед вами.

A:
Нужно создать торрент файл, который начал бы раздачу этой картинки.

Три варианта создания торрент файла.
Начнем с установки нужных пакетов в composer:

*

*Установить composer

*composer require coldwinds/torrent-rw

*Добавить в файл require_once("vendor/autoload.php");

*php -f your-file.php
   <?php
    require __DIR__ . '/vendor/autoload.php';
    // create torrent массив файлов или файл,
    // URL optional: http://torrent.tracker/annonce
    $torrent = new Torrent( array('you-image.jpg' ), 'http://torrent.tracker/annonce' );
    $torrent->save('test.torrent'); // save to disk
 // На этом в принципе создание торрент файла закончено
 // если поместить его в директорию, которая доступна из вне, то
 // теоритически можно раздавать...
 // практически придется выбирать трекер из возможных списков
 //----------------------------------------------------------------
 // Если хочется вывести в браузер информацию о созданном файле
  // get torrent infos
  $torrent = new Torrent( './test.torrent' );
echo '
private: ', $torrent->is_private() ? 'yes' : 'no',
     '
annonce: ', $torrent->announce(),
     '
name: ', $torrent->name(),
     '
comment: ', $torrent->comment(),
     '
piece_length: ', $torrent->piece_length(),
     '
size: ', $torrent->size( 2 ),
     '
hash info: ', $torrent->hash_info(),
     '
stats: ';
   var_dump( $torrent->scrape() );
   echo '
content: ';
   var_dump( $torrent->content() );
   echo '
source: ',
     $torrent;

// get magnet link
$torrent->magnet(); // use $torrent->magnet( false ); to get non html encoded ampersand

torrent-rw док

Ещё одни вариант создания торрент файла php: >=5.3.2:
Команда:
composer require christeredvartsen/php-bittorrent

Файл:
  <?php
    $torrent = PHP\BitTorrent\Torrent::createFromPath('/path/to/files', 'http://tracker/announce.php');

    $torrent->setComment('Some comment')
            ->save('/save/to/path/file.torrent');

php-bittorrent док

Ещё один пример php: >=7.1:
Команда:
composer require sandfoxme/torrent-file

Файл:
 <?php

 require __DIR__ . '/vendor/autoload.php';

 use SandFoxMe\Torrent\TorrentFile;

 $torrent = TorrentFile::fromPath('/home/user/your-file.jpg');
 $torrent->store('your-file.torrent');

torrent-file док


text:
Q: Hierarchical clustering plot with high dimensional dataset I am trying to visualize clusters within a chart. After trying to understand which model is best I end up using a hierarchical clustering. My dataset is pandas dataframe with products in index and ticket in columns. Values are a count of product so that each ticket (imagine a client) buy a set of products.
dataset sample:
           ticket1 ticket2 ticket3
product 1       3        2       6
product 2       8        0       2
product 3       0        10      1

I could follow a lot of tutorial explaining hierarchical indexing such as https://www.kaggle.com/heeraldedhia/hierarchical-clustering-for-customer-data
But there is something I am missing as the cluster representation in chart is always picking up some columns which represent for example the age and salary. I don't want to pick up a ticket in my case. I don't care about the ticket and I want to have an overall representation of the PRODUCTS clustered within a chart. Is there a way to come up with this in hierarchical clustering?
FYI my code:
data = data
lt.figure(1, figsize = (16 ,8))
dendrogram = sch.dendrogram(sch.linkage(data, method  = "ward"))

plt.title('Dendrogram')
plt.xlabel('product')
plt.ylabel('Euclidean distances')
plt.show()

hc = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage ='average')

y_hc = hc.fit_predict(data)
y_hc

data['cluster'] = pd.DataFrame(y_hc)


text:
Q: Grails: Refresh view after submit I've seen various answers to similar questions, but not for this specific case:
I have a Grails gsp with several fields and a submit button. I want to enter a value in the first field, click submit, and have the controller return values into the remaining fields (including the original entry field). I want to do this with a simple page refresh (no AJAX) and it does not involve a database. I have it working fine with two gsp pages that are identical but have different names. I just call the first one, enter the value, and have the submit action point to the second. But I would like to be able to do it with a single gsp. A simplified version of my controller looks like this:
class CalculatorController {

    def index = {
    redirect(action: "input")
    }

    def input= {}

    def calculateValues = {

        def inputString = params.enterValue
        def value2 = 'You entered something on the page'
        [field1: inputString, field2: value2]
   }
}

A: you need to have all of logic inside of the same closure if you want to use only one gsp. Test if the params are passed in and return the correct vals

A: Actually you don't need to have all of your logic in the same closure.  Simply specify the view template to use in calculateValues...
def calculateValues = {
  def inputString = params.enterValue
  def value2 = 'You entered something on the page'
  render(view: 'input', model: [field1: inputString, field2: value2])
}

By using the render method you can have multiple controller action reuse the same gsp view.


text:
Q: removing a view controller on click of a button I am developing a library for a iOS app that will authenticate the users on the basis of the credential entered by them.
What I am doing is that, from a view controller say TestViewController I am setting a new view controller LoginScreenViewController on top of TestViewController when user taps a button by using the following code.
LoginScreenViewController * LoginScreen = [[LoginScreenViewController alloc] initWithNibName:nil bundle:nil];

[self.view addSubview:LoginScreen.view];

This LoginScreenViewController contains a Cancel button, on which I want to remove the LoginScreenViewController. For this I am using following code
[self.view removeFromSuperview];

the problem is when I am executing this code, my app is crashing.
Since my LoginScreenViewController is defined by the Library, I want it to be independent of the caller's implementation.
EDIT:
In LoginScreenViewController.m I have used following code to add an event handler to the cancel button.
[button addTarget:self action:@selector(CancelButtonHandler:) forControlEvents:UIControlEventTouchUpInside];

The app is crashing when I am tapping the Cancel button. Even if the CancelButtonHandler does not contain any line of code.

A: You are trying to remove wrong view. To remove LoginScreen view do:
[LoginScreen.view removeFromSuperview];


text:
Q: How can I force the UIInterpolatingMotionEffect to refresh the views without the device being moved? I use a vertical and horizontal UIInterpolatingMotionEffect for each view in my app.
_horizontalEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
_verticalEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];

The .minimum and .maximum relative values are relative to the view's size and change each time the size of the view changes.
_horizontalEffect.minimumRelativeValue = @(size.width / 10.0);
_horizontalEffect.maximumRelativeValue = @(-size.height / 10.0);
_verticalEffect.minimumRelativeValue = @(size.width / 10.0);
_verticalEffect.maximumRelativeValue = @(-size.height / 10.0);

The user can change the size of the view by using a UISlider. Also, he can do a lot of view.center changes on all the views without the device being moved.
The problem is that if the device doesn't move the views are not updated according to UIInterpolatingMotionEffect and they look misaligned.
How can I force the UIInterpolatingMotionEffect to refresh the views without the device being moved?
Maybe, I'm asking the wrong question but I really need some guidance here.


text:
Q: Changing a value in a column to another from the same column I have a table named titles with 3 columns named titleID, price, and pubDate
I've been trying to change the price of a row to the same price as the row with the most recent pubDate
I have
UPDATE titles t
INNER JOIN titles t2
ON t.titleID = t2.titleID
SET
    t.price = (
        /*Returns the price of the titleID with the most recent date in pubID*/
        SELECT t3.price FROM titles t3
        ORDER BY t.pubDate DESC LIMIT 1)
WHERE t.titleID = 1001

The error I am getting is
Error Code: 1053. You can't specify target table t for update in FROM clause

How can I correctly change a value to a value from the same column

A: One workaround to this error is to use an update join:
UPDATE titles t1
INNER JOIN
(
    SELECT titleID, MAX(pubDate) AS maxPubDate
    FROM titles
    GROUP BY titleID
) t2
    ON t2.titleID = t1.titleID AND
INNER JOIN titles t3
    ON t3.titleID = t1.titleID AND
       t3.pubDate = t2.maxPubDate
SET
    price = t3.price
WHERE
    price <> t3.price;

A: Another solution is to add an outer query in the select statement:
UPDATE titles t
INNER JOIN titles t2
ON t.titleID = t2.titleID
SET
    t.price = ( SELECT t1.price FROM (
                                     SELECT t3.price
                                     FROM titles t3
                                     ORDER BY t.pubDate DESC LIMIT 1) as t1 )
WHERE t.titleID = 1001

For more details check: https://dev.mysql.com/doc/refman/8.0/en/update.html

A: Both of the above answers didn't give me what I was looking for but they really helped in pointing me in the right direction
Here's the code that finally changed the price, I think I was searching max date row incorrectly I think the first time on top of the other errors as well
UPDATE titles t1
INNER JOIN titles t2
ON t1.titleID = t2.titleID
SET t1.price = ( SELECT t4.price FROM (
                                        SELECT t5.price
                                        FROM titles t5
                                        WHERE t5.pubDate = ( SELECT MAX(t3.pubDate)
                                                            FROM titles t3))
                                        AS t4)
WHERE t1.titleID = 1001

Here's the code that fetches the price from the row with the max date
SELECT t5.price
FROM titles t1
WHERE t5.pubDate = ( SELECT MAX(t3.pubDate)
                    FROM titles t3 )


text:
Q: Update multiple rows of one column based on primary key in SQL I know that I want to update only one row from a column I use this statement
UPDATE Customers
    SET ContactName = 'Alfred Schmidt'
    WHERE CustomerID = 1;

but what if I want to update multiple for example 5 rows based on primary key value?

A: The IN operator allows you to specify multiple values in a WHERE clause.
Example:
As in this:
SELECT *
FROM Customers
WHERE Customer_id IN (5000, 7000, 8000, 9000);

format:
expression IN (value1, value2, .... value_n);

In the mentioned case :
UPDATE Customers
    SET ContactName = 'Alfred Schmidt'
    WHERE CustomerID IN(12, 156);


text:
Q: Resolver arvore genealógica com PROLOG Estou com uma dificuldade em criar algumas relações.
Segue a tabela:
homem(jose).
homem(ananias).
homem(helio).
homem(jurandir).
homem(valdir).
homem(delio).
homem(fabiano).
homem(willian).
homem(diego).
homem(mateus).
homem(henrique).
mulher(generosa).
mulher(tereza).
mulher(maria).
mulher(nilzete).
mulher(ildete).
mulher(jaqueline).
mulher(gislaine).
mulher(jaqueline).
mulher(livia).
mulher(isabela).
mulher(maria_e).
casado(jose, generosa).
casado(ananias, tereza).
casado(delio, maria).
casado(jurandir, nilzete).
casado(delio, ildete).
casado(willian, jaqueline).
casado(diego, gislaine).
progenitor(jose, helio).
progenitor(generosa, helio).
progenitor(jose, jurandir).
progenitor(generosa, jurandir).
progenitor(ananias, nilzete).
progenitor(tereza, nilzete).
progenitor(ananias, valdir).
progenitor(tereza, valdir).
progenitor(ananias, ildete).
progenitor(tereza, ildete).
progenitor(helio, fabiano).
progenitor(maria, fabiano).
progenitor(jurandir, willian).
progenitor(nilzete, willian).
progenitor(jurandir, gislaine).
progenitor(nilzete, gislaine).
progenitor(delio, jaqueline).
progenitor(ildete, jaqueline).
progenitor(willian, henrique).
progenitor(jaqueline, henrique).
progenitor(willian, livia).
progenitor(jaqueline, livia).
progenitor(diego, isabela).
progenitor(gislaine, isabela).
progenitor(diego, maria_e).
progenitor(gislaine, maria_e).
progenitor(fabiano, mateus).

Preciso das seguintes regra de relações:
Pai, mãe, avó paterna, irmãos, irmão, irmãos completos, sogro, tio, neto, relação antepassado.
Pai e mae estou fazendo desta maneira:
pai(X,Y) :- homem(Y), progenitor(Y,X).
mae(X,Y) :- mulher(Y), progenitor(Y,X).

Mas apos retornar a mãe ou pai, tem um retorno false.
Irmãos fiz da seguinte maneira:
irmao(X,Y) :- progenitor(HOMEM,X), progenitor(HOMEM,Y), X \== Y.

Mas nesse caso so retorna irmão por parte de pai.
Preciso de uma regra para retornar irmão com pelo menos uma relação entre pai ou mãe.

A: Executando a primeira query obtive a seguinte resposta:
?- pai(jurandir,willian).
false.

?- pai(willian,jurandir).
true .

?- pai(willian,Y).

Y = jurandir .

Vamos entender o que está acontecendo antes de
abordamos o problema propriamente dito vendo o trace:

Talvez seja necessário apenas que tu organizes tuas regras.
Eu faria: pai(X,Y) :- homem(X), progenitor(X,Y).

Lê-se: "X é pai de Y  caso X seja homem E X seja progenitor de Y"

Para encontrar o irmão, tua regra precisa apenas de um complemento:
irmao(X,Y):-homem(X), pai(Z,X), pai(Z,Y),X\=Y.
irmao(X,Y):-homem(X), mae(Z,X), mae(Z,Y),X\=Y.

Realizando as consultas:
?- irmao(helio,jurandir).
true .

?- irmao(henrique,livia).
true .

Acrescentando o segunte fato para testar meio irmão:

progenitor(gislaine, mateus).

?- irmao(mateus,isabela).
true .

Sugiro que faças esse tipo de composição de regras para encontrar tios, primos etcétera.
Antes de prosseguirmos, considere o seguinte exemplo:
digerindo(X,Y) :- comeu(X,Y).
digerindo(X,Y) :- comeu(X,Z), digerindo(Z,Y).

comeu(mosquito,sangue(joão)).
comeu(sapo,mosquito).
comeu(cegonha,sapo).

Bastante ordinárion, não? Uma base de conhecimento contendo dois fatos
e duas regras, mas a definição de digeringo/2 é recursiva e ocorre em ambos os lados da segunda regra. Crucialmente, contudo, há uma ponto de parada (um caso base) para o número de chamadas. Este ponto é dado pela regra comeu/1, que ocorre am ambos os lados
das duas regras
A primeira regra (que não é recursiva, ou como normalmente a chamamos, a cláusula base), simplesmente diz que: se X acabou de comer Y, então X não está digerindo Y.
Então, e a segunda regra, a regra recursiva? esta diz que: se X tiver comido Z e Z está digerindo Y,
então X está digerindo Y também. Logo, Prolog conclui por inferência que a consulta é verdadeira.

Finalmente, voltando ao seu problema, vamos encontra um ascendente(antepassado).
?- ascendente(jose,helio).
true .

?- ascendente(jose,fabiano).
true .

Caso tu queiras um bom material em português, procure por Eloi Favero
Fonte:  BLACKBURN, Patrick; BOS, Johannes; STRIEGNITZ, Kristina. Learn
prolog now!. Londres: College Publications, 2006.


text:
Q: What segment in 8-bit LED Displays used for Traffic Light timers can be removed causing minimal impact in the readability of the countdown numbers? I passed by an intersection with traffic lights and noticed that 1 segment of the 8-bit display counter is dimmed (it's not working). When the lowermost segment is dimmed for example, number 4 can still be read as 4, but number 5 will not be read as 5.
First level question:
I just thought if there is a mathematical way (aside from brute force method) to determine what segment could be removed from the LED display that would make minimal impact in the readability of numbers.
I am curious if the solution is only 1 segment, or it can be multiple segments.
And possibly the countdown timer would matter? For example, the removed segment causing minimal impact differs if the traffic light timer counts from 30 to 00 as compared to a timer that counts from 15 to 00.
If we know this answer, in case 1 segment is dimmed are there are no available spare LED segments, they can just replace the dimmed LED segment from the segment with least impact in number readability.
Second level question:
What if we consider in the permutations when a removed/added segment from the number will not impair readability.
For example, number 9 with and without the lowermost segment is still readable.
Thanks!

A: Let's number each segments (actually there are only 7 of them) referring to this labeling. https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/7_segment_display_labeled.svg/220px-7_segment_display_labeled.svg.png
$0=a, 1=b, 2=c, 3=d, 4=e, 5=f, 6=g$
And then we can express each number as a vector $\{(v_0,v_1,v_2,v_3,v_4,v_5,v_6)\mid v_i=0\space or\space1\}$.
\begin{align}
0=(0,0,0,0,0,0,0)\\
1=(0,1,1,0,0,0,0)\\
2=(1,1,0,1,1,0,1)\\
3=(1,1,1,1,0,0,1)\\
4=(0,1,1,0,0,1,1)\\
5=(1,0,1,1,0,1,1)\\
6=(1,0,1,1,1,1,1)\\
7=(1,1,1,0,0,0,0)\\
8=(1,1,1,1,1,1,1)\\
9=(1,1,1,1,0,1,1)\\
\end{align}
And then let's define $distance(d_{min})$ as
$$d_{min}=\min d_{ij}=\min \|v_i (xor)v_j\|$$
If we don't lose any segment then the distance is $1$. The minimum distance happens for $(i,j)=(1,7),(6,8),(5,6),(8,9),(3,9)$ in which cases either segments $0$, $1$, $4$ or $5$ is the only difference. So we shouldn't lose those segments.
We can define two things.

*

*$d(k)=$Minimum distance when we lost $k$'th segment.

*$f(k)=$Impact factor of $k$'th segment $=\sum_{i,j} d_{ij}-d_{i}(k)$ where $d_{ij}(k)$ means $d_{ij}$ when $k$'th segment is lost.

Actually we can define different parameter, for example, "minimum of distance number that is changed by losing the segment" etc. But let's just keep going for now.
Then we can choose a segment that will not change $d(k)$ and has the minimum $f(k)$. I'll have to do some calculation to get this.
(*) It turns out that we could replace segments $2$, $3$, or $6$, but the segment $2$ has the minimum impact factor of $32$. The next one is the segment $6$ having impact factor of $42$. The segment $3$ has impact factor of $48$.


text:
Q: Defining a JSON schema currency type I'm trying to define a JSON schema for a property
money: 12.12

My main concern is that a maximum of 2 decimal places should be allowed. My initial attempt at defining this field was
money: {
  type: 'number',
  minimum: 0,
  multipleOf: 0.01
}

However, owing to floating point imprecision this fails. For example, using the tv4 validator, the number 147.41 passes validation, but 147.42 fails. Is there an alternative way to define a numeric type which will only allow a maximum of 2 decimal places?
It seems that the purpose of the "format" attribute is to implement these types of restrictions, but if I define the field like so:
money: {
  type: 'number',
  format: 'currency',
  minimum: 0
}

Then how do I specify that fields with a 'currency' format should only allow up to 2 decimal places?

A: I dislike the integer value thing, I find it doesn't solve real issues when it comes to proper number rounding when things like percentages get involved, (which is why other languages have Decimal types) and wanted to offer this very simple solution using string and pattern:
"amount":{
    "type": "string",
    "pattern": "^(0|([1-9]+[0-9]*))(\.[0-9]{1,2})?$",
    "minLength": 1,
    "description": "A Monetary Amount",
    "examples": [
        "0",
        "0.00",
        "0.05",
        "19.95",
        "255.5",
        "120000"
    ]
}

You can remove the minLength if you don't want it.

A: Your best option is likely to multiply  your currency values by 100.  Then you have whole numbers, and validation should work fine.  In general, using floating point to store monetary values is a bug farm, so you're better off moving toward "integers" even if technically they are still floating point values in JSON.
Some systems use an ISO currency code with the third letter in lower case to denote such currencies.  For example GBp for British pence, or USd for US pennies.  See https://stackoverflow.com/a/30635729/4323


text:
Q: What is the difference between Castle Windsor "Container" and "Kernel"? I'm starting using Windsor, and I want to understand when should I use container and when kernel. E.g.
var c = new WindsorContainer();
c.Register(Component.For<ITt>().ImplementedBy<Tt>());
var tt = c.Resolve<ITt>();

Everything is fine and everything works,
but here is also c.kernel that can do the same, what for?
var c = new WindsorConatiner();
c.kernel.Register(Component.For<ITt>().ImplementedBy<Tt>());
var tt = c.kernel.Resolve<ITt>();

Honestly I don't well understand is there any difference between "Container" and "Kernel" term. In my head it sounds like two names of the same thing in different IoC Libraries?
P.S. I read this post but still can't understand what for leave two implementations of one functionality here?
Update:
Just found in my code such row
      c.Kernel.Resolver.AddSubResolver(new ArrayResolver(c.Kernel));

What reason was to do it through Kernel? I completely lost

A: They're mostly equivalent today, but at first the IKernel and the IWindsorContainer were living in separate assemblies, with the Windsor container wrapping the kernel. Both were merged at some point but were kept alive to ensure backwards compatibility for users who may have used one or another.
Since the merge occured at version 2.5 (as discussed in the linked post) it is reasonable to assume there was some non negligible number of users who may have worked on one interface or the other, hence the cruft you see now.
Looking into the code you can see that almost all code from the windsor container calls the kernel internally, with some behavior added for child containers functionality, another option that remains from the past and is not necessarily useful

To those who though I'm seriously going to remove support for nested
  containers rest assured this is not going to happen. I still think
  this could be a viable option and I wanted to throw it into the air,
  but its become such a core feature of each IoC container, that
  Windsor would look crippled if it didn't have it, regardless of
  whether or not it'd be actually needed.

In the end, I'd recommend using the container; it wraps the kernel and is the official point of entry for managing your application (for example there is no Install method on the kernel)


text:
Q: Virtualenv (python) in Ubuntu 14.04 LTS on external hard drive I am trying to create a virtualenv on my external hard drive that I use for both my Ubuntu and my Windows installation (I have a SSD and use 2TB external hard drive for anything but PC games).
When I navigate to the place and try to create it with the commands that work on the standard Ubuntu home drive, I get the following:
nebelhom@nebelhom-desktop:/media/extHDD/virt_folder$ virtualenv MyFolder
New python executable in /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python
ERROR: The executable /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python could not be run: [Errno 13] Permission denied

Running the same with "sudo" did not help either and gave the same error as above.
What I tried next is indicating the python version
nebelhom@nebelhom-desktop:/media/nebelhom/extHDD/virt_folder$ sudo virtualenv -p python2.7 MyFolder
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python2.7
Not overwriting existing python script /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python (you must use /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python2.7)
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 2332, in <module>
    main()
  File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 711, in main
    symlink=options.symlink)
  File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 924, in create_environment
    site_packages=site_packages, clear=clear, symlink=symlink))
  File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 1369, in install_python
    os.symlink(py_executable_base, full_pth)
OSError: [Errno 17] File exists

And now I am stuck :/ . Has anyone of you tried something like this before and succeeded? I am really out of ideas here...
I tried to search for a solution previously, but for this particular problem I did not find anything useful. I will carry on looking and post any link that I can find that might be remotely related.
Thanks in advance for any help you can offer. It is much appreciated.

A: I think its happening because of filesystem on your external HDD. From your question I can guess that you use your external hard disk with both windows and linux, and its file system might be NTFS.
File permissions don't exist on NTFS and all the usual linux things like chown and chmod, that can be the reason why you are having these problems.
I would suggest, that you try to create a new partition on your ext HDD using a linux based filesystem like ext4. Then try to create a virtual environment.
I have tried creating python virtual environment on a removable disk, worked like a charm, only the FS was ext4.

A: Seems like Python is having trouble with permission on that folder.
Try giving root permission on the folder using this command:
sudo chown root:root -R /media/nebelhom/extHDD/virt_folder/MyFolder

Then run this command to create the virtualenv:
sudo virtualenv /media/nebelhom/extHDD/virt_folder/MyFolder


text:
Q: Range of a standard brownian motion, using reflection principle With a standard brownian motion $B_t$, I'm trying to find the distribution of the "range":
$$R_{t} = \sup_{0 \leq s \leq t} B_s - \inf_{0 \leq s \leq t} B_s = \overline{M_t}-\underline{M_t}$$
The reflection principle gives, for $a > 0$, $P(\overline{M_t} \geq a) = 2 P(B_t \geq a)$ (as stated by @A.S. as comment on this question), and clearly $P(\overline{M_t} \geq a) = 1$ for $a \leq 0$.
Thus $\overline{M_t} \sim |X|$ with $X \sim \mathcal N(0,\sqrt{t}^2)$, i.e. $\overline{M_t}$ has a folded normal distribution, with well-known density $f_\overline{M_t}$.
Now, in order to find $R_t$'s distribution I would like to do:
$$P(R_t \geq a ) = P(\overline{M_t} - \underline{M_t} \geq a) = \int_{\mathbb R^+} P(s - \underline{M_t}\geq a | \overline{M_t} = s) f_{\overline{M_t}}(s) d s.$$
So now what I need, is to compute:
$$P(-\underline{M_t} \geq y | \overline{M_t} = s)$$
or, for symmetry reason, I need to compute :
$$P(\overline{M_t} \geq y | \underline{M_t} = -s)$$

When $y \geq -s$, it seems that it's possible to compute
$$P(\overline{M_t} \geq y | \underline{M_t} = -s)$$
with reflection principle (not 100% sure).
In the other case, how to compute $P(\overline{M_t} \geq y | \underline{M_t} = -s)$ ?


text:
Q: Вызов функции из строки Есть строка:

var s = 'function a(){...} function b(){...}'

Возможно ли из кода вызывать эти функции по отдельности, без разбиения на разные строки?

A: У вас идет объявление ф-ции, а не их вызов

var s = 'function a(){...} function b(){...}'

И даже если после этого вы напишете eval(s);, то ничего не произойдет,
потому что вызова функций у вас нет нет.
Если писать самовызывающиеся ф-ции, как у вас, код вызовет ошибку ( ; нехватает между ф-циями ), а вот писать так можно
var s = "function a () { console.log('a'); }; function b () { console.log('b'); }; a(); b()");
eval(s);

Но ; все равно необходимо расставлять

A: Да, в данном случае если использовать eval
 var a = 'function f(){ alert(111); } function d(){ alert(222);}';
 eval(a);
 d();

Выведет алертом 222. Но более безопасным считается следующий вид преобразования строки в функцию:
// function name and parameters to pass
var fnstring = "runMe";
var fnparams = ["aaa", "bbbb", "ccc"];

// find object
var fn = window[fnstring];

// is object a function?
if (typeof fn === "function") fn.apply(null, fnparams);
// как вариант:  if (typeof fn === "function") fn();

function runMe(a,b){
  alert(b);
}

Выведет алертом bbb
Код в исполнении здесь: http://plnkr.co/edit/OiQAVd9DMV2PfK0NG9vk


text:
Q: Should we distinguish the minus sign from the negative sign? In the set $\mathbb{C}$ of complex numbers, the minus sign "-" may be used for following:

*

*As a unary operator $-_u$, given a complex number $a$, $-_ua$ is the unique number (called the negative of a) $c$ such that $a+c=c+a=0$, where $0$ is the additive identity.

*As a binary opeartor $-_b$, given two complex numbers $a$ and $d$, $a-_bd$ is the sum of $a$ and $-_ub$.

Though $-_u$ and $-_b$ are closely related, they are completely different objects in mathematics: $_u$ is considered as a map from $\mathbb{C}$ to $\mathbb{C}$ while $-_b$ is a map from $\mathbb{C}\times\mathbb{C}$ to $\mathbb{C}$. As maps, they have the same codomain but different domains.
In some calculators such as TI nspire, two different keys are used for the two different meanings of $-$. However, in our everyday writing, we seldom differentiate the unary opeartor $-_u$ and $-_b$. Shouldn't we use diffrent symbols for them; after all, though closely related, they are different?
If we do not use different symbols for them, the following simple calculation appears confusing:
\begin{equation*}\begin{array}{c}
\phantom{\times9}-23\\
\underline{-\phantom{9}-15}
\\
\phantom{999}-8
\end{array}\end{equation*}
Also, I find the idea that in the same equation $-1-1=-2$, the first $-$ has different meaning from the second $-$ unsatisfactory.

A: In my opinion, the notation should be different—but I accept that it's not.
For another (rather egregious) example, consider the equation
$$(a+bi)+(c+di) = (a+c)+(b+d)i.$$
Notice that the symbol '+' serves three distinct purposes: 1) to separate the real and imaginary parts of each complex number; 2) to indicate complex addition; and 3) to indicate real number addition (right hand side of the equation).
I alert my students to this and when, inevitably, they ask why we use such deficient notation, I tell them that, with respect to notation, mathematicians try to strike a balance betwixt clarity and readability; for instance, the following substitute for the previous equation (which I'm making up for convenience)
$$(a \oplus bi)+_{\mathbb{C}}(c\oplus di) = (a+_ \mathbb{R} c ) \oplus (b+_ \mathbb{R} d)i$$
contains no ambiguity but is visually unpleasant and cumbersome to write and typeset.

A: Only when there is the sort of ambiguity that could plausibly cause someone to completely misunderstand what you mean.
For example, what do I mean by $\pi(-\pi - 1)$? Do I mean $-\pi - \pi^2 \approx -13.011197$? Or do I mean 0? Or maybe I even mean 2.
The ambiguity here arises in part out of choosing to interpret the first "$\pi$" as the prime counting function or choosing to interpret it as that famous transcendental number.
Then there might be the ambiguity of whether, given positive $x$, is $\pi(-x) = 0$ or is it $\pi(-x) = \pi(x)$? In other words, is $\pi(x)$ how many positive primes there are between 0 and $x$ or is it how many primes, positive or negative, there are between 0 and $x$? The latter interpretation justifies $\pi(-4.14159) = 2$ rather than 0.
Though I suppose it would be possible to interpret both instances of $\pi$ as the prime counting function, in which case $\pi(-\pi(-1)) = 0$ regardless.
Try these in Wolfram Mathematica or Wolfram Alpha:

*

*Pi(-Pi - 1)

*PrimePi[-Pi - 1]

*PrimePi[-PrimePi[-1]]
This is not to say that confusion around the meaning of "$-$" is completely impossible. It is unlikely, though.
For example, we could assert both instances of "$-$" are unary negation. To make Mathematica see it that way, we'd need to do either Pi((-Pi)(-1)) or PrimePi[(-Pi)(-1)] (the former is $\pi^2$, the latter is 2). How likely is that, though? Without your question, not very.
So in general, there is no ambiguity whatsoever between negation and subtraction. However, if you like, you can choose to view negation as subtraction with an implied minuend of 0, e.g., $-8 = 0 - (0 + 8)$.

A: We do distinguish most of the time, at such a subconscious level that it seems either automatic or unthinking. Heck, we're even capable of resolving meanings that a computer would find contradictory.
Take for instance $$\frac{3}{2} = 1 + \frac{1}{2}.$$ In a cake recipe, you might find something like
1-1/2 cups light brown sugar

Put that in the context of JavaScript and it could be misunderstood as $$1 - \frac{1}{2} = \frac{1}{2}.$$ But if the author had meant one half rather than three halves, why didn't they just write one half? We understand in the recipe context that the author meant three halves, not one half.
If that's not manly enough an example, try a search for a 1-1/2 socket wrench.

A: First, note that there is already a distinction that is made, in the sense that you don't pronounce them the same: $$0-6=-6\qquad \text{"zero } \textbf{minus}\text{ six}=\textbf{negative}\text{ six}"$$
while other languages wouldn't - French, for instance, has "zéro moins six = moins six".
Now perhaps there is one case where it could be relevant to also point out the difference as you're writing, and that's when you're teaching at low level. Pupils get confused about the rules involving the $-$ sign partially because of this intentional mix-up by mathematicians and teachers (another, though related, source of confusion being the fact that you systematically write down the $-$ attached to negative numbers, while positive numbers don't have to have a $+$ at all times).


text:
Q: Transformation of Discrete Random Variables I am having trouble figuring out what values y takes in the below problem:
Let $f(x)$ be the PDF of $x$, For each of the following, find the PDF of Y:
$f(x)= 1/4$ when $x$ is between $0$ and $1$,
$f(x)= 3/8$ when $x$ is between $3$ and $5$,
$f(x)=0$ otherwise
Y=1/x
I am guessing that f(y)= 3/8y when y is between 3 and 5 but am otherwise clueless

A: We have $Pr(X \le x) =\begin{cases} \frac{x}{4} &, 0 < x< 1 \\ \frac14+\frac38(x-3) &, 3< x <5\end{cases}$
$$Pr(Y \le y)=Pr(\frac1X \le y)=Pr(X \ge \frac1y)$$
That is if $1 < y$, we have $Pr(Y  \le y)=Pr(X \ge \frac1y)=1-\frac{1}{4y}$
and if $\frac15 < y <\frac13$, we have $Pr(Y \le y)=Pr(X \ge \frac1y)=\frac34-\frac{3}{8}(\frac1y-3)$
Differentiating each rule, we have
$$f_Y(y)=\begin{cases} \frac1{4y^2} &, 1<y \\ \frac3{8y^2}  & ,\frac15< y < \frac13\\ 0 &\text{, Otherwise}\end{cases}$$

A: Please note, that your random variable $X$ is not discrete random variable.
One way you can compute it is:

*

*Find CDF of $X$

*Then CDF of $Y$ is $G(y) = P(Y < y) = P(X>1/y ) = 1 - F(1/y)$

*Then PDF of $Y$ is derivative of the CDF.


text:
Q: python password generator for django How can I manually generate password for django? For example, in other application, but using  the same database as django .For username 'admin'  password like this
pbkdf2_sha256$10000$T0BzrDwfZSrI$pSgvDEam9V9jcdYpYDVkYMMwtSnRrFdf6Aqow82Tjr8=

A: The most common (not safest) algorithm for hashing is md5. Extracting a few ideas from Django's password system can be this code:
import hashlib

def make_password(password):
    assert password
    hash = hashlib.md5(password).hexdigest()
    return hash

def check_password(hash, password):
    """Generates the hash for a password and compares it."""
    generated_hash = make_password(password)
    return hash == generated_hash

>>> hash = make_password('hello123')
>>> hash
'f30aa7a662c728b7407c54ae6bfd27d1'
>>> check_password(hash, 'hello123')
True
>>> check_password(hash, 'Hello123')
False

Use make_password to generate a hash and check_password to check if the entered password is the same as the stored one.
As @Emil pointed out, Django supports multiple password hashers such as pbkdf2_sha256 and pbkdf2_sha1, storing the string as a 3-fold value separated by $: algorithm$salt$hash.  salt is a randomly generated string to prevent same password from repeating in the database.

A: I think this maybe what you are looking for :
Manually managing a user's password

make_password(password[, salt, hashers])
Creates a hashed password in
  the format used by this application. It takes one mandatory argument:
  the password in plain-text. Optionally, you can provide a salt and a
  hashing algorithm to use, if you don't want to use the defaults (first
  entry of PASSWORD_HASHERS setting). Currently supported algorithms
  are: 'pbkdf2_sha256', 'pbkdf2_sha1', 'bcrypt_sha256' (see Using bcrypt
  with Django), 'bcrypt', 'sha1', 'md5', 'unsalted_md5' (only for
  backward compatibility) and 'crypt' if you have the crypt library
  installed. If the password argument is None, an unusable password is
  returned (a one that will be never accepted by check_password()).

I want write function for using without django

Well luckily Django is open source, so you can go and take what you need. The functions source is visible here.


text:
Q: Remove Null values from SQL Oracle I have an SQL query

SELECT
    EXPORT_MONTH "EXPORT_MONTH",
    EXPORT_PROD "EXPORT_PROD",
    QUANTITY "QUANTITY"
 FROM EXPORT_IMPORT
  LEFT OUTER JOIN  EXPORT_DATE
ON EXPORT_MONTH (EXPORT MONTH) <=
EXPORT_PROD_CYCLE_YEAR_MONTH
ORDER BY EXPORT_MONTH DESC;

which produces the following output
Current Output

EXPORT_MONTH","EXPORT_PROD","QUANTITY

'198609',null,null
'198608',null,null
'198607',null,null
'198606','2287472','4961023'
'198605','1820387','4591548'
'198604','2305491','7171038'
'198603','2247472','4961023'
'198602','1810387','4591548'
'198601','2315491','7171038'

I'm trying yield the following output
Expected Output

EXPORT_MONTH","EXPORT_PROD","QUANTITY

'198606','2287472','4961023'
'198605','1820387','4591548'
'198604','2305491','7171038'
'198603','2247472','4961023'
'198602','1810387','4591548'
'198601','2315491','7171038'

https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=c90b4568fe89532574884446f3585854

A: I think you want an INNER JOIN:
SELECT EXPORT_MONTH, EXPORT_PROD, QUANTITY
FROM EXPORT_IMPORT i INNER JOIN
     EXPORT_DATE d
     ON EXPORT_MONTH <= EXPORT_PROD_CYCLE_YEAR_MONTH
ORDER BY EXPORT_MONTH DESC;


text:
Q: sending data from controller to a typeclass in symfony 3 i'm trying to get data from the database and pas it to the form's drop down list
this is the Entity from where i'm looking to get the data from, specifically the type column
<?php

namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\TypesRepository")
* @ORM\Table(name="types")
*/
class Types
{

 /**
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 * @ORM\Column(name="idtype",type="integer")
 */
 private $idtype;
 /**
 * @ORM\Column(type="string", length=100)
 */
 private $type;

and this is the type class that holds the form,as you can see i created a construct based on some internet cherche that i have done, the constructer adds the passed value to the variable, then it's called in the EntityType
class sell_form extends AbstractType
{

protected $cat;

public function __construct (Types $cat)
{
$this->cat = $cat;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{

$builder

->add('categorie',EntityType::class,array(
                       "required"=>false,
                        'class' => 'AppBundle\Entity\Types',
                        'choices' => $cat
                        ))

                        ;
                ;
 }
 }

and finaly this is the controller where i inisialize the $cat variable from the database using a repository function
/**
  * @Route("/Old/buy", name="old_buy")
*/
public function Old_buyAction()
{

return $this->render('/user_module/Old Views/Old_buy.html.twig');
        }
/**
   * @Route("/Old/sell", name="old_sell")
   *@Method({"GET","POST"})
*/
public function Old_sellAction()
{
$cat = $this->getDoctrine()->getManager()->getRepository('AppBundle:Types')-
>tn();

 /*line 122 */

$form = $this->createForm(new sell_form($cat));
 //$form = $this->createForm(sell_form::class,$cat);
 return $this->render("user_module/Old Views/old_sell.html.twig",array(
                                          "myForm"=>  $form->createView(),

                                    ));

this is the error that it's shown
Catchable Fatal Error: Argument 1 passed to
AppBundle\Forms\sell_form::__construct() must be an instance of
AppBundle\Entity\Types, array given, called in
C...\OldController.php
on line 122 and defined`

Many Thanks in advance

A: $cat is an array of AppBundle\Entity\Types instances. You pass them into form constructor:
public function __construct (Types $cat)
{
    $this->cat = $cat;
}

At this moment your code expects that $cat is a single Types instance, so it crashes:

AppBundle\Forms\sell_form::__construct() must be an instance of
  AppBundle\Entity\Types, array given

You need to expect an array:
public function __construct (array $cat)
{
    $this->cat = $cat;
}


text:
Q: Capture group in specific string I have a string:
User{self=https:example.com, name=S1234, displayName=Johny B, accountId=null, emailAddress=johny.b@example.com, active=true}'

I try to capture group and get Johny B in sed.
I have proper regex: displayName=(.*?),
but below sed command return me all string:
's/.*displayName=\(.*?\),/\1/'

A: You can try this sed
sed -E 's/.*displayName=([^,]*).*/\1/' $file

You have further strings after the match which you need to account for.


text:
Q: Want to add a custom author link to a single.php I want to add a custom link to linkedin near author name. It should be very easy if it would be only one author, but now it's not. So, I have to add something on all single.php and somewhere the real links. Can anybody help me with this? Thanks!

A: Have a look at this tutorial. It will teach you how to add a linkedin box to a user's profile and how to display that in a post.


text:
Q: How to add RBAC in Azure Databricks using ARM I am trying to add RBAC in Azure Databricks using ARM. I have managed to add RBAC using ARM in App Insights with the following code
"resources": [
    {
      "type": "Microsoft.Insights/components/providers/roleAssignments",
      "apiVersion": "2017-05-01",
      "name": "[concat(parameters('AppInsightName'),'/Microsoft.Authorization/',guid('AppInsightName'))]",
      "properties": {
        "roleDefinitionId": "[variables(parameters('builtInRoleType'))]",
        "principalId": "[parameters('principalId')]"
      }
    }
  ]

Looking for some input in creating RBAC in Databricks using ARM

A: you'd use the exact same approach:
{
  "type": "Microsoft.Databricks/workspaces/providers/roleAssignments",
  "apiVersion": "2017-05-01",
  "name": "[concat(parameters('databricks_name'),'/Microsoft.Authorization/',guid('something'))]",
  "properties": {
    "roleDefinitionId": "[variables(parameters('builtInRoleType'))]",
    "principalId": "[parameters('principalId')]"
  }
}


text:
Q: Why is MySQL server only accepting empty passwords? I've added a new user to my MySQL 5.1 server on a fresh installation of Fedora 13 and set its password. (Using SET PASSWORD FOR USER myuser = PASSWORD('...')), but MySQL only accepts the user when I'm using an empty password to log on.
In other words: When I enter the correct password, I get an access denied error. When I use an empty string, it get in.
Things I tried:

*

*Changing the password and changing it back.

*Recreating the user.

*I verified that changing the password actually modifies the password hash in the user table.

*It makes no difference if I connect from the command line (mysql -u myuser -p) or from phpMySQL.

*I experimented with different hostnames (myuser, myuser@localhost, myuser@'%')

Is there any configuration option which might trigger this behaviour?

A: Could be you did not flush the privileges
flush privileges