text:
Q: Find the smallest integer $n$ with $\tau(n)=a$ Find the smallest integer $n$ with $\tau(n)=a$ with $\tau(n)$ the number of dividers of n.

*

*$\tau(n)=1$

*$\tau(n)=2$

*$\tau(n)=3$

*$\tau(n)=6$

The soluion is given by:

The book does not give a solution method, I just tried it by trail and error. What is the best method for such an excercice?

A: This can be done by factoring the number into prime factor.Read this https://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic , SO there is only one unique to factorize a number into prime factors.
Suppose Given number is N for unique way to reduce this into prime factor is $p1^{e1}*p2^{e2}......pn^{e^{m}}$ Here $p1 < p2 < p3....$. Now the total number of divisors of this number is $ (e1 + 1)*(e2 + 1) *(e3 + 1).....(em +1)$ So if you are given a number of divisors of Nyou can easily find the number by factoring it.
Just take $τ(n)=3$ so prime factor of 3 is 3 and it is = $(e1 + 1)$. Now put this in form o$p1^{e1}*p2^{e2}......pn^{e^{m}}$ Here $p1 < p2 < p3....$. it will be $2^{2} $ whic is equal to 4 and hence 4 is the smallest number with 3 divisors which are $ 1, 2 ,4$ . Hope this helps.


text:
Q: FIONBIO for ioctl under Fusion I'm working on a project based on uCOS and the Fusion standard (rather than POSIX) and I want to set my socket into non-blocking mode. The POSIX ioctl command would be ioctl(data,FIONBIO, TRUE); but I can't seem to get it going under Fusion.
In the comments of the header fclioctl.h, I see the following:
/*
 *  The UNIX definition was as follows:
 *
 *      int ioctl( int fd, int cmd, ... )
 *
 *  But since POSIX does not include "ioctl" as part of it's requirements for
 *  Fusion the format follows more closely to Win32.
 *
 *  TO get information about a device, a handle to the device or a device in
 *  it's device stack must be obtained.
 */

fclIoResult_t fclIoctl
(
    fclHandle_t     hDevice,            /*  Handle to device                */
    fclIoCode_t     nIoControlCode,     /*  Function to perform             */
    fclIoBuffer_t   pInBuffer,          /*  Data to the device              */
    fclIoSize_t     nInBufferSize,      /*  Size of data to the device      */
    fclIoBuffer_t   pOutBuffer,         /*  Data from the device            */
    fclIoSize_t     nOutBufferSize,     /*  Size of buffer to receive data  */
    fclIoSize_t*    pnBytesReturned     /*  Actual number of bytes received */
);

and for 1fclIoCode_t`, i only see:
/*
 *  IOCTL Types
 */

typedef unsigned char   FIO_BYTE;
typedef unsigned int    FIO_WORD;
typedef u32   FIO_DWORD;

#ifndef FCL_IOCODE_T
    typedef u32 fclIoCode_t;
    #define FCL_IOCODE_T    fclIoCode_t
#endif

Does anybody have experience with Fusion and may be able to help out here?

redpajama_set_name: RedPajamaStackExchange


text:
Q: php + mysql + utf-8 + спецсимволы Приветствую. Есть некий форм который скоро пропадет. Есть необходимость получить его "слепок". Языков он держит много, и там UTF-8.
Работаю с БД в UTF-8, использую и mysql_real_escape_string и mb_convert_encoding так как порой приходят сбойные символы в русскоязычном разделе. И всё бы хорошо (mb_convert_encoding заменяет когда всё совсем печально нечитаемое и не записываемое в БД на "?"), но столкнулся вот с такой красотой "☺". Она корректно пропускается на заменяясь и не корректируясь и mysql_real_escape_string и mb_convert_encoding но в БД не пишется. Проще говоря строка на этих красотулях обрезается, пишется только то, что до них. Как бы это победить?
P.S. возможно важно указать, что эти символы найдены в рус. части форума, где они идут среди русскоязычных букв UTF-8

A: mysqldump -uusername -ppassword dbname --default-charset=utf8 > dump.sql

A: Разобрался. Пересоздал базу в формате utf8mb4_unicode_ci и применил эту же кодировку на все ее таблицы.
Оказалось, что для некоторых спецсимволов в utf8 кодировке, обычного формата базы данных в utf8 не достаточно. Эти символы требуют по 4 байта для записи, а не по 2.


text:
Q: TraditionalForm-like typesetting in Jupyter notebook One of the nice thing about running Mathematica codes in the front-end,
is that one can attach custom typesetting rules to the user-defined symbols.
Then, setting the format type of new output cells to TraditionalForm
provides you with a nice output similar to what one sees in papers and
textbooks.
Suppose that someone wants to use my package (that comes with extensive
typesetting rules) with the free Wolfram Engine, where the front-end
is a Jupyter notebook. As far as I can see, no typesetting is displayed
by default.
As a minimal working example, consider the following code.
cf /: MakeBoxes[cf[i_], TraditionalForm] := SubscriptBox["c", i];
SMP /: MakeBoxes[SMP["g_W"], TraditionalForm] :=
  SubscriptBox["g", "W"];
MakeBoxes[myvec[x_], TraditionalForm] :=
  TemplateBox[{OverscriptBox[ToBoxes[x], "\[RightArrow]"]}, "Abs"];
MakeBoxes[Power[myvec[x_], n_], TraditionalForm] :=
  SuperscriptBox[
    TemplateBox[{OverscriptBox[ToBoxes[x], "\[RightArrow]"]}, "Abs"],
    ToBoxes[n]] /; OddQ[n];
MakeBoxes[Power[myvec[x_], n_], TraditionalForm] :=
  SuperscriptBox[OverscriptBox[ToBoxes[x], "\[RightArrow]"],
    ToBoxes[n]] /; EvenQ[n];

In Mathematica, for
SMP["g_W"] (cf[1] myvec[v] + cf[2] myvec[v]^2 + cf[3] myvec[v]^3)

I get the expected typesetted output, but in Jupyter
this is not the case.

Is there something that can be tweaked in the notebook configuration or
in the package source code, to get the typesetting working?

A: I'd just use StandardForm because the loop WE-Jupyter is tricky to hook to.
I guess this solution won't work once WLforJupyter is out of beta stage but anyway:
toOut = toOutImage @* TraditionalForm;
toOut /: (toOut = _) := Null;

It is not a joke :)

Explanation
toOut and toOutImage are symbols that are originally defined within the loop that handles communication between the Kernel and Jupyter notebook. Kernel sends evaluated response but Jupyter does not understand MMA Box language so it needs to be something else. Currently it is implemented that it is either a plain text, an image or an embedded iFrame with contents deployed to cloud.
WLforJupyter loop makes a choice that it should be e.g. an image and does toOut = toOutImage @ evaluationResults
So the trick is to set toOut (1st line) and prevent it from being reset (2nd line). :)


text:
Q: Numpy mask by rows I have 2D array:
matrix =np.array([[95,90,-1,55],[100,90,-1,80],[0,90,85,100]])

I try to choose 2 random rows, and ignore -1.
I tried:
random_ints = np.random.choice(len(matrix), size=2, replace=False)
students = matrix[random_ints, :]
ignored = students[students != -1]

but the ignored var reshaped to 1D array for example:
[95,90,55,100,90,80]

I want the ignored saved 2D for example:
[[95,90,55],[100,90,80]]

How can do that?

A: If you had equal number of elements to be left (!= -1) in
each row, you could run:
np.apply_along_axis(lambda row: row[row != -1], 1, students)

To check this variant, set random_ints = np.array([0,1]), select just
the above rows to students and run the above code.
But if the number of these element is different, Numpy will
raise exception:
ValueError: could not broadcast input array from shape (3) into shape (4)

The reason is that (in this case) some rows have 4 elements to be
left, whereas other - only 3.
Unfortunately, Numpy does not support "jagged" arrays (with different
number of elements in each row).
You can get something like you wanted, but as a nested list
(not a Numpy array):
result = []
for row in students:
    result.append(row[row != -1].tolist())

The result (for rows 2 and 1) is:
[[0, 90, 85, 100], [100, 90, 80]]


text:
Q: Calculate Textboxs Values With Jquery But It's Not Working I have some problem with this codes. Codes work without loop but i need to change div ids, input ids and variables names in every loop. "@id's" value rising sequentially (ex: 1-2-3....). but I can't calculate sum. Here my codes;

  @{ foreach (var tbirimfiyat in ViewBag.TurlerBirimFiyat)
  {
  if (item.Musteri_ID == tbirimfiyat.Musteri_ID && tur.Tur_ID == tbirimfiyat.Tur_ID)
  {
  <input type="text" class="turbirimfiyat" id="turbirfiyat_@id" name="Musteri_ID" value="@tbirimfiyat.tBirim_Fiyat" />
  }
  }
  }

        Verilen @tur.Tur_Ad
        <input type="number" value="0" id="verilen_@id" class="form-control turadetler_@id" name="verilen">

        Alınan @tur.Tur_Ad
        <input type="number" class="form-control turadetler_@id" id="alinan_@id" name="alinan" value="0">

        Alınan Para
        <input type="number" class="form-control" id="para_@id" name="para" value="0">

Error Message; jquery-3.3.1.js:8032 The specified value "NaN" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?
And here my codes without loop;

  $(document).ready(function() {
    var birim= $('#turbirfiyat').val();
    $(".turadetler").on("keydown keyup", function() {
      var sum = 0;

      $(".turadetler").each(function() {

        if (!isNaN(this.value) && this.value.length != 0) {
          sum += parseFloat(this.value) * birim;
          $(this).css("background-color", "#FEFFB0");
        }
        else if (this.value.length != 0) {
          $(this).css("background-color", "red");
        }
      });
      $("#para").val(sum.toFixed(2));
    });
  });

        1
        Number
        <input  type="text" name="txt" id="turbirfiyat" value="2" />

        2
        verilen
        <input class="turadetler" type="text" name="txt" id="verilen"value="0" />

        3
        Alinan
        <input class="turadetler" type="text" name="txt" id="alinan" value="0" />

            Sum :

          <input type="text" id='para' name="input" />

Output ;

  <input type="text" class="turbirimfiyat" id="turbirfiyat_3" name="Musteri_ID" value="0,2">

        Verilen Tahinli
        <input type="number" value="0" id="verilen_3" class="form-control turadetler_3" name="verilen" style="background-color: rgb(254, 255, 176);">

        Alınan Tahinli
        <input type="number" class="form-control turadetler_3" id="alinan_3" name="alinan" value="0" style="background-color: rgb(254, 255, 176);">

        Alınan Para
        <input type="text" class="form-control" id="para_3" name="para" value="0">

How can I fix ?

A: Use $(this).val() instead of this.value. Don't mix Plain JS and JQuery.

$(document).ready(function () {
  var birim = $("#turbirfiyat").val();
  $(".turadetler").on("keydown keyup", function () {
var sum = 0;
//iterate through each textboxes and add the values
$(".turadetler").each(function () {
  const val = $(this).val();
  //add only if the value is number
  if (!isNaN(val) && val.length != 0) {
    sum += parseFloat(val) * (Number(birim) || 0);
    $(this).css("background-color", "#FEFFB0");
  } else if (val.length != 0) {
    $(this).css("background-color", "red");
  }
});
$("#para").val(sum.toFixed(2));
  });
});

        1
        Number
        <input type="text" name="txt" id="turbirfiyat" value="2" />

        2
        verilen
        <input class="turadetler" type="text" name="txt" id="verilen" value="0" />

        3
        Alinan
        <input class="turadetler" type="text" name="txt" id="alinan" value="0" />

            Sum :

            <input type="text" id='para' name="input" />


text:
Q: EasyPhp: How to Enable Openssl Hi how can I enable openssl in Easyphp as Im getting the error Message could not be sent.Mailer Error: Extension missing: opensslTime: when using phpmailer. Thanks

A: In your php.ini
Change
;extension=php_openssl.dll

to
extension=php_openssl.dll

and restart your web server.


text:
Q: Efficient MySQL query for huge set of data Say i have a table like below:
CREATE TABLE `hadoop_apps` (
  `clusterId` smallint(5) unsigned NOT NULL,
  `appId` varchar(35) COLLATE utf8_unicode_ci NOT NULL,
  `user` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `queue` varchar(35) COLLATE utf8_unicode_ci NOT NULL,
  `appName` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `submitTime` datetime NOT NULL COMMENT 'App submission time',
  `finishTime` datetime DEFAULT NULL COMMENT 'App completion time',
  `elapsedTime` int(11) DEFAULT NULL COMMENT 'App duration in milliseconds',
  PRIMARY KEY (`clusterId`,`appId`,`submitTime`),
  KEY `hadoop_apps_ibk_finish` (`finishTime`),
  KEY `hadoop_apps_ibk_queueCluster` (`queue`,`clusterId`),
  KEY `hadoop_apps_ibk_userCluster` (`user`(8),`clusterId`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

mysql> SELECT COUNT(*) FROM hadoop_apps;

This would return me a count 158593816
So I am trying to understand what is inefficient about the below query and how I can improve it.
mysql> SELECT * FROM hadoop_apps WHERE DATE(finishTime)='10-11-2013';

Also, what's the difference between these two queries?
mysql> SELECT * FROM hadoop_apps WHERE user='foobar';
mysql> SELECT * FROM hadoop_apps HAVING user='foobar';

A:
WHERE DATE(finishTime)='10-11-2013';

This is a problem for the optimizer because anytime you put a column into a function like this, the optimizer doesn't know if the order of values returned by the function will be the same as the order of values input to the function. So it can't use an index to speed up lookups.
To solve this, refrain from putting the column inside a function call like that, if you want the lookup against that column to use an index.
Also, you should use MySQL standard date format: YYYY-MM-DD.
WHERE finishTime BETWEEN '2013-10-11 00:00:00' AND '2013-10-11 23:59:59'

What is the difference between [conditions in WHERE and HAVING clauses]?

The WHERE clause is for filtering rows.
The HAVING clause is for filtering results after applying GROUP BY.
See SQL - having VS where

A: If WHERE works, it is preferred over HAVING.  The former is done earlier in the processing, thereby cutting down on the amount of data to shovel through.  OK, in your one example, there may be no difference between them.
I cringe whenever I see a DATETIME in a UNIQUE key (your PK).  Can't the app have two rows in the same second?  Is that a risk you want to take.
Even changing to DATETIME(6) (microseconds) could be risky.
Regardless of what you do in that area, I recommend this pattern for testing:
WHERE finishTime >= '2013-10-11'
  AND finishTime  < '2013-10-11' + INTERVAL 1 DAY

It works "correctly" for DATE, DATETIME, and DATETIME(6), etc.  Other flavors add an extra midnight or miss parts of a second.  And it avoids hassles with leapdays, etc, if the interval is more than a single day.
KEY `hadoop_apps_ibk_userCluster` (`user`(8),`clusterId`)

is bad.  It won't get past user(8).  And prefixing like that is often useless.  Let's see the query that tempted you to build that key; we'll come up with a better one.
158M rows with 4 varchars.  And they sound like values that don't have many distinct values?  Build lookup tables and replace them with SMALLINT UNSIGNED (2 bytes, 0..64K range) or other small id.  This will significantly shrink the table, thereby making it faster.


text:
Q: Usage of Some: Does "some" require a plural or singular verb? Usage of Some:  Does "some" require a plural or singular verb?

A: when some is an adjective it can be used with both plural and singular
1.
being an undetermined or unspecified one:
Some person may object.
Informal. of impressive or remarkable quality, consequence, extent, etc.:
That was some storm.
though when used as a quantifier then it may only be used with mass nouns and uncountable ones.
May i have some sugar please
I think i see some people over there
and since the verb form is decided by the SN and none other this should answer your question
SN= subject noun

A: If the word that you want to put after "some" has a plural form, then use the plural form of the verb:

Some people are egoistic.

If the word doesn't have a plural form, use the singular form:

Some information is incorrect.

Information does not have a plural form, so you have to use the singular form of the verb.
The same rule applies for other quantities:

A lot of people are egoistic.
  A lot of information is incorrect.
  Many people are egoistic.
  Much information is incorrect.

A:

singular
plural

An apple is…
Some apples are…

A book has…
Some books have…

A man does…
Some men do…

A child lives…
Some children live…

A cake tastes…
Some cakes taste…

A piece of cake is…
Some pieces of cake are…

A glass of water isn't…
Some glasses of water aren't…

Water is…
Some water is…

A piece of advice was…
Some advice was…

I have (a piece of) good news.
I have some good news.


text:
Q: Programmatically turn on/off GPS on Android
Possible Duplicate:
Enable GPS programatically like Tasker

Is it possible to programmatically turn on/off gps on android? It is mentioned on this SO post: How can I enable or disable the GPS programmatically on Android? that it cannot be done without the user consent.

A: No it is not possible. The closest you can get is firing an Intent that shows the GPS settings to the user. Please follow this guide: Guide for GPS intent Android


text:
Q: Vertical coriolis effect Imagine the Earth to be an extended body, spinning about an axis. Suppose we throw a ball vertically upwards. As soon as the ball leaves our hand, it starts traveling upward with some velocity and also with some angular velocity, equal to that of the Earth, just before it was thrown. However, as soon as the ball leaves our hand, we can consider it to be a Kepler orbit. As it moves upward, due to the conservation of angular momentum, its angular velocity should decrease, as distance increases. Let's say, the ball rises to a height $h$. At ground $0$, it had an angular velocity $\omega_g$, and at height $h$ it has an angular velocity $\omega_h$ such that $\omega_h \lt \omega_g$.
Since the earth is an extended object, if we project the longitudes on the surface of the Earth, at the height $h$, they would have the exact same angular velocity as the ground, as in extended circular motion, the angular velocity remains the same, as the points are still completing one revolution in 1 day.
Hence the ball lags behind the longitudes at this height, while rising and falling down again, as it has an angular velocity always less than that on the ground.
Is this the reason, why balls get deflected sideways when thrown upwards ? Is this the reasoning behind the vertical coriolis effect?

A: If the earth was stationary, as seen by an observer on earth (an inertial reference frame) a ball thrown straight upwards would go vertically up, then vertically down due to the force of gravity, with no sideways movement. In the inertial reference frame, the angular momentum of the ball relative to the center of the earth zero.
Due to the earth's rotation, as seen by an observer on earth (a non-inertial reference frame), the ball experiences fictitious forces, one of which is the Coriolis force.  The Coriolis force appears when an object has a velocity in the rotating frame of reference, here the velocity of the ball relative to the earth.  The Coriolis force is $−2m \vec ω × {d^* \vec r \over dt}$ where $m$ is the mass of the object (here, the ball), $\vec ω$ is the angular velocity of the rotating frame of reference, $\vec r$ is the position of the object (in either frame) and ${d^* \vec r \over dt}$ is the velocity of the object in the rotating frame of reference. The Coriolis force, hence the sideways deflection, depends on the latitude where the ball is thrown. In the non-inertial reference frame, the angular momentum of the ball relative to the center of the earth is not zero due to the Coriolis force.
(As an aside, the angular momentum depends on the point about which it is evaluated.)
See a physics mechanics textbook such as Symon, Mechanics, and the question/response @mmesser references in a comment above.


text:
Q: IIS mail server relay mails stuck in queue due to DNS? Recently our internal SMTP relay server stopped working - or rather, stopped sending emails. It responds to send mail requests, a simple TELNET session shows no errors, but all messages get stuck in its queue.
This all happened after our virtualization server ran out of disk space and suspended quite a few machines.
I suspect this is a DNS issue. I was able to set up a working relay server inside a virtual machine (on my own workstation), but I had to configure 8.8.8.8 as the DNS server for that machine.
As soon as I reverted to our DHCP assigned DNS my own mail server would stop.
Unfortunately, there appear to be no useful logs whatsoever. I don't know if the mail server is having issues resolving some domain name or connecting to some IP. On my virtual machine with Google DNS the log contains send message requests followed by a set of messages for relaying - i.e. connecting to another mail server and forwarding the email. On the actual server where the issue occurs there are no messages regarding relaying.
Unfortunately, the machine hosting the mail server is also the primary DNS machine for our internal network (don't look at me, I didn't set that up), so I cannot just use Googles DNS and call it a day - doing so I'd probably break a lot of other things.
Any idea what could possibly be wrong? Alternatively - is there any way to find find out what is the EXACT reason messages aren't leaving the queue folder?

A: I've eventually managed to find the answer.
Someone had turned on the "disable recursion" advanced option in the DNS server.
I'm not sure why exactly turning recursion off effectively disabled the SMTP relay server's capability, but in my case this was the direct cause of the problem.

A: I had a space in the front of the DNS entry


text:
Q: apt downgrade to a specific version of package (not present in repository) I've got a system with libgtk-3-0 version 3.22.30-1ubuntu1 installed. To fix a known bug I want to downgrade to version 3.22.21. However, running aptitude to find the available versions yells the following:
$ aptitude versions libgtk-3-0
package libgtk-3-0:
p  3.22.30-1ubuntu1                     bionic
i  3.22.30-1ubuntu2                     bionic-updates

so of course trying to install the version that I want didn't work
$ sudo apt install libgtk-3-0=3.22.21-1ubuntu1
E: Version "3.22.21-1ubuntu1" for "libgtk-3-0" not found


text:
Q: Cookie is not set / working i have a script with html login form jQuery and php all works fine but if visitor select remember me then cookie is not set or working even after i reload the page using jQuery window.location.replace('index.php'); still not working can any one please help, thanks
HTML
    <form class="login-form" action="" method="POST" name="operator_login">

Login Success!

     <input type="text" placeholder="Email" name="adminusers_username"/>
     <input type="password" placeholder="Password" name="adminusers_password"/>
     <input type="checkbox" name="operator_remember" checked /> Remember me
     <button type="submit"  name="operator_login">Login</button>
    </form>

jQuery
    $(document).ready(function() {
    $('.login-form').submit(function(){
        var adminusers_username = $('input[name=adminusers_username]'),
            adminusers_password = $('input[name=adminusers_password]'),
            loginerror = $('#loginerror'),
            loginsuccess = $('#loginsuccess');
                if ($('input[name=operator_remember]').is(':checked')) {
                    var operator_remember = 1;
                    }else{
                    var operator_remember = 2;
                 }
        $.post('server/login.php', {
        'adminusers_username': adminusers_username.val(),
        'adminusers_password': adminusers_password.val(),
        'operator_remember': operator_remember
        },
            function(data){
                if (data==1) {
                loginerror.hide();
                loginsuccess.show();
                window.location.replace('index.php');
                } else {
               loginerror.show().html(data);
            }
    });
    return false;
    });
});

PHP
session_start();
if ( isset($_REQUEST['adminusers_username'])
    && $_REQUEST['adminusers_username'] !=''
    &&  isset($_REQUEST['adminusers_password'])
    && $_REQUEST['adminusers_password']!='') {

    $postedusername = $_REQUEST['adminusers_username'];
    $postedpassword = $_REQUEST['adminusers_password'];
    $rememberme = $_REQUEST['operator_remember'];

    $query_rsUserLogin = "SELECT * FROM adminusers
    WHERE adminusers_username = '".trim($postedusername)."'";
    $rsUserLogin = mysql_query($query_rsUserLogin, $connection);
    $row_rsUserLogin = mysql_fetch_assoc($rsUserLogin);
    $totalRows_rsUserLogin = mysql_num_rows($rsUserLogin);

    $username = $row_rsUserLogin['adminusers_username'];
    $userpassword = $row_rsUserLogin['adminusers_password'];
    $email_conf = $row_rsUserLogin['admin_email_confirmed'];
    $user_status = $row_rsUserLogin['admin_status'];

    if ($totalRows_rsUserLogin > 0  ) {
        if ($user_status == 'Active' ) {
            if ($email_conf == 'Yes' ) {
                if ($postedusername === $username
                    && $postedpassword === $userpassword ){
                    if ($rememberme==1){
                        setcookie("adminusers_username", $username);
                        echo 1;
                        }else{
                        $_SESSION['adminusers_username'] = $username;
                        echo 1;
                    }
                }else {
                echo 'Password Incorrect!.';
                }
            }else{
            echo 'email not confirmed!.';
            }

        }else{
        echo 'acount closed!.';
        }
    }else {
    echo 'email not exist!.';
    }
}else {
echo 'insert Username and Password!.';
}

A: change
&& $_REQUEST['adminusers_password']!=0) {

to
&& $_REQUEST['adminusers_password']!='') {


text:
Q: how to upload multiple files in php? i have this code in html
<input type="file" name="file" id="file1"/>

<input type="file" name="file" id="file2"/>

here is my php code
if(!empty($_FILES['image']['name'])) {
            $ext=explode('.',$_FILES['image']['name']);
            $new_name=$property_id."_".rand(10,10000).".".end($ext);
            $name=SITEPATH.S_LOCATIONS_LARGE.$new_name;
            $small=SITEPATH.S_LOCATIONS.$new_name;
            move_uploaded_file($_FILES['image']['tmp_name'],$name);
            if(is_file($name)) {
                $this->db->update("insert into bloom_location_images (image,property_id) values ('$new_name',$property_id)");
                list($width, $height, $type, $attr) = getimagesize($name);
                if($width > 600) {
                    $this->magic->constrain_by_scale($name,500,0);
                }
                copy($name,$small);
                if($width > 301) {
                    $this->magic->constrain_by_scale($small,301,0);
                }
            }
        }

        return $property_id

now i want to store this two files but i cant. i think i have to pass it through array element. if yes then please tell me how is it possible
    please help me to do this

A: try this instead:
<input name="upload[]" type="file" multiple="multiple" />

of course add as many <input> as you want
PHP
your files will be available in the $_FILES array. So you can simply do something like this:
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
    $tmp = $_FILES['upload']['tmp_name'][$i];

    $path = "yourfolder/" . $_FILES['upload']['name'][$i];

    if(move_uploaded_file($tmp, $path)) {
         // your code here
    }
}

hope this helps

A: Change the name attribute not id and it will work.
Or meaby You could use something like that (HTML5 only):
How can I select and upload multiple files with HTML and PHP, using HTTP POST?

A: User array try name in form file element like this
<input name="image[]" type="file" multiple="multiple" />

And you will get upload data in $_FILES as array


text:
Q: Rails sunspot solr reindex error - undefined method 'includes' for Event:Class I am following up on a previous question that I posted a few months ago. I have a slightly different problem now, and I wasn't sure if the old question would get that much visibility from updating it. So, here is my situation:
I am working on a Ruby on Rails application that uses MongoDB, and I have implemented basic Sunspot functionality. Here is some information about my environment

*

*Rails 3.2.11

*Mongo 2.4.3

*Sunspot 2.0.0

*gem mongo_mapper

*gem sunspot_rails

*gem sunspot_solr

*gem sunspot_mongo_mapper

The three steps I need to run to get solr working are

*

*bundle exec rake sunspot:solr:start

*bundle exec rake db:seed

*bundle exec rake sunspot:solr:reindex
The first two run without any problems, however I get an error when I try the reindex command. This is the stacktrace
$ bundle exec rake sunspot:solr:reindex
rake aborted!
undefined method `includes' for Event:Class
/home/my_username/.rvm/gems/ruby-1.9.3-p429/gems/mongo_mapper-0.12.0/lib/mongo_mapper/plugins/dynamic_querying.rb:39:in `method_missing'
/home/my_username/.rvm/gems/ruby-1.9.3-p429/gems/sunspot_rails-2.1.0/lib/sunspot/rails/searchable.rb:254:in `solr_index'
/home/my_username/.rvm/gems/ruby-1.9.3-p429/gems/sunspot_rails-2.1.0/lib/sunspot/rails/searchable.rb:203:in `solr_reindex'
/home/my_username/.rvm/gems/ruby-1.9.3-p429/bundler/gems/sunspot_mongo_mapper-b6cf3edca97a/lib/sunspot/mongo_mapper/tasks.rb:21:in `block (3 levels) in <top (required)>'
/home/my_username/.rvm/gems/ruby-1.9.3-p429/bundler/gems/sunspot_mongo_mapper-b6cf3edca97a/lib/sunspot/mongo_mapper/tasks.rb:20:in `each'
/home/my_username/.rvm/gems/ruby-1.9.3-p429/bundler/gems/sunspot_mongo_mapper-b6cf3edca97a/lib/sunspot/mongo_mapper/tasks.rb:20:in `block (2 levels) in <top (required)>'
/home/my_username/.rvm/gems/ruby-1.9.3-p429/bin/ruby_noexec_wrapper:14:in `eval'
/home/my_username.rvm/gems/ruby-1.9.3-p429/bin/ruby_noexec_wrapper:14:in `<main>'
Tasks: TOP => sunspot:solr:reindex => sunspot:reindex
(See full trace by running task with --trace)

It has been a few months since I have worked with solr/sunspot, so I don't really understand the error. I saw this question, but when I try this answer I see this message
$ bundle exec rake sunspot:mongo:reindex
rake aborted!
Don't know how to build task 'sunspot:mongo:reindex'

In my stacktrace, what is "Event:Class"? And where can I find the "includes" method?
Any help in resolving this issue would be much appreciated!


text:
Q: pg_search using associated_against gives error "column [model_name].[associated_column_name] does not exist" I'm trying to use pg_search to search through an associated model.  When I run a search I get the error "PG::Error: ERROR:  column plans.name does not exist".  I'm running the search in the "plans" model and trying to search against association the "place" with a column "name".  The has_many :through model that connects these is polymorphic.  Somehow the sql query is combining the two and throwing an error.  I've run the associated_against migration (rails g pg_search:migration:associated_against), scoured the documentation, and looked for others with the error and come up with nothing, it must be that I'm just overlooking something.  It runs correctly (without the more extensive search results) if I just remove the associated_against line in plan.rb.  Any help would be appreciated!
Plan.rb:
class Plan < ActiveRecord::Base
    belongs_to :user
    has_many :plan_places, :dependent => :destroy
    has_many :places, through: :plan_places, source: :plan

    include PgSearch
    pg_search_scope :search, :against => [:title, :summary],
        associated_against: { places: [:name, :address]},
        using: {tsearch: {dictionary: "english"}},
        ignoring: :accents

    def self.text_query(query)
        if query.present?
          search(query)
        else
          scoped
        end
    end
end

Place.rb:
class Place < ActiveRecord::Base
    has_many :plan_places, as: :sortable #polymorphic -- could this be the issue??
    has_many :plans, through: :plan_places

   include PgSearch
        multisearchable :against => [:name, :address]
        pg_search_scope :search, against: [:name, :address],
            using: {tsearch: {dictionary: "english"}},
            ignoring: :accents
    def self.text_query(query)
            if query.present?
              search(query)
            else
              scoped
            end
    end
end

Controller:
def index
    query = params[:query]
    @plans = Plan.text_query(query)
  end

Full Error Message:
PG::Error: ERROR:  column plans.name does not exist
LINE 1: ...OUTER JOIN (SELECT "plans"."id" AS id, string_agg("plans"."n...
                                                             ^
: SELECT "plans".*, ((ts_rank((to_tsvector('english', unaccent(coalesce("plans"."title"::text, ''))) || to_tsvector('english', unaccent(coalesce("plans"."summary"::text, ''))) || to_tsvector('english', unaccent(coalesce(pg_search_ef8b0c36567cc241900c73.pg_search_1d546fcf34c118d2a7b8f6::text, ''))) || to_tsvector('english', unaccent(coalesce(pg_search_ef8b0c36567cc241900c73.pg_search_f3147101e01c522d780049::text, '')))), (to_tsquery('english', ''' ' || unaccent('giraffe') || ' ''')), 0))) AS pg_search_rank FROM "plans" LEFT OUTER JOIN (SELECT "plans"."id" AS id, string_agg("plans"."name"::text, ' ') AS pg_search_1d546fcf34c118d2a7b8f6, string_agg("plans"."address"::text, ' ') AS pg_search_f3147101e01c522d780049 FROM "plans" INNER JOIN "plan_places" ON "plan_places"."plan_id" = "plans"."id" INNER JOIN "plans" "places_plans" ON "places_plans"."id" = "plan_places"."plan_id" GROUP BY "plans"."id") pg_search_ef8b0c36567cc241900c73 ON pg_search_ef8b0c36567cc241900c73.id = "plans"."id" WHERE (((to_tsvector('english', unaccent(coalesce("plans"."title"::text, ''))) || to_tsvector('english', unaccent(coalesce("plans"."summary"::text, ''))) || to_tsvector('english', unaccent(coalesce(pg_search_ef8b0c36567cc241900c73.pg_search_1d546fcf34c118d2a7b8f6::text, ''))) || to_tsvector('english', unaccent(coalesce(pg_search_ef8b0c36567cc241900c73.pg_search_f3147101e01c522d780049::text, '')))) @@ (to_tsquery('english', ''' ' || unaccent('giraffe') || ' '''))))  ORDER BY pg_search_rank DESC, "plans"."id" ASC, created_at DESC

A: I ended up using a somewhat hacky workaround if someone else experiences this.  In the plan model's search method, I just run the search on the child model (places), get the associated plans of the results using the has_many :through table (plan_places), and append this list to the regular plan search results.  It's ugly and probably very inefficient, so if anyone knows a "real" answer please submit!
def self.text_query(query)
    if query.present?
      place_ids = Place.text_query(query).map(&:id).uniq
      plan_ids = PlanPlace.where(sortable_id: place_ids, sortable_type: "Place").map(&:plan_id).uniq
      plans = find(plan_ids)
      plans = plans + search(query)
    else
      scoped
    end
  end


text:
Q: How to add custom permission for a role in liferay 6.2 ga3 i want to add a new role on which i need to assign new set of permission (custom permissions).trying to do this in liferay 6.2 ga3 with tomcat and mysql as DB.
Eg: the new role will be ticket admin and the new permission i want to assign to him is "book ticket".

A: If you're creating a new role in Administration you can create a hook to override custom creation Roles and add your new ones.
Also you can create your roles and provide custom fields for them, managing you own permissions in your portlets (this is a really flexible way to do it when it has a deep logic) retrieving that customfields with expandoBridge mechanism.


text:
Q: Why is accepts_nested_attributes_for not working as expected? I am trying to figure out why my create is not working. If I have the following two models below
class Product < ActiveRecord::Base
  belongs_to :product_template
  has_many :presentations, through: :product_presentations
  has_many :product_presentations

  accepts_nested_attributes_for :product_presentations

  validates :start_date, :product_template_id, presence: true
  validates :start_date, uniqueness: true
end

class ProductPresentation < ActiveRecord::Base
  belongs_to :product
  belongs_to :course
  belongs_to :presentation

  validates_presence_of :product_id, :course_id, :presentation_id
  validates_uniqueness_of :presentation_id, :scope => :product_id
end

And I enter the following into my console.
product = Product.new(
{"start_date"=>"Sat, 06 Sep 2014 00:00:00 +0200",
"product_template_id"=>"5", "product_presentations_attributes"=>{
  "0"=>{"course_id"=>"1", "presentation_id"=>"1"},
  "1"=>{"course_id"=>"2", "presentation_id"=>"2"}}})

It should save, but I get the error below
#<ActiveModel::Errors:0x007f9eaeb9d698 @base=#<Product id: nil, product_template_id: 5, start_date: "2014-09-05 22:00:00", created_at: nil, updated_at: nil>, @messages={:"product_presentations.product_id"=>["can't be blank"]}>

Now I understand that there is not product_id in the product_presentations_attributes hash, but I thought this would be rails automigically populated because it's being created via the product.
I had this working and now I can't figure out how I messed it up. Any help appreciated.

A: Cool ... after posting this, reading over my own post I tried to remove the validation for the product_id presence.
This seems to fix the error.
I am guessing that this is a limitation of accepts_nested_attributes_for in rails - the parent object cannot have it's foreign key validated in the model.


text:
Q: lower accuracy is not reflected in AUC in biased data set? X_train = {my training data features}
y_train = {my training data truth}

kf = KFold(n_splits=5, random_state=42, shuffle=True)
score = cross_val_score(SVC(), X_train, y_train, scoring = 'accuracy', cv = kf, n_jobs = -1)

gives this:
array([1.        , 0.98717949, 1.        , 1.        , 0.98701299])
I run this code to get AUC:
tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)
plt.figure(figsize=(10,10))
i = 0
for train, test in kf.split(npX_train):
    model = SVC(probability=True).fit(npX_train[train], npy_train[train])
    probas_ = model.predict_proba(npX_train[test])
    # Compute ROC curve and area the curve
    fpr, tpr, thresholds = roc_curve(npy_train[test], probas_[:, 1])
    tprs.append(interp(mean_fpr, fpr, tpr))
    tprs[-1][0] = 0.0
    roc_auc = auc(fpr, tpr)
    aucs.append(roc_auc)
    plt.plot(fpr, tpr, lw=1, alpha=0.3,
             label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc))

    i += 1
plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',
         label='Chance', alpha=.8)

mean_tpr = np.mean(tprs, axis=0)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
std_auc = np.std(aucs)
plt.plot(mean_fpr, mean_tpr, color='b',
         label=r'Mean ROC (AUC = %0.2f $\pm$ %0.2f)' % (mean_auc, std_auc),
         lw=2, alpha=.8)

std_tpr = np.std(tprs, axis=0)
tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,
                 label=r'$\pm$ 1 std. dev.')

plt.xlim([-0.01, 1.01])
plt.ylim([-0.01, 1.01])
plt.xlabel('False Positive Rate',fontsize=18)
plt.ylabel('True Positive Rate',fontsize=18)
plt.title('Cross-Validation ROC of SVM',fontsize=18)
plt.legend(loc="lower right", prop={'size': 15})
plt.show()

which gives me this:

but if I get a confusion matrix for each iteration:
for train, test in kf.split(npX_train):
    model = SVC(probability=True).fit(npX_train[train], npy_train[train])

    # make confusion matrix plot for iteration
    y_pred = model.predict(npX_train[test])
    cm = confusion_matrix(npy_train[test], y_pred)
    cm_display = ConfusionMatrixDisplay(cm).plot()
    plot_confusion_matrix(model, npX_train[test], npy_train[test])
    plt.plot()

The accuracy for label 1, which I care about does not look that great. Of the 22 true label 1, seems to get it right 20 times out of all runs.

My questions are:

*

*Did I mess up that AUC plot or is that slight bend in the blue mean ROC line reflecting the inaccuracy of the model?

*Is there a better way to evaluate accuracy for a biased input where I care about the accurate prediction of the more rare event?

A: For biased or imbalanced datasets use the metric F1 score. F1 score uses precision and recall.
Read for more detail on f1 score
https://medium.com/analytics-vidhya/accuracy-vs-f1-score-6258237beca2
Sklearn
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html


text:
Q: Position text under each other and stretch Here is my CSS code;
#nav a {
  display:block;
  background: #1a1a1a;
  color: #fff;
  text-decoration: none;
  padding: 20px;
  text-transform: uppercase;
  font-size: 11px;
  letter-spacing: 1px;
  text-shadow: 0 -1px 0 #000;
  width: 100%;
  height: 100%;
  position: static;
  float:left;

  }

Here is the problem:

I'm trying to make each item have it's own line (on the image you can see re-tweets and likes are on the same line), when they should be on a separate line. Also, as you can see by looking at the re-tweets and likes background, it doesn't stretch to the red border because the text isn't long enough. How would I make the background stretch to the border width? Here is more code used for this section;
  /* submenu positioning*/
  #nav ul {
  position: absolute;
  z-index: 1;
  left: -99999em;
  width: auto;
  height: auto;
  border: 1px solid #A81E1E;

}

Another example of the background not stretching:

A: You can add dsiplay:block to the li.
#nav li {
    position: relative;
    margin: auto !important;
    display: block;
}


text:
Q: What happens when someone teleports when Nautilus' Depth Charge is chasing them?
Possible Duplicate:
What happens if the target of Nautilus's ult teleports?

Nautilus' ultimate, Depth Charge, fires a shockwave that chases the enemy champion and explodes when it reaches them. What happens if the enemy recalls to base while the shockwave is chasing them?

A: It has a range. This has happened to me before, and it went about halfway across the map before it just disappeared and took his cooldown.

A: Source from Xypherous, Nautilus' technical designer:

If they are more than 2000 units away from Nautilus - it will detonate on the spot.

So it will explode after a certain amount of follow-distance.


text:
Q: GIT warning: unsupported ssl version tlsv1.2: using default I am trying to clone a git repository and receiving the following warning and error message:
Cloning into 'projectname'...
warning: unsupported ssl version tlsv1.2: using default
* Couldn't find host <HOST> in the .netrc file; using defaults
*   Trying <IP ADDRESS>...
* Connected to <HOST> (<IP ADDRESS>) port 443 (#0)
* Unknown SSL protocol error in connection to <HOST>:-9838
* Closing connection 0
fatal: unable to access 'https://<HOST>/ios/ios-app.git/': Unknown SSL protocol error in connection to <HOST>:-9838

I am using:
OS X El Capitan (10.11.3)
Git client (2.6.4)
OpenSSL (1.0.2e)
Can you help me out what's wrong?

Update:
I created another user on my computer and there the cloning works. Only my user has the problem. Where can the problem lie?

A: Removed the following lines from my .gitconfig file:
http.sslverify=false
http.postbuffer=157286400
http.sslversion=tlsv1.0
credential.helper=cache --timeout=3600

I am not sure which one blocked my connection to the remote. Maybe the http.sslversion=tlsv1.0. I hope this helps somebody else too.


text:
Q: Python 2.7 string concatenation odd timing results The question has been asked about which is the fastest method of string concatenation, and very often the answer is ''.join() or %s.  However, I just ran a test and am getting significantly faster times with +=, to the tune of less than 1% the time of any other option.
My question is this: why do my results differ so much from other answers I've read?  Is this case particularly unique?
NOTE: I am running this in Python 2.7 and have no intention on migrating to 3 any time soon.
UPDATE: Per @Coldspeed's comments, this code has been updated using timeit.  Results seem to be on par with previous run.
Code:
import timeit

print '+=        : ' + \
str(timeit.Timer("new_string=''\nlong_string='lksjdliu3l9809c8098welkjwelrkjv99v8wfwlkj3'\n" +
    "for i in range(10000): new_string += long_string").timeit(number = 5))

print "''.join() : " + \
str(timeit.Timer("new_string=''\nlong_string='lksjdliu3l9809c8098welkjwelrkjv99v8wfwlkj3'\n" +
    "for i in range(10000): new_string = ''.join((new_string, long_string))").timeit(number = 5))

print "%s        : " + \
str(timeit.Timer("new_string=''\nlong_string='lksjdliu3l9809c8098welkjwelrkjv99v8wfwlkj3'\n" +
    "for i in range(10000): new_string = '%s%s' %(new_string, long_string)").timeit(number = 5))

print "{}      : " + \
str(timeit.Timer("new_string=''\nlong_string='lksjdliu3l9809c8098welkjwelrkjv99v8wfwlkj3'\n" +
    "for i in range(10000): new_string = '{}{}'.format(new_string, long_string)").timeit(number = 5))

Results (run multiple times, always roughly the same):
+=        : 0.00943579411126
''.join() : 2.76879656576
%s        : 2.13202393986
{}        : 1.60845005433


text:
Q: C# Initialize object with parallel task or some other way I have a class constructor with something like:
AuthenticationService = new AuthenticationService();

However this "variable initialization" may take some seconds and sometimes the father class may still not need it.
How can I use parallel programming in order to initialize it and still let the "father" class continue and only wait when he needs to use it and the object AuthenticationService is still not ready.
How can I do this?
My Solution (thanks to Jon Skeet)
    private Task<AuthenticationService> authTask;
    public AuthenticationService AuthenticationService
    {
        get
        {
            return authTask.Result;
        }
    }

    public MyConstructor(){
          authTask = Task.Factory.StartNew(() => new AuthenticationService());
    }

A: You could use a Task:
Task<AuthenticationService> authTask =
    Task.Factory.StartNew(() => new AuthenticationService);

// Do other things here...

// Now if we *really* need it, block until we've got it.
AuthenticationService authService = authTask.Result;

Note that the Result property will block the current thread until the result is available. If you were using C# 5, you might want to consider using an asynchronous method instead, in which case you could await the task.


text:
Q: Manipulating text with symbols in PowerPoint using VBA I am trying to use VBA to manipulate text in a PowerPoint.
I have formatted text in a frame with greek symbols, superscript and subscript.
I want to divide that text into two frames.
For example I use something like this:
Dim frame1Text As String
Dim frame2Text As String
Set frame1 = ActivePresentation.Slides(1).Shapes(1).TextFrame
Set frame2 = ActivePresentation.Slides(1).Shapes(2).TextFrame
frame1Text = frame1.TextRange.Text
frame2Text = Right(frame1Text, Len(frame1Text) - 10)
frame1Text = Left(frame1Text, Len(frame1Text) - Len(frame2Text))
frame1.TextRange.Text = frame1Text
frame2.TextRange.Text = frame2Text

As a result there are symbols and formatting lost. Is there any way to make it better?
Thanks for any help.

A: If possible, I would duplicate the shape and then delete what you don't want in the text. That way all formatting will be retained, character-by-character. Something along the lines of this:
Option Explicit

Sub CopyText()
  Dim oShp1 As Shape
  Dim oShp2 As Shape

  Set oShp1 = ActivePresentation.Slides(1).Shapes(1)
  oShp1.Copy
  ActiveWindow.View.Slide.Shapes.Paste

  Set oShp2 = ActivePresentation.Slides(1).Shapes(ActivePresentation.Slides(1).Shapes.Count)

  With oShp1.TextFrame.TextRange
    .Text = Left(.Text, 10)
  End With

  With oShp2.TextFrame.TextRange
    .Text = Right(.Text, Len(.Text) - Len(oShp1.TextFrame.TextRange.Text))
  End With
End Sub


text:
Q: Connect to a database running in a docker container via a local mysql client i.e. workbench I have a mysql database running in a docker container
docker ps
6496a209cb30   mysql:5.7.22           "docker-entrypoint.s…"   34 minutes ago   Up 34 minutes   0.0.0.0:3317->3306/tcp, :::3317->3306/tcp    db

I'm able to login to this container via a shell and run queries fine
docker exec -it db bash

Why am I unable to connect to the same container via a mysql client on my local machine (using mysql workbench)?

Here's my docker-compose.yml config;
 #MySQL Service
  db:
    image: mysql:5.7.22
    container_name: db
    restart: unless-stopped
    tty: true
    ports:
      - "3317:3306"
    environment:
      MYSQL_DATABASE: laravel
      MYSQL_ROOT_PASSWORD: password
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    volumes:
      - dbdata:/var/lib/mysql/
      - ./mysql/my.cnf:/etc/mysql/my.cnf
    networks:
      - app-network

For the Hostname field - I've tried 127.0.0.1 & db;- the name of the running container with no success?

A: This is due to the fact that your MySQL client is forcing an SSL connection, more specifically TLS 1.2 or higher.
A quick solution to this is to turn off SSL from your mysql workbench.

This will not force SSL/TLS and you will be able to connect to the database


text:
Q: What does '/bin/bash: line 2: 30063 Killed' mean? I'm trying to install ps2dev a homebrew playstation 2 development toolchain and SDK But I'm having trouble compiling gcc 11.1.0 it stops at
make[2]: Entering directory '/home/david/ps2toolchain-ee/build/gcc/build-mips64r5900el-ps2-elf-stage1/gcc'
build/genautomata ../../gcc/common.md ../../gcc/config/mips/mips.md \ insn-conditions.md > tmp-automata.c
/bin/bash: line 2: 16577 Killed
build/genautomata ../../gcc/common.md ../../gcc/config/mips/mips.md insn-conditions.md > tmp-automata.c
make[2]: *** [Makefile:2459: s-automata] Error 137
make[2]: Leaving directory '/home/david/ps2toolchain-ee/build/gcc/build-mips64r5900el-ps2-elf-stage1/gcc'
make[1]: *** [Makefile:4410: all-gcc] Error 2
make[1]: Leaving directory '/home/david/ps2toolchain-ee/build/gcc/build-mips64r5900el-ps2-elf-stage1'

I'm quite litterally using my android phone running a linux emulator called UserLAnd running debian/ubuntu
Android Version
8.1.0 (Oreo)
Model
Alcatel TCL LX A502DL
Chipset
Mediatek MT6739WM
CPU
4x ARM Cortex-A53 @ 1105 MHz (1.1 GHz)
GPU
PowerVR GE8100
Instruction Set
64-bit ARMv8-A (32-bit Mode)
RAM
2GB
Internal Storage
16GB

A: /bin/bash: line 2: 16577 Killed Means that the process with the PID 16577 got killed.  A bash script ran this process, and the OS Killed it independently for some reason.

"Killed" indicates a SIGKILL, which can be generated by the kernel.
One possible reason is if the process tries to go over a resource
limit, or possibly if the system runs out of memory. It could also be
something that UserLand generates for whatever reason, perhaps because
the process is trying to use a system feature that UserLand doesn't
provide. When attempting to compile GCC with only 2GB of RAM, the OOM
killer (triggered by running out of RAM) is plausible.

Some of the possible reasons are listed by Gilles 'SO - stop being evil'


text:
Q: On the evaluation of the mean-square limit: an example In this answer the mean-square limit of a succession of stochastic processes $Q_n$ is calculated in this simple way:

*

*Check whether the limit of their mean value is finite or not:
$$\tag{1}\displaystyle \lim_{n\to\infty}\operatorname{ E}[Q_n]=:Q\lt\infty$$

*Make sure that the variance vanishes in the limit:
$$\tag{2}\displaystyle \lim_{n\to\infty}\operatorname{Var}[Q_n]=0.
$$
If both $(1)$ and $(2)$ are realized, then $Q$ is shown to be the mean square limit of $Q_n$. Is this a general strategy? According to what theorem?


text:
Q: What is the difference between International English and other dialects of English? What makes International English worthy of the "International" title, and not, say, British English, or American English?

A: Expressed simply, "International English" is an idea. It is "worthy" of the title because it is that version of English which is useful internationally. It represents those elements of the English language which are usefully learnt, as a second or additional language, by those, outside the zones where English is the (or an) official language. As such it is 'decentered' (or 'decentred' if you prefer). Attempts to create a version of English separate from the American or British "centres" include Basic Global English, based on a 750 word vocabulary, Basic English, Threshold Level English, and others. International English reaches toward cultural neutrality. According to this viewpoint, International English is a concept of English that minimises the aspects defined by either the colonial imperialism of Victorian Britain or the cultural imperialism of the 20th century United States. The International English Language Testing System, or IELTS, is an international standardized test of English language proficiency for non-native English language speakers. It is jointly managed by the British Council, IDP: IELTS Australia and Cambridge Assessment English, and was established in 1989.
International English
IELTS


text:
Q: Como trabalhar com if e else? Bom dia.
Gostaria de Obter ajuda de vocês para montar esse código pois não estou conseguindo implementa-lo.
$query1 = "INSERT INTO paciente VALUES ('NULL, $nome_paciente, $nome_doutor')";

$id_paciente = mysql_insert_id();

$query2 = "INSERT INTO servico VALUES ('NULL, tipo_servico, data_servico,{$id_paciente})";

$id_servico = mysql_insert_id();

$query3 = "INSERT INTO estagio VALUES ('NULL, {$id_servico}, data_estagio, tipo_estagio')";

No seguinte padrão:
if (@mysql_query(INSERT INTO cad_paciente VALUES (NULL, $nome_paciente, $nome_doutor))) {

if(mysql_affected_rows() == 1){
    echo "Registro efetuado com sucesso
";
}

}

Nesse padrão acima consigo inserir apenas um registro numa tabela como faço para continuar a inserção.

A: Pelo o que eu entendi você deve informar o que quer inserir onde .. Uma boa dica para ficar bem claro e organizado é usando a função sprintf() do PHP.
Tenta mais ou menos assim:
<?php

$q = mysql_query(
    sprintf(
        "INSERT INTO cad_paciente (id, nome, doutor) VALUES ('%s', '%s', '%s')",
        "NULL",
        $nome_paciente,
        $nome_doutor
    )
);

if($q) {
    echo "Registro efetuado com sucesso
";
}

Neste exemplo, a função sprintf() está recebendo uma string que recebe 3 chaves, que são os %s dentro do código. Ele pega estas chaves dentro da primeira string e substitui pelos parâmetros subsequentes que são passados na função.
Espero que seja esta a sua dúvida e que eu a tenha respondido .. Abs.
UPDATE
É vivendo e aprendendo, rsrs
Baseado na sua dúvida e usando este post como referência eu consegui entender e executar o bloco de inserção de uma única vez com o mysqli.
Segue o código que acho que resolverá seu problema e sanará sua dúvida ..
<?php

// cria conexão com o banco de dados usando o classe mysqli orientado a objetos
$conn = new mysqli("localhost", "root", "", "test");

$deuCerto = true;

// começa a transação
$conn->query("START TRANSACTION");

if($deuCerto) {
    $query1 = $conn->query("INSERT INTO paciente VALUES (NULL, '".$nome_paciente."', '".$nome_doutor."')");
    $id_paciente = $query1->insert_id;
    // se falhar, para o restante do código
    if(!$query1) {
        $deuCerto = false;
    }
}

// se na insert anterior não tiver sucesso, não executa mais
if($deuCerto) {
    $query2 = $conn->query("INSERT INTO servico VALUES (NULL, '".$tipo_servico."', '".$data_servico."', ".$id_paciente.")");
    $id_servico = $query2->insert_id;
    if(!$query2) {
        $deuCerto = false;
    }
}

// se na insert anterior não tiver sucesso, não executa mais
if($deuCerto) {
    $query3 = "INSERT INTO estagio VALUES (NULL, '".$id_servico."', '".$data_estagio."', '".$tipo_estagio."')";
    $id_estagio = $query3->insert_id;
    if(!$query3) {
        $deuCerto = false;
    }
}

// se nenhuma das inserções derem erro, irá inserir tudo de uma vez
if($deuCerto) {
    $conn->query("COMMIT");
} else { // se houver algum erro, desfaz todos as alterações
    $conn->query("ROLLBACK");
}


text:
Q: Is there any way to give Boxcars 15 Med-X? Boxcars says that, since I'm the Powder Gangers' "Grim [expletive] Reaper," if I give him 15 Med-X, he'll OD and die for me.
But my only options (while carrying 43 Med-X's) are 1, 2, 3 and 5. If I give him 5, I don't seem to have an option to give him more.
Is there any way to get him to OD? Or if I'm playing pro-NCR (who would kill him anyway), is my only in-character option to shoot him?

A: You cannot OD him to death, the only answer is shooting.
However MINOR SPOILER:

 You'll need him for another quest, later on.


text:
Q: ListView with ArrayAdapter showing only 1 item for height wrap_content I'm having a issue where my ListView is displaying only one row even though ArrayList containing data has 2 items in it.

For clarification, YES, I'm using ListView inside a ScrollView but to balance it out I'm using custom ExpandableHeightListView (retrieved from one of the answers on SO) which is useful for exactly this purpose. This ListView is not scrollable. It has fixed height.

Also, within the same ScrollView, couple of other ListView are working fine but this one ListView is not working properly.
Going further, when I logged the position variable value inside getView() method, it's always 0 for this ListView while for other ListView, it's increasing sequentially.
I've compared both Adapter's code and they are identical but still current ListView is not working.
I tried with overriding getView() method, but to no avail.
Any help appreciated.
EDIT
If I give fixed height to ListView like 250dp, both the rows are getting displayed but it shows only 1 row with height set to wrap_content

A: As I know that ListView within a scrollView does not worked properly.
Because both widget has scroll so they does not worked well.
So I recommend to delete the ScrollView
Thanks..

A: I know this is not what you want to hear, but seriously, whatever you are programming, consider displaying it on tabs or similar, such that you don't need the scrollview.
If you really must have so much data on one screen, consider using something like a LinearLayout with an adapter to display your data.
Listviews are not designed to work inside a scrollview because they are scrollable themselves. You can "hack" your way around it, but it's not nice. If you really need the features that listviews provide, consider splitting up your screens into tabs, displaying a listview or two in each tab.

A: This solution worked for me and also adjusts the layout automatically. On the top-level ListView adapter, inside the getView() method, you will create a view that references a layout with another ListView. Assuming that "inner" ListView is declared as "listView" with its adapter called "adapter", try using the code below. Also, ensure that the inner ListView layout is set to WRAP_CONTENT, so that even if the height is correct, it is not being overridden by the layout constraints.
listView.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            listView.getLayoutParams().height = adapter.getCount() * {whatever your list item height is}  OR do something else to add up all of the heights;
            listView.requestLayout();
            listView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    }
);


text:
Q: Parameters for loading PDF files in MuPDF with different resolution I'm running MuPDF in Windows 8.1. It works fine for the most part (it allows file association). But there are no CFG/INI files for manipulating parameters and no app-specific option menu in the window. That has to be done from the command line.
The tedious part comes in for the default resolution (72 dpi). Naturally some files are rendered smaller than I would prefer for viewing. The command syntax (from the Run window) is as follows:
>(PATH to mupdf.exe) -r** (PATH to file.pdf)

I'd like to set up a batch file that performs the same function as the above command, except I want an option to change the resolution. This is what I've written so far.
@echo off
start C:\Users\name\mupdf\mupdf.exe %1 (this last option seems to be redundant)
(Do I need a CLS here?)
exit

This opens a window that lets me pick the PDF I want to open. So that part works fine. I just need to know how to change the -r flag.

A: According to the documentation I found in the package here (man\mupdf.txt):

OPTIONS
-r resolution
Changes the initial zoom level, specified as the  resolution  in dpi.  The default value is 72.

So, your batch should be something like this:
start C:\Users\name\mupdf\mupdf.exe -r 96 (path to file)

Where 96 is the desired resolution.


text:
Q: AWS role vs iam credential in duckdb HTTPFS call I am pretty baffled and I don't know what is going on with this one.
I'm using DuckDB to query parquet files in an s3 bucket.
import pandas as pd
import duckdb

query = """
    INSTALL httpfs;
    LOAD httpfs;
    SET s3_region='us-west-2';
    SET s3_access_key_id='key';
    SET s3_secret_access_key='secret';
    SELECT
        FROM read_parquet('s3://bucket/folder/file.parquet')

cursor = duckdb.connect()

cursor.execute(query).df()

I have an IAM user with admin access. I am able to query this parquet file with programatic access keys. I also have a role that I want to use in an application that I have also given admin access just for testing purposes.
When I assume the role and create temporary credentials and input those into the code above
export $(printf "AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s" \
$(aws sts assume-role \
--role-arn arn:aws:iam::<account-id>:role/<role-name> \
--role-session-name test-session \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
--output text))

I get the error

duckdb.Error: Invalid Error: Unable to connect to URL
"s3://bucket/folder/file.parquet": 403 (Forbidden)

However, when I use my IAM user, I am able to access this s3 object and query the data just fine. Is there something I am missing about the difference between roles and IAM users?
If it helps, what I am trying to do is create a role for a lambda function and then access the environmental variables AWS_ACCESS_KEY_ID, and AWS_SECRET_ACCESS_KEY with os.getenviron() in the code above. I believe if I can get the role working by writing in the temporary credentials it should work when I use os.getenv() in the lambda function.

A: I had a very similar issue, after also setting the s3_session_token via SET s3_session_token='sessiontoken'; it worked.
The code would be changed to
import pandas as pd
import duckdb

query = """
    INSTALL httpfs;
    LOAD httpfs;
    SET s3_region='us-west-2';
    SET s3_access_key_id='key';
    SET s3_secret_access_key='secret';
    SET s3_session_token='session-token';
    SELECT
        FROM read_parquet('s3://bucket/folder/file.parquet')

cursor = duckdb.connect()

cursor.execute(query).df()

A: If the other answers worn't help you, you might want to try setting another S3_region.
I got the same error message Error: Invalid Error: IO Error: Unable to connect to URL "s3://elsa-data-lake/transformed/20230228_041047_00038_yihfd_00629123-f824-4a31-ba70-e341d4028a3b.parquet": 400 (Bad Request)  but with different underlying problem. I set the wrong S3 region, thinking that S3 is a global service. I was using SET s3_region='us-east-1' because that is where our SSO service is set up, but I needed to specify the region where the file is stored on S3. So if I use SET s3_region='eu-west-1 everything works!
Here is a screenshot from the S3 console that shows that my file was stored in "EU (Ireland) eu-west-1".


text:
Q: python - django error "RuntimeError: doesn't declare an explicit app_label" I am struggling with a problem in using django. When I type python manage.py runserver, it holds for few seconds and keeps giving me a following message:

RuntimeError: Model class upload.models.ImgParent doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

I searched similar problems on the internet and tried to add 'upload.models.ImgParent' on INSTALLED_APPS in settings.py but it still doesn't work.
My current INSTALLED_APPS in settings.py looks like this:
INSTALLED_APPS = [

    'search.apps.SearchConfig',
    'upload.apps.UploadConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'mod_wsgi.server',
    'home',
]

and my apps.py looks like this:
class UploadConfig(AppConfig):

    name = 'upload'

edit, this is full traceback:
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
    raise _exception[0](_exception[1]).with_traceback(_exception[2])
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/apps/config.py", line 134, in create
    % (mod_path, cls_name, ', '.join(candidates))
django.core.exceptions.ImproperlyConfigured: 'upload.apps' does not contain a class 'uploadConfig'. Choices are: 'UploadConfig'.

Traceback (most recent call last):
  File "manage.py", line 19, in <module>
    execute_from_command_line(sys.argv)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 60, in execute
    super().execute(*args, **options)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 95, in handle
    self.run(**options)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 102, in run
    autoreload.run_with_reloader(self.inner_run, **options)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 579, in run_with_reloader
    start_django(reloader, main_func, *args, **kwargs)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 564, in start_django
    reloader.run(django_main_thread)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 272, in run
    get_resolver().urlconf_module
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 564, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/edwardkim/syseng/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/edwardkim/syseng/Foram_Tagger_Team43_Software/projectsite/projectsite/urls.py", line 23, in <module>
    path('search/', include('search.urls')),
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/edwardkim/syseng/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/edwardkim/syseng/Foram_Tagger_Team43_Software/projectsite/search/urls.py", line 3, in <module>
    from . import views
  File "/home/edwardkim/syseng/Foram_Tagger_Team43_Software/projectsite/search/views.py", line 2, in <module>
    from upload.models import Img
  File "/home/edwardkim/syseng/Foram_Tagger_Team43_Software/projectsite/upload/models.py", line 3, in <module>
    class ImgParent(models.Model):
  File "/home/edwardkim/syseng/venv/lib/python3.6/site-packages/django/db/models/base.py", line 111, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class upload.models.ImgParent doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

Please help with my problem and let me know if you need any additional information. Thank you.


text:
Q: decompose the permutation $\sigma$ in cycle notation into an object A permutation of a set  is a bijection (one-to-one and onto) : → .
As an object a permutation $\sigma$ looks like this:
$$
    \begin{matrix}
    1 & 2 & 3 & 4 & 5 & 6\\
    2 & 3 & 1 & 4 & 6 & 5\\
    \end{matrix}
$$
They can also be written in terms of cycle notation which looks like this for the above permutation:
$(1,2,3),(4), and (5,6)$
I want to take the following permutation in cycle form and convert it into its form as an object.
$(1,3)(1,2)(4,5)$
It is the duplication of the $1'$s in two separate orbits that are throwing me off. I have been taught to go from right to left

A: You could multiply $(13)(12)(45)=((13)((12))(45)=(123)(45)$.  From there the object form is easy.

A: Just follow how the cycles act on elements. For instance (working right to left), we have for $(1\;2)(1\;3)\;(2\;3)$
$$
    \begin{matrix}
    1 & 2 & 3 \\
    3 & 2 & 1
    \end{matrix}
$$
For instance, tracking the action of this product acts on 2. First, it sends 2 to 3 then it sends that 3 to 1 then it sends that 1 to 2. Therefore, it fixes 2. Follow the action of elements similarly. [Note again, you may have been taught to compose left to right, rather than my right to left. It depends on the convention you are learning.]


text:
Q: How to bind an input type 'time' in knockout.js I assumed it was something like this but it doesn't work -
HTML:
<input id="timePicker" type="time" placeholder="HH:MM" required="" data-bind="value: timeFrom">

JS:
self.timeFrom = ko.observable("8:00");

A: It should be set to "08:00":
self.timeFrom = ko.observable("08:00");

JsFiddle


text: Q: TensorBook: can't enter Ubuntu desktop I have removed Nvidia drivers using sudo apt-get remove nvidia-* and now I can't enter desktop, I also get "A start job is running for Hold until boot process finishes up(time/no limit)", someone can help me without re-install Ubuntu? Thanks.


text:
Q: Rootless Docker (remote system) and VS Code - Attach VS Code to container failing I am using the following setup

*

*Remote system

*

*Running "rootless Docker"

*Docker context named "rootless" being active

*VS Code Docker extension being installed

*VS Code - Connecting via SSH to the remote machine using "Remote Extension"

*

*Building and runing the Docker container using rootless Docker

*Checking that the "rootless" Docker context is selected

*Trying to use "right-click" option on container "Attach Visual Studio Code", which will fail with the following error message:

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

VS Code tries to refer to the "default" Docker context, altouhgh the "rootless" Docker context is selected, which in my case is:
rootless *    Rootless mode    unix:///run/user/1001/docker.sock

Also when the "docker.host" is set to the one of the rootless Docker or if the "docker.context" is set to the "rootless", using "Attach Visual Studio Code" will fail with the same error message.
What did work out is the following:

*

*On local machine defining Docker context for remote
docker context create <some_name> --docker host="ssh://<user>@<ip address>

*VS Code - connected to local machine

*

*Selecting the Docker context of the remote machine

*Using "Attach Visual Studio Code" to attach to remote container

Does someone know how to fix the issue, so that it is possible to use "Attach Visual Studio Code" directly from the VS Code window being connected via ssh to the remote system?

A: My SSH config looks like this
Host remote
    HostName 1.2.3.4
    User ubuntu
    IdentityFile ~/.ssh/remote
    SetEnv DOCKER_HOST=unix:///run/user/1001/docker.sock
    SetEnv PATH=/home/ubuntu/bin:$PATH

I have created SSH key pair called remote, and the pair is under my local ~/.ssh/. For SetEnv you should have that information once you installed docker rootless.
In VS Code, I have one line in my user settings.json
"docker.host": "ssh://remote",

where "remote" is the name that matches my SSH config. After these steps you should be able to attach to your running remote container.


text:
Q: lower function in postgres How to use lower function in postgres to convert upper special chars to lower special chars. For exam: SELECT lower('Ş'). Its result is 'Ş' not 'ş'.

A: You have to choose the correct collation:
SELECT lower('Ş' COLLATE "C");
 lower
-------
 Ş
(1 row)

SELECT lower('Ş' COLLATE "az_AZ.utf8");
 lower
-------
 ş
(1 row)

If you do not choose a collation explicitly, it is taken from the collation of the column or (lacking that) the collation of the database which you can display with \l.
It is usually a good idea to choose the database collation wisely so that you don't have to specify a collation explicitly.


text:
Q: Comma Delimiter Issue I'm developing a C# based application and want to use "," (Comma) delimiter to split strings. The problem arrives when the comma is part of my string and not a delimiter (like we have in addresses for example).
Example:
Input: "A,B,Venus, New York 10001"
Actual output: "A", "B", "Venus", "New York"
Required output: "A", "B", "Venus, New York"
What is the best practice for this kind of issue?
Thanks.

A: I recommend you to take a look at dotctor and Zohar Peled comments. This could result in a more robust solution. However, if you still need to split the string as mentioned in your question you could do the following.
I notice that the input is split on a comma that is not followed by a whitespace. When there is a whitespace behind the comma the string should not be split. If this is always the case for your, then the following will work:
static void Main(string[] args)
{
    var result = SplitOnCommaNotFollowedByWhiteSpace("A,B,Venus, New York 10001");
    //Result: string["A", "B", "Venus, New York"]
}

public static string[] SplitOnCommaNotFollowedByWhiteSpace(string input)
{
    var regex = new Regex(@",(?!\s)", RegexOptions.IgnoreCase);
    return regex.Split(input);
}


text:
Q: I want to use the Corpus function, but I am unable to install the tm package for text mining in R 3.4.2 The error:

Warning in install.packages :   cannot open URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/tm_0.7-1.zip': HTTP status was '404 Not Found' Error in download.file(url, destfile, method, mode = "wb", ...) :    cannot open URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/tm_0.7-1.zip' Warning in install.packages :   download of package 'tm' failed

A: It can happen sometimes. My suggestion is to download the .zip or .tar.gz file from CRAN and install it through the user interface:
Tools -> Install packages -> Install from: "Package Archive File"


text:
Q: Passing generic Type from parent class to state class in flutter I want to create some widget to wrap a ListViewer and also make it generic so that it can be used for many types of data. But I could not be able to pass the Type from the parent class(GenericList) to extending child state class(_GenericListState). Can anybody explain me how can I pass types to child so that I can use that type and access its Provider.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class GenericList<T> extends StatefulWidget {
  final T providerType;

  const GenericList({Key? key, required this.providerType}) : super(key: key);

  @override
  State<GenericList> createState() => _GenericListState();
}

class _GenericListState extends State<GenericList> {
  @override
  Widget build(BuildContext context) {
    final list = Provider.of<T>(context);
    final items = list.map;

    return ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, int index) {
        return ListTile(
          onTap: () => index,
          title: Text(items[items.keys.elementAt(index)]!.name),
          trailing: Text(
            items[items.keys.elementAt(index)]!.totalSpending.toString(),
          ),
        );
      },
    );
  }
}

A: defining this way solved my problem but I did not understand why it works. Can somebody explain it to me?
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class GenericList<T> extends StatefulWidget {

  const GenericList({Key? key}) : super(key: key);

  @override
  State<GenericList<T>> createState() => _GenericListState<T>();
}

class _GenericListState<T> extends State<GenericList<T>> {
  @override
  Widget build(BuildContext context) {
    final list = Provider.of<T>(context);
    final items = list.map;
    ....
  }
}


text:
Q: IllegalStateException - removeView() in ViewPager I am trying to get working my Fragment with ViewPager but I am getting this error:
LogCat:
12-19 14:16:25.180: I/mFragment(5866): onCreate() LogicAnalizerActivity
12-19 14:16:25.235: I/mFragment(5866): FragmentAdapter Constructor
12-19 14:16:25.235: I/mFragment(5866): onResume() LogicAnalizerActivity
12-19 14:16:25.310: I/mFragment(5866): Page item 0
12-19 14:16:25.320: I/onCreate()(5866): onCreate LogicAnalizerView
12-19 14:16:25.350: D/AndroidRuntime(5866): Shutting down VM
12-19 14:16:25.355: W/dalvikvm(5866): threadid=1: thread exiting with uncaught exception (group=0x40d77300)
12-19 14:16:25.690: E/AndroidRuntime(5866): FATAL EXCEPTION: main
12-19 14:16:25.690: E/AndroidRuntime(5866): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewGroup.addViewInner(ViewGroup.java:3378)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewGroup.addView(ViewGroup.java:3249)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewGroup.addView(ViewGroup.java:3194)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewGroup.addView(ViewGroup.java:3170)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.support.v4.app.NoSaveStateFrameLayout.wrap(NoSaveStateFrameLayout.java:40)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:874)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:431)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:139)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.support.v4.view.ViewPager.populate(ViewPager.java:804)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1016)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.View.measure(View.java:15172)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.View.measure(View.java:15172)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.View.measure(View.java:15172)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.View.measure(View.java:15172)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2432)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.View.measure(View.java:15172)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1850)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1102)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1275)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.Choreographer.doCallbacks(Choreographer.java:555)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.Choreographer.doFrame(Choreographer.java:525)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.os.Handler.handleCallback(Handler.java:615)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.os.Looper.loop(Looper.java:137)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at android.app.ActivityThread.main(ActivityThread.java:4978)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at java.lang.reflect.Method.invokeNative(Native Method)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at java.lang.reflect.Method.invoke(Method.java:511)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
12-19 14:16:25.690: E/AndroidRuntime(5866):     at dalvik.system.NativeStart.main(Native Method)

ActivityFragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;

public class LogicAnalizerActivity extends SherlockFragmentActivity {

    private static final boolean DEBUG = true;
    /** Numero de paginas del ViewPager */
    private static final int pageCount = 1;

    private static ActionBar actionBar;
    private static ViewPager mViewPager;
    private static MyFragmentAdapter mAdapter;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        if(DEBUG) Log.i("mFragment","onCreate() LogicAnalizerActivity");

        actionBar = getSupportActionBar();
        setContentView(R.layout.fragment);

        mAdapter = new MyFragmentAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pagerLogicAnalizer);
        mViewPager.setAdapter(mAdapter);

        mViewPager.setCurrentItem(0);
        mViewPager.setOffscreenPageLimit(1);

    }

    @Override
    protected void onResume() {
        if(DEBUG) Log.i("mFragment","onResume() LogicAnalizerActivity");
        super.onResume();
    }

    /**
     * Crea el ActionBar desde el XML actionbarlogic que define los iconos en el mismo
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if(DEBUG) Log.i("onCreateOptionsMenu()", "onCreateOptionsMenu() -> LogicAnalizerView");
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.actionbarlogic, menu);
        return true;
    }

    public static class MyFragmentAdapter extends FragmentPagerAdapter{

        public MyFragmentAdapter(FragmentManager fm) {
            super(fm);
            if(DEBUG) Log.i("mFragment","FragmentAdapter Constructor");
        }

        @Override
        public Fragment getItem(int arg0) {
            if(DEBUG) Log.i("mFragment","Page item " + arg0);
            switch(arg0){
                case 0:
                    return new LogicAnalizerFragment();
                case 1:
                    return new LogicAnalizerFragment();
            }
            return new LogicAnalizerFragment();
        }

        @Override
        public int getCount() {
            return pageCount;
        }

        @Override
        public void destroyItem(View collection, int position, Object view) {
            if(DEBUG) Log.i("mFragment","Destroy item " + position);
            ((ViewPager) collection).removeView((LinearLayout) view);
        }

    }
}

LogicAnalizerFragment:
It is too long, you can see it here

Fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        android:id="@+id/pagerLogicAnalizer"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

The Fragment is correctly working, but when I try to use it with ViewPager I am getting this error, I have searched a lot of ViewPager examples and all are the same. I have added:
            @Override
            public void destroyItem(View collection, int position, Object view) {
                if(DEBUG) Log.i("mFragment","Destroy item " + position);
                ((ViewPager) collection).removeView((LinearLayout) view);
            }

to try to solve the problem but it persists.

A: Line 250,
return inflater.inflate(R.layout.logicanalizer, container);

add false;
 return inflater.inflate(R.layout.logicanalizer, container,false);

the 3rd params determins weather it should be attached to the 'container' or not, documents:

@3rd param attachToRoot   Whether the inflated hierarchy should be attached to the
  root parameter? If false, root is only used to create the correct
  subclass of LayoutParams for the root view in the XML.
@return The root View of the inflated hierarchy. If root was supplied
  and attachToRoot is true, this is root; otherwise it is the root of
  the inflated XML file.


text:
Q: Windows Update / Server 2008 R2 SP1 Fresh install of Server 2008 R2 with SP1 from disc. Installed all drivers and software needed. Go to Windows Update and change settings to download but NOT install. After 4 hours, it only downloads 3 updates.
Here's the last few lines of the log file:
2012-11-15  07:33:11:230    1004    b38 DnldMgr Regulation: {7971F918-A847-4430-9279-4A52D1EFE18D} - Update 55AA099F-30B0-4B1E-A6F0-242CA4CFCFDE is "Priority" regulated and can NOT download. Sequence 7591 vs AcceptRate 6738.
2012-11-15  07:33:11:230    1004    b38 DnldMgr Regulation: {7971F918-A847-4430-9279-4A52D1EFE18D} - Update 8885D85B-FCFF-468B-A677-BF5B17320257 is "Priority" regulated and can NOT download. Sequence 7591 vs AcceptRate 6738.
2012-11-15  07:33:11:230    1004    b38 DnldMgr Regulation: {7971F918-A847-4430-9279-4A52D1EFE18D} - Update 231BDBA2-E51F-4210-BD28-0BAB1BA17E33 is "Priority" regulated and can NOT download. Sequence 7591 vs AcceptRate 6738.
2012-11-15  07:33:11:230    1004    b38 DnldMgr Regulation: {7971F918-A847-4430-9279-4A52D1EFE18D} - Update 0257C940-6D4B-4278-9B5E-A6D88C06E10F is "Priority" regulated and can NOT download. Sequence 7591 vs AcceptRate 6738.
2012-11-15  07:33:11:230    1004    b38 DnldMgr Regulation: {7971F918-A847-4430-9279-4A52D1EFE18D} - Update 67F7824D-578E-4126-88A9-2642BEFBC16C is "Priority" regulated and can NOT download. Sequence 7591 vs AcceptRate 6738.
2012-11-15  07:33:11:246    1004    b38 Report  REPORT EVENT: {FF3D2E27-A036-4428-92D4-A8B20868DC2C}    2012-11-15 07:32:49:015-0500    1   162 101 {133BDE32-024C-48A6-BF83-393E21AF0548}  100 0   AutomaticUpdatesWuApp   Success Content Download    Download succeeded.
2012-11-15  07:33:11:246    1004    b38 Report  REPORT EVENT: {72231E4C-D335-46B3-85BC-A3A5A93ABA67}    2012-11-15 07:32:49:031-0500    1   188 102 {00000000-0000-0000-
2012-11-15  07:33:11:246    1004    b38 Report  REPORT EVENT: {D2DA71EB-4D6A-43D5-BB2C-
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  REPORT EVENT: {ECBF0A1A-C3B5-4628-A5BB-1887A2B99FC4}    2012-11-15 07:33:00:310-0500    1   147 101 {00000000-0000-0000-0000-000000000000}  0   0       Success Software Synchronization    Windows Update Client successfully detected 65 updates.
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1536    914 COMAPI  >>--  RESUMED  -- COMAPI: Search [ClientId = <NULL>]
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  REPORT EVENT: {6C051E8A-B775-493E-8E92-3BF95C5400A0}    2012-11-15 07:33:11:168-0500    1   147 101 {00000000-0000-0000-0000-000000000000}  0   0       Success Software Synchronization    Windows Update Client successfully detected 65 updates.
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:246    1004    b38 Report  CWERReporter finishing event handling. (00000000)
2012-11-15  07:33:11:292    1536    914 COMAPI    - Updates found = 65
2012-11-15  07:33:11:292    1536    914 COMAPI  ---------
2012-11-15  07:33:11:292    1536    914 COMAPI  --  END  --  COMAPI: Search [ClientId = <NULL>]
2012-11-15  07:33:11:292    1536    914 COMAPI  -------------
2012-11-15  07:33:16:175    1004    b38 Report  CWERReporter finishing event handling. (00000000)

A: You have to let those 3 updates install first.
They update WindowsUpdate itself.
Afterwards it will function more or less as expected.
Please note that at any time you may see that not all updates are offered because of the simple fact that some updates require that another update is installed first.
Such updates are only offered/downloaded after the installation of the requirede update(s).


text:
Q: How does recovery work when server is shutdown before a checkpoint? So for any query that makes changes to data:

*

*SQL Server pulls the page from disk into memory if it doesn't already exist in memory.

*Lock the page/row and make the data changes.

*Writes the changed to the log in memory.

*Release the page/row lock.

*Send acknowledgement to user

Then, whenever there is a checkpoint:

*

*Write the log to disk

*Write dirty page to disk

Suppose the server gets shutdown due to power failure just before a checkpoint. Then is the data from memory that wasn't burnt to disk lost? Or does SQL Server write the log to disk before sending acknowledgement to user?

A: In full durability, the default, the commit completes only when the data is physically written to the log file - it's only data pages that are later written to disk on checkpoint by the lazy writer.
There's a per-database setting called delayed durability that can override and allow the transaction to be committed but only written to the log file when the buffer is full, offering faster transactions but the risk of losing (as yet) unwritten committed transactions.
More info

A: You're right that there's a finely tuned choreography between disk, the buffer pool and the write-ahead log. Each part has to work with the others to guarantee consistent recovery after an un-planned shutdown. There are many choices to make and the sequence in which actions occur is critical to the success of the whole.
Most DBMS follow a protocol called ARIES published by IBM in 1992. Certainly SQL Server does. There's a readable overview here. This protocol's steps differ a little from the question's bullet points.
Somewhere before acknowledgement is sent to the user in step 5 the transaction has to be committed. This can be explicit (COMMIT statement) or implied (at the end of a statement without an explicit BEGIN TRANSACTION). At this point the write-ahead log records are forced to disk.

Log records are written to disk when the log buffers are flushed. This happens whenever a transaction commits or the log buffers become full.

As well as "before" and "after" copies of the changed data the log also receives "transaction start" and "transaction commit" records. Each log record has a Log Sequence Number (LSN). As data changes are written to the log the corresponding LSN is written to the data page in the buffer pool. Only the most recent LSN is required in each page. (You can read this value.)
During a checkpoint not only are dirty pages flushed, the fact a checkpoint happened is also written to the log and flushed. From a previous reference: "SQL Server has logic that prevents a dirty page from being flushed before the associated log record is written."
To answer the actual question - what if there's a failure before the dirty page can be checkpointed? On restart, the system reads the log. It discovers that there was a transaction, that wrote to our page, and  committed. It can read the required page back into the buffer pool. Because the just-read page contains the LSN of the most recent change made to it, the system knows what log records to re-apply -- everything after the page's LSN. Those records are re-applied and the transaction commited. Now the buffer pool contains our page as it was after our data change was made but before the outage.
In a similar way the protocol can deal with pages that were checkpointed while transactions that dirtied them were still open when the system failed, and with transactions that were rolled back before a checkpoint hardened the affected pages to disk.
There are a lot of details I've skimmed over and many corner cases that the full protocol handles (a second power loss while recovering from the first power loss?).
SQL Server 2019 introduced Accelerated Database Recovery which improves on ARIES to reduce the time required to recover from failure.