text:
Q: WordPress Send notification when I publish a Custom Post Type I want to send a notification web push when i publish a CPT named 'Notification' in WordPress.
$data = array(
'app_id' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'data' => array(
    'foo' => 'bar'
),
'headings' => array(
    'en' => 'Test Notifications API'
),
'contents' => array(
    'en' => 'Test Notifications API'
),
'url' => 'PAGE URL',
'include_player_ids' => [
  'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
]);

$data_string = json_encode($data);

$ch = curl_init('https://onesignal.com/api/v1/notifications/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string)
));
$result = curl_exec($ch);

I want to send $result when i publish my CPT 'Notification'.
Thanks for help.

A: You need to hook it to some action, for example save_post or transition_post_status or
function my_published_notification( $new, $old, $post ) {
     if ( $new === 'publish' && $new !== $old ) {
           // put whatever you want to do here
     }
}

add_action( 'transition_post_status', 'my_published_notification', 10, 3 );

For CPT you also  have some custom hooks options like like save_* or publish_* where * is myCPTname.
add_action( 'publish_myCPTname', 'my_published_notification', 10, 2 );

See more info ok hooks and actions to get more details.


text: Q: How to add remote event receiver to already created document library in SharePoint online? I have a document library which has different folders in it like Task 1 , Task 2 etc. Whenever user uploads a file inside any folder lets say Task 1 , i want to assign file property(Task Name) as Task 1 . I tried this with SharePoint Designer Workflow but it is taking time for calculations . Is there any way to do this ? I am thinking about Synchronous Remote Event Receivers .Any kind of suggestion will be helpful .

redpajama_set_name: RedPajamaStackExchange


text:
Q: SmtpException while sending mails from a particular mailing server My question may be duplicate one, but i didn't got a proper solution for my problem.That's why i am asking.
I have a asp website.I am using smtpclient to send messages.My code is working fine with gmail settings.But in the production server they are using Bellnetwork's(smtp10.on.aibn.com) mailing server.They are using port 25 and also not using SSL(email provider doesn't support SSL).But the same mail settings was running fine for the last 2-3 years,but now when we send some messages from our site(production) 1 or 2 fails to send out and others will send out successfully.The strange thing is there was no problem for the last 3years.I am getting the following errors for the failed mails.
Exceptions:
1.
 System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
   at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
   at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
   at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
   at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response)
   at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Handler.BLL.cSendMail.SendMail(String p_strFrom, String p_strDisplayName, String p_strTo, String p_strSubject, String p_strMessage, String strFileName)
2.

System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
3.

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 67.69.240.69:25
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 67.69.240.69:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
   --- End of inner exception stack trace ---
   at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
   at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
   at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
   at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Handler.BLL.cSendMail.SendMail(String p_strFrom, String p_strDisplayName, String p_strTo, String p_strSubject, String p_strMessage, String strFileName)
my code:
      public bool SendMail(string p_strFrom, string p_strDisplayName, string p_strTo, string p_strSubject, string p_strMessage , string strFileName)
     {
         try
         {
             p_strDisplayName = _DisplayName;
             string smtpserver = _SmtpServer;
             SmtpClient smtpClient = new SmtpClient();
             MailMessage message = new MailMessage();
             MailAddress fromAddress = new MailAddress(_From,_DisplayName);
             smtpClient.Host = _SmtpServer;
             smtpClient.Port = Convert.ToInt32(_Port);
             string strAuth_UserName = _UserName;
             string strAuth_Password = _Password;
             if (strAuth_UserName != null)
             {
                 System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strAuth_UserName, strAuth_Password);
                 smtpClient.UseDefaultCredentials = false;
                 if (_SSL)
                 {
                     smtpClient.EnableSsl = true;
                 }
                 smtpClient.Credentials = SMTPUserInfo;
             }
             message.From = fromAddress;

             message.Subject = p_strSubject;
             message.IsBodyHtml = true;
             message.Body = p_strMessage;
             message.To.Add(p_strTo);
             try
             {
                 smtpClient.Send(message);
                 return true;
             }
             catch (SmtpException ee)
             {
          Log.WriteSpecialLog("smtpClient mail sending first try failed : " + ee.ToString(),"");
          Log.WriteSpecialLog("status code : " + ee.StatusCode, "");
         }
       }

A: This code is working for me
 public static string sendMail(string fromEmail, string toEmail, string subject, string body, string Name, string bcc="" , string replyTo="")
    {
            MailMessage mailer = new MailMessage
                                     {
                                         IsBodyHtml = true,
                                         From = new MailAddress(fromEmail, "yoursite.com"),
                                         Subject = subject,
                                         Body = body,
                                         BodyEncoding = Encoding.GetEncoding("utf-8")
                                     };

            mailer.To.Add(new MailAddress(toEmail, toEmail));

            //
            if (!string.IsNullOrEmpty(bcc))
            {
                mailer.Bcc.Add(bcc);
            }
            //
            if (!string.IsNullOrEmpty(replyTo))
            {
                mailer.Headers.Add("Reply-To", replyTo);
            }
            //
            AlternateView plainView = AlternateView.CreateAlternateViewFromString(Regex.Replace(body, "<(.|\\n)*?>", string.Empty), null, "text/plain");

            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");

            mailer.AlternateViews.Add(plainView);
            mailer.AlternateViews.Add(htmlView);

            SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["SMTPserver"]);
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            //smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
          NetworkCredential basicAuthenticationInfo = new NetworkCredential(ConfigurationManager.AppSettings["passMail"], ConfigurationManager.AppSettings["passKey"]);
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = basicAuthenticationInfo;
            smtp.EnableSsl = false;
            smtp.Port = ConfigurationManager.AppSettings["Port"];
            //
                try
                {
                    smtp.Send(mailer);
                    return "Email sent successfully !";
                }
                catch (Exception ex)
                {
                      return "Failure in Email Message= !" + ex.message;
                }
    }


text:
Q: How can build a model that will predict duplicate records in your dataset? What are the algorithms that will predict duplicates in your dataset.
For example -
Name Marks
A    100
B     90
C     80
A    100

I need something like this -
Name  Marks S/D
A     100   Single
B     90    Single
C     80    Single
A     100   Duplicate

I'm looking for some algorithms that can help in this case.

A: IIUC, you need this:
import pandas as pd
df = pd.DataFrame({'Name':['A','B','C','A'],'Marks': [100, 90, 80, 100]})

df['res'] = df.duplicated().map({False:"Single", True:"Duplicated"})

Output:
>>> df
  Name  Marks         res
0    A    100      Single
1    B     90      Single
2    C     80      Single
3    A    100  Duplicated


text:
Q: How can you get a list of pull requests reviewed in a repository by a user from the GitHub API? On the GitHub website, it is possible to list PRs reviewed by a user for a specific repository with the filter query is:pr reviewed-by:your-github-username. See example.
But I can't find how to replicate this functionality using the GitHub API. Is there a query you can make that will do something like GET /repos/:owner/:repo/pulls/reviewedby/:reviewer?

A: The search endpoint turned out to be the key. Example request:
https://api.github.com/search/issues?q=+type:pr+repo=facebook/react+reviewed-by:bvaughn


text:
Q: Toggle Clickable LinearLayout I have a problem. I created a clickable LinearLayout, with a custom xml selector. Now when I focus the LinearLayout the design changes like the way I want. But when I release the LinearLayout it goes back to normal. I want to create some kind of toggle button, but with a LinearLayout. Here is the FULL code of the LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0e2a56"
    android:weightSum="100">
    <LinearLayout
        android:orientation="vertical"
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_weight="10"
        android:layout_height="0dp"
        android:id="@+id/linearLayout2" >
        <TextView
            android:text="Choose your shape:"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/textView1"
            android:textColor="#ffffffff"
            android:textStyle="bold"
            android:textSize="30dp"
            android:gravity="center_vertical" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_weight="100"
        android:layout_height="0dp"
        android:id="@+id/linearLayout1" >
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="0dp"
            android:layout_weight="50"
            android:layout_height="120dp"
            android:background="@drawable/TriangleShapeButton"
            android:id="@+id/btnTriangle"
            android:clickable="true"
            android:focusable="true">
            <ImageView
                android:src="@drawable/triangle3"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:id="@+id/imageView1"
                android:layout_gravity="center|center_horizontal" />
        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="0dp"
            android:layout_weight="50"
            android:layout_height="120dp"
            android:background="@drawable/HexagonShapeButton"
            android:id="@+id/btnHexagon"
            android:clickable="true"
            android:focusable="true">
            <ImageView
                android:src="@drawable/hexagon2"
                android:layout_width="90dp"
                android:layout_height="match_parent"
                android:id="@+id/imageView1"
                android:layout_gravity="center_horizontal|center_vertical"
                android:scaleX="1.2"
                android:scaleY="1.2"  />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

And here is the custom XML:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="false">
    <layer-list>
      <item android:right="5dp" android:top="5dp" android:bottom="5dp" android:left="5dp">
        <shape>
          <corners android:radius="2dp"/>
          <solid android:color="#000000"/>
        </shape>
      </item>
      <item android:right="2dp" android:top="2dp" android:bottom="2dp" android:left="2dp">
        <shape>
          <gradient android:angle="270" android:endColor="#082e72" android:startColor="#104bb2"/>
          <stroke android:width="1dp" android:color="#000000"/>
          <corners android:radius="4dp"/>
          <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp"/>
        </shape>
      </item>
    </layer-list>
  </item>
  <item android:state_pressed="true">
    <layer-list>
      <item android:right="5dp" android:top="5dp">
        <shape>
          <corners android:radius="2dp"/>
          <solid android:color="#D6D6D6"/>
        </shape>
      </item>
      <item android:right="2dp" android:top="2dp" android:bottom="2dp" android:left="2dp">
        <shape>
          <gradient android:angle="270" android:endColor="#6b9fff" android:startColor="#4064a5"/>
          <stroke android:width="3dp" android:color="#FFFFFF"/>
          <corners android:radius="4dp"/>
          <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp"/>
        </shape>
      </item>
    </layer-list>
  </item>
</selector>

I thought that I could just use this code:
LinearLayout btnTriangle = view.FindViewById<LinearLayout>(Resource.Id.btnTriangle);
btnTriangle.Click += (sender, e) => {
    btnTriangle.Pressed = true;
};

But that doesn't work!
Can anyone help me?

A: You set the android:layout_width="0dp" in LinearLayout ,So you cannot see your image.
I change the value from 0dp to 120dp
<LinearLayout
android:orientation="vertical"
android:layout_width="120dp"
android:layout_weight="50"
android:layout_height="120dp"
android:background="@drawable/TriangleShapeButton"
android:id="@+id/btnTriangle"
android:clickable="true"
android:focusable="true">
<ImageView
    android:src="@drawable/triangle3"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:id="@+id/imageView1"
    android:layout_gravity="center|center_horizontal" />
 </LinearLayout>

I do not know your <ImageView
        android:src="@drawable/triangle3", so I find another picture to replace it, there is running GIF.

update:Do you need following result like following screenshot?

There is code of layout(I changed android:layout_width from  0dp to android:layout_width="wrap_content" mainly)
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"

 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#0e2a56"
 android:weightSum="100">

 <LinearLayout
    android:orientation="vertical"
    android:minWidth="25px"
    android:minHeight="25px"
    android:layout_width="match_parent"
    android:layout_weight="10"
    android:layout_height="wrap_content"
    android:id="@+id/linearLayout2" >
    <TextView
        android:text="Choose your shape:"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/textView1"
        android:textColor="#ffffffff"
        android:textStyle="bold"
        android:textSize="30dp"
        android:gravity="center_vertical" />
</LinearLayout>

<LinearLayout
    android:orientation="horizontal"
    android:minWidth="25px"
    android:minHeight="25px"
    android:layout_width="match_parent"
    android:layout_weight="100"
    android:layout_height="0dp"
    android:id="@+id/linearLayout1" >
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_weight="50"
        android:layout_height="120dp"
        android:background="@drawable/TriangleShapeButton"
        android:id="@+id/btnTriangle"
        android:clickable="true"
        android:focusable="true">
         <ImageView
            android:src="@drawable/ring"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/imageView1"
            android:layout_gravity="center|center_horizontal" />
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_weight="50"
        android:layout_height="120dp"
        android:background="@drawable/TriangleShapeButton"
        android:id="@+id/btnHexagon"
        android:clickable="true"
        android:focusable="true">
         <ImageView
            android:src="@drawable/ring"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/imageView2"
            android:layout_gravity="center|center_horizontal" />

    </LinearLayout>
</LinearLayout>

</LinearLayout>
</LinearLayout>

Update: After setting  in selector there is running GIF

CODE of selector
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected ="false" >
<layer-list>
  <item android:right="5dp" android:top="5dp" android:bottom="5dp"
 android:left="5dp">
    <shape>
      <corners android:radius="2dp"/>
      <solid android:color="#000000"/>
    </shape>
  </item>
  <item android:right="2dp" android:top="2dp" android:bottom="2dp"
   android:left="2dp">
    <shape>
      <gradient android:angle="270" android:endColor="#082e72"
      android:startColor="#104bb2"/>
      <stroke android:width="1dp" android:color="#000000"/>
      <corners android:radius="4dp"/>
      <padding android:bottom="10dp" android:left="10dp"
      android:right="10dp" android:top="10dp"/>
    </shape>
  </item>
 </layer-list>
 </item>
 <item android:state_selected ="true">
 <layer-list>
  <item android:right="5dp" android:top="5dp">
    <shape>
      <corners android:radius="2dp"/>
      <solid android:color="#D6D6D6"/>
    </shape>
  </item>
  <item android:right="2dp" android:top="2dp" android:bottom="2dp"
   android:left="2dp">
    <shape>
      <gradient android:angle="270" android:endColor="#6b9fff"
       android:startColor="#4064a5"/>
      <stroke android:width="3dp" android:color="#FFFFFF"/>
      <corners android:radius="4dp"/>
      <padding android:bottom="10dp" android:left="10dp"
    android:right="10dp" android:top="10dp"/>
    </shape>
  </item>
</layer-list>
</item>
</selector>

when I click the pic, change the state.
  LinearLayout btnTriangle = FindViewById<LinearLayout>
 (Resource.Id.btnTriangle);

        btnTriangle.Click += (sender, e) =>
        {
            btnTriangle.Selected = !btnTriangle.Selected;

        };


text:
Q: Backward elimination for a non-linear multivariate regression I'm trying to determine what would be a good model for my problem. I am not a statistician and use some words colloquially - please excuse my lack of knowledge.
I'll illustrate the problem with the mtcars dataset in R.
BACKGROUND
For linear regression, I can use the function lm to get a model. Without any prior knowledge of the relationship b/w the independant variables and dependant variable (mpg), I can fit a model with all variables and then use backward elimination to remove the number of independant variables in the model:
> all_in <- lm(formula = mpg ~ ., data = mtcars)
> summary(all_in)

Call:
lm(formula = mpg ~ ., data = mtcars)

Residuals:
    Min      1Q  Median      3Q     Max
-3.4506 -1.6044 -0.1196  1.2193  4.6271

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 12.30337   18.71788   0.657   0.5181
cyl         -0.11144    1.04502  -0.107   0.9161
disp         0.01334    0.01786   0.747   0.4635
hp          -0.02148    0.02177  -0.987   0.3350
drat         0.78711    1.63537   0.481   0.6353
wt          -3.71530    1.89441  -1.961   0.0633 .
qsec         0.82104    0.73084   1.123   0.2739
vs           0.31776    2.10451   0.151   0.8814
am           2.52023    2.05665   1.225   0.2340
gear         0.65541    1.49326   0.439   0.6652
carb        -0.19942    0.82875  -0.241   0.8122
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.65 on 21 degrees of freedom
Multiple R-squared:  0.869, Adjusted R-squared:  0.8066
F-statistic: 13.93 on 10 and 21 DF,  p-value: 3.793e-07

As expected, the significance values are too high for all independat variables. To simplify the model, I can use step for backward elimination:
> step(object = all_in, direction = "backward")
Start:  AIC=70.9
mpg ~ cyl + disp + hp + drat + wt + qsec + vs + am + gear + carb

       Df Sum of Sq    RSS    AIC
- cyl   1    0.0799 147.57 68.915
- vs    1    0.1601 147.66 68.932
- carb  1    0.4067 147.90 68.986
- gear  1    1.3531 148.85 69.190
- drat  1    1.6270 149.12 69.249
- disp  1    3.9167 151.41 69.736
- hp    1    6.8399 154.33 70.348
- qsec  1    8.8641 156.36 70.765
<none>              147.49 70.898
- am    1   10.5467 158.04 71.108
- wt    1   27.0144 174.51 74.280

Step:  AIC=68.92
mpg ~ disp + hp + drat + wt + qsec + vs + am + gear + carb

       Df Sum of Sq    RSS    AIC
- vs    1    0.2685 147.84 66.973
- carb  1    0.5201 148.09 67.028
- gear  1    1.8211 149.40 67.308
- drat  1    1.9826 149.56 67.342
- disp  1    3.9009 151.47 67.750
- hp    1    7.3632 154.94 68.473
<none>              147.57 68.915
- qsec  1   10.0933 157.67 69.032
- am    1   11.8359 159.41 69.384
- wt    1   27.0280 174.60 72.297

Step:  AIC=66.97
mpg ~ disp + hp + drat + wt + qsec + am + gear + carb

       Df Sum of Sq    RSS    AIC
- carb  1    0.6855 148.53 65.121
- gear  1    2.1437 149.99 65.434
- drat  1    2.2139 150.06 65.449
- disp  1    3.6467 151.49 65.753
- hp    1    7.1060 154.95 66.475
<none>              147.84 66.973
- am    1   11.5694 159.41 67.384
- qsec  1   15.6830 163.53 68.200
- wt    1   27.3799 175.22 70.410

Step:  AIC=65.12
mpg ~ disp + hp + drat + wt + qsec + am + gear

       Df Sum of Sq    RSS    AIC
- gear  1     1.565 150.09 63.457
- drat  1     1.932 150.46 63.535
<none>              148.53 65.121
- disp  1    10.110 158.64 65.229
- am    1    12.323 160.85 65.672
- hp    1    14.826 163.35 66.166
- qsec  1    26.408 174.94 68.358
- wt    1    69.127 217.66 75.350

Step:  AIC=63.46
mpg ~ disp + hp + drat + wt + qsec + am

       Df Sum of Sq    RSS    AIC
- drat  1     3.345 153.44 62.162
- disp  1     8.545 158.64 63.229
<none>              150.09 63.457
- hp    1    13.285 163.38 64.171
- am    1    20.036 170.13 65.466
- qsec  1    25.574 175.67 66.491
- wt    1    67.572 217.66 73.351

Step:  AIC=62.16
mpg ~ disp + hp + wt + qsec + am

       Df Sum of Sq    RSS    AIC
- disp  1     6.629 160.07 61.515
<none>              153.44 62.162
- hp    1    12.572 166.01 62.682
- qsec  1    26.470 179.91 65.255
- am    1    32.198 185.63 66.258
- wt    1    69.043 222.48 72.051

Step:  AIC=61.52
mpg ~ hp + wt + qsec + am

       Df Sum of Sq    RSS    AIC
- hp    1     9.219 169.29 61.307
<none>              160.07 61.515
- qsec  1    20.225 180.29 63.323
- am    1    25.993 186.06 64.331
- wt    1    78.494 238.56 72.284

Step:  AIC=61.31
mpg ~ wt + qsec + am

       Df Sum of Sq    RSS    AIC
<none>              169.29 61.307
- am    1    26.178 195.46 63.908
- qsec  1   109.034 278.32 75.217
- wt    1   183.347 352.63 82.790

Call:
lm(formula = mpg ~ wt + qsec + am, data = mtcars)

Coefficients:
(Intercept)           wt         qsec           am
      9.618       -3.917        1.226        2.936

The last model (with the lowest AIC value and 3 independant variables instead of the initial 10) indeed looks better than the initial model (all_in):
> summary(lm(formula = mpg ~ wt + qsec + am, data = mtcars))

Call:
lm(formula = mpg ~ wt + qsec + am, data = mtcars)

Residuals:
    Min      1Q  Median      3Q     Max
-3.4811 -1.5555 -0.7257  1.4110  4.6610

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   9.6178     6.9596   1.382 0.177915
wt           -3.9165     0.7112  -5.507 6.95e-06 ***
qsec          1.2259     0.2887   4.247 0.000216 ***
am            2.9358     1.4109   2.081 0.046716 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.459 on 28 degrees of freedom
Multiple R-squared:  0.8497,    Adjusted R-squared:  0.8336
F-statistic: 52.75 on 3 and 28 DF,  p-value: 1.21e-11

QUESTION
My question is how to carry out the same investigation for higher order models when the order is unknown, i.e. if the square or cube of ``wt` gives me a better fit? I could add additional columns in the dataset corresponding to these higher powers but that would be cumbersome and I'm not sure if that would give me the correct result


text:
Q: Putting citation on right side of the equation I have written an equation in LaTeX and I need to cite the author name with date (Einstein 1915) on the right side of my equation, I tried with the margin note command but it gets split in two lines, how do I get it in one line just right-below my equation?

A: Use the \tag command from the mathtools package (useless to load amsmath in that case). If you don't want the parentheses, use \ tag*:
    \documentclass[12pt,a4paper,bothsides]{article}

    \usepackage[utf8]{inputenc}
    \usepackage[T1]{fontenc}
    \usepackage{fourier}
    \usepackage{mathtools}

    \begin{document}

    \begin{gather}
    E = mc^{2}\tag{Einstein 1915}\\
    E = mc^{2}\tag*{Einstein 1915}
    \end{gather}

    \end{document}


text:
Q: Is there a way to capture error message in chrome console Hi I need to grep error message from chrome console such as 404 file not found, not sure what api chrome is calling to throw error, but seems not console.error.
I've tried to override console.error, but it doesn't work.
//this would not work for error thrown by browser.
console.error=function(msg){
    alert(msg);
}

ps. Not limited to using javascript.


text:
Q: Allow hold block to unblock more than one agent type So, I'm currently sending two different agents (each from their own source blocks) to a common queue. In that queue I use agent comparison in order to prioritize one agent over another.
View descriptive Image here:

However, in an upcoming hold-block, I cannot seem to unblock the next unit in the queue which is a different agent-type from the first (even though I have set it to "isBlocked = False" when the previous unit exited seize-delay-release). After that, the agent type that first entered service is the only one that can operate throughout the simulation. The other agent-type is stuck in the queue.
Any ideas on how I can get the other agent-type through the Hold-block?

A: The hold block will work independently of the agent types in the queue ahead of it.
You should not be using isBlocked = false to 'open ' or 'close' the hold.  This code simply returns if the hold block is blocked or not.

You should use block for blocking and unblock for unlbocking

Here is a small working example where

*

*the hold block is set to initially blocked = false

*blocking the hold on the On Enter code of the hold block using self.block()

*unblocking the hold at the last delay using the On Exit code with hold.unblock()
and most importantly it uses two different agent types to proof that it can handle multiple agents types.


text:
Q: Sytles.css is being copied to dist folder as Styles.js when building with NX I am in the early stages of migrating our existing angular applications to a mono-repo using nx as the framework to build.
After migrating my first application I am noticing the styles.scss file located within the styles dir is being copied over as .js rather than .css.
I cannot for the life of me figure out why.
angular.json:
{

      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
      "version": 1,
      "newProjectRoot": "projects",
      "projects": {
        "LSApp": {
          "projectType": "application",
          "schematics": {},
          "root": "apps/LSApp",
          "sourceRoot": "apps/LSApp/src",
          "prefix": "LSApp",
          "architect": {
            "build": {
              "builder": "@angular-devkit/build-angular:browser",
              "options": {
                "outputPath": "dist/apps/LSApp",
                "index": "apps/LSApp/src/index.html",
                "main": "apps/LSApp/src/main.ts",
                "polyfills": "apps/LSApp/src/polyfills.ts",
                "tsConfig": "apps/LSApp/tsconfig.app.json",
                "assets": [
                  "apps/LSApp/src/favicon.ico",
                  "apps/LSApp/src/assets"
                ],
                "styles": [
                  "node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
                  "apps/LSApp/src/styles/material-theme.scss",
                  "apps/LSApp/src/styles/styles.scss",
                  "apps/LSApp/src/styles/index.scss",
                  "node_modules/font-awesome/css/font-awesome.min.css",
                  "node_modules/tachyons/css/tachyons.min.css",
                  "node_modules/vis/dist/vis.min.css",
                  "node_modules/tether-shepherd/dist/css/shepherd-theme-arrows.css",
                  "node_modules/tether-shepherd/dist/css/shepherd-theme-arrows-fix.css",
                  "node_modules/tether-shepherd/dist/css/shepherd-theme-arrows-plain-buttons.css",
                  "node_modules/tether-shepherd/dist/css/shepherd-theme-default.css",
                  "./node_modules/froala-editor/css/froala_editor.pkgd.min.css",
                  "./node_modules/froala-editor/css/froala_style.min.css"
                ],
                "scripts": []
              },
              "configurations": {
                "production": {
                  "fileReplacements": [
                    {
                      "replace": "apps/LSApp/src/environments/environment.ts",
                      "with": "apps/LSApp/src/environments/environment.prod.ts"
                    }
                  ],
                  "optimization": true,
                  "outputHashing": "all",
                  "sourceMap": false,
                  "extractCss": true,
                  "namedChunks": false,
                  "aot": true,
                  "extractLicenses": true,
                  "vendorChunk": false,
                  "buildOptimizer": true,
                  "budgets": [
                    {
                      "type": "initial",
                      "maximumWarning": "10mb",
                      "maximumError": "10mb"
                    }
                  ]
                }
              }
            },
            "serve": {
              "builder": "@angular-devkit/build-angular:dev-server",
              "options": {
                "browserTarget": "LSApp:build",
                "port": 3000
              },
              "configurations": {
                "production": {
                  "browserTarget": "LSApp:build:production"
                }
              }
            },
            "extract-i18n": {
              "builder": "@angular-devkit/build-angular:extract-i18n",
              "options": {
                "browserTarget": "LSApp:build"
              }
            },
            "lint": {
              "builder": "@angular-devkit/build-angular:tslint",
              "options": {
                "tsConfig": [
                  "apps/LSApp/tsconfig.app.json",
                  "apps/LSApp/tsconfig.spec.json"
                ],
                "exclude": [
                  "**/node_modules/**",
                  "!apps/LSApp/**"
                ]
              }
            },
            "test": {
              "builder": "@angular-devkit/build-angular:karma",
              "options": {
                "main": "apps/LSApp/src/test.ts",
                "tsConfig": "apps/LSApp/tsconfig.spec.json",
                "karmaConfig": "apps/LSApp/karma.conf.js",
                "polyfills": "apps/LSApp/src/polyfills.ts",
                "styles": [
                  "src/styles/styles.scss"
                ],
                "scripts": [],
                "assets": [
                  "src/favicon.ico",
                  "src/assets"
                ]
              }
            }
          }
        },
        "LSApp-e2e": {
          "root": "apps/LSApp-e2e/",
          "projectType": "application",
          "architect": {
            "e2e": {
              "builder": "@angular-devkit/build-angular:protractor",
              "options": {
                "protractorConfig": "apps/LSApp-e2e/protractor.conf.js",
                "devServerTarget": "LSApp:serve",
                "port": 3000
              },
              "configurations": {
                "production": {
                  "devServerTarget": "LSApp:serve:production"
                }
              }
            },
            "lint": {
              "builder": "@angular-devkit/build-angular:tslint",
              "options": {
                "tsConfig": "apps/LSApp-e2e/tsconfig.e2e.json",
                "exclude": [
                  "**/node_modules/**"
                ]
              }
            }
          }
        }
      },
      "cli": {
        "warnings": {
          "typescriptMismatch": false,
          "versionMismatch": false
        },
        "defaultCollection": "@nrwl/angular"
      },
      "defaultProject": "LSApp",
      "schematics": {
        "@nrwl/angular:application": {
          "unitTestRunner": "karma",
          "e2eTestRunner": "none"
        },
        "@nrwl/angular:library": {
          "unitTestRunner": "karma"
        },
        "schematics": {
          "@schematics/angular:component": {
            "styleext": "scss"
          }
        },
        "@nrwl/schematics:component": {
          "styleext": "scss"
        }
      }
    }

package.json
{
  "name": "lsapp",
  "version": "1.36.0",
  "scripts": {
    "test": "node --max_old_space_size=8000 ./node_modules/@angular/cli/bin/ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "build:prod": " node --max_old_space_size=8000 ./node_modules/@angular/cli/bin/ng build LSApp --prod",
    "clean:dist": "npm run rimraf -- dist",
    "rimraf": "rimraf",
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "affected:apps": "nx affected:apps",
    "affected:libs": "nx affected:libs",
    "affected:build": "nx affected:build",
    "affected:e2e": "nx affected:e2e",
    "affected:test": "nx affected:test",
    "affected:lint": "nx affected:lint",
    "affected:dep-graph": "nx affected:dep-graph",
    "affected": "nx affected",
    "format": "nx format:write",
    "format:write": "nx format:write",
    "format:check": "nx format:check",
    "update": "ng update @nrwl/workspace",
    "update:check": "ng update",
    "workspace-schematic": "nx workspace-schematic",
    "dep-graph": "nx dep-graph",
    "help": "nx help"
  },
  "private": true,
  "dependencies": {
    "@acl/datepicker": "~2.0.9",
    "@acl/grid": "^2.1.9",
    "@angular/animations": "^8.2.14",
    "@angular/cdk": "^8.0.1",
    "@angular/common": "~8.2.14",
    "@angular/compiler": "~8.2.14",
    "@angular/core": "~8.2.14",
    "@angular/forms": "~8.2.14",
    "@angular/material": "^8.0.1",
    "@angular/platform-browser": "~8.2.14",
    "@angular/platform-browser-dynamic": "~8.2.14",
    "@angular/router": "~8.2.14",
    "@angularclass/hmr": "^1.2.2",
    "@hos/ah-df-schematics": "^1.1.2",
    "@hos/design-factory": "~7.1.0",
    "@hos/hospitality": "^9.8.0",
    "@ng-bootstrap/ng-bootstrap": "~5.2.1",
    "@ng-select/ng-option-highlight": "~0.0.2",
    "@ng-select/ng-select": "~3.0.7",
    "@ngrx/effects": "^8.0.1",
    "@ngrx/router-store": "^8.0.1",
    "@ngrx/store": "^8.0.1",
    "@ngrx/store-devtools": "^8.0.1",
    "@ngx-translate/core": "^11.0.1",
    "@ngx-translate/http-loader": "^4.0.0",
    "@types/vis": "^4.21.17",
    "angular-2-local-storage": "~2.0.0",
    "angular-froala-wysiwyg": "^3.0.4",
    "angular-sortablejs": "^2.7.0",
    "autoprefixer": "^6.7.7",
    "bootstrap": "~4.3.1",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.6.9",
    "font-awesome": "^4.7.0",
    "hammerjs": "^2.0.8",
    "messageformat": "^1.1.1",
    "moment": "~2.24.0",
    "moment-timezone": "^0.5.25",
    "ng2-validation": "^4.2.0",
    "ng5-slider": "~1.2.4",
    "ramda": "^0.24.1",
    "reflect-metadata": "^0.1.13",
    "reselect": "^3.0.1",
    "rxjs": "~6.4.0",
    "sortablejs": "^1.9.0",
    "tachyons": "^4.11.1",
    "tether-shepherd": "^1.8.1",
    "text-mask-addons": "^3.7.2",
    "tslib": "^1.9.0",
    "url-search-params-polyfill": "^6.0.0",
    "vis": "^4.21.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0",
    "@angular/cli": "~8.3.19",
    "@angular/compiler-cli": "~8.2.14",
    "@angular/language-service": "~8.2.14",
    "@nrwl/angular": "^8.2.0",
    "@nrwl/cli": "^8.2.0",
    "@nrwl/workspace": "^8.2.0",
    "@types/google-libphonenumber": "^7.4.17",
    "@types/hammerjs": "^2.0.35",
    "@types/jasmine": "^2.8.16",
    "@types/node": "~8.9.4",
    "@types/selenium-webdriver": "^2.53.43",
    "@types/tapable": "^1.0.2",
    "@types/tether-shepherd": "^1.2.28",
    "@types/uglify-js": "^3.0.3",
    "angular2-template-loader": "^0.6.2",
    "codelyzer": "^5.0.0",
    "dotenv": "6.2.0",
    "find-root": "^1.1.0",
    "gh-pages": "^0.12.0",
    "jasmine": "^2.99.0",
    "jasmine-allure-reporter": "^1.0.2",
    "jasmine-core": "^2.99.1",
    "jasmine-marbles": "^0.3.0",
    "jasmine-spec-reporter": "^4.2.1",
    "jasmine-tfs-reporter": "^1.0.2",
    "jest": "^24.8.0",
    "jest-preset-angular": "^7.1.1",
    "jest-zone-patch": "^0.0.7",
    "jquery": "^3.4.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-coverage": "^1.1.2",
    "karma-coverage-istanbul-reporter": "^2.0.5",
    "karma-jasmine": "^1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-mocha-reporter": "^2.2.5",
    "karma-remap-coverage": "^0.1.5",
    "karma-spec-reporter": "^0.0.32",
    "node-sass": "^4.14.1",
    "optimize-js-plugin": "^0.0.4",
    "parse5": "^3.0.3",
    "prettier": "^1.15.3",
    "protractor": "^5.4.2",
    "request": "^2.86.0",
    "rimraf": "^2.6.3",
    "source-map": "^0.7.3",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "tslint-config-prettier": "^1.17.0",
    "typedoc": "^0.15.0",
    "typescript": "~3.4.3",
    "wallaby-webpack": "^3.9.15"
  }
}

Any help would be greatly appreciated!


text:
Q: How to get a string within an element from with Selenium for Python I am familiar with how to get an element by id, but how would I get "Microsoft Corporation" from this block using Selenium? I am using the Selenium to navigate through the page for other purposes:
    <input type="hidden" id="hdncompanyid" value="175650211"/>
<form action="/Subscriber/Bio/CompanyProfile" method="post" name="formPOST">    <script type="text/javascript">
        var companyName = "LinkedIn Corporation";
        var parentName = "Microsoft Corporation";


text:
Q: Python (3) readline returns empty string regardless of what is in the file I have a Python (3) program that reads some data in from a file, gets the relevant parts and spits it out to various other places. The problem is that file.readline() has started refusing to get any lines from any file. It just returns an empty string as if it was at the end of the file. The files are not the problem, I checked that with a quick script (read file, print line by line). The possible solution (although I don't know why) is I used 2to3 to convert the code to python3, but looking at the diff it printed I don't see any modifications to the file I/O stuff.
Here is the program:
import threading
import time

def runFile(eventFile, channelRefFileName, serialPorts, timeScale, maxPEs):
    timer0 = threading.Timer(.0001, turnOffLED, [0, 0, 0, 1])
    numEvents = getNumEvents(eventFile)
    eventCount = 0
    while 1:
        linein = eventFile.readline()
        #if linein == '' or '\n' or '\r\n' or '\r': break
        #above checks if the end of file has been reached, below is debugging
        if linein == '': print('EOF')
        if linein == '\n': print('linefeed')
        if linein == '\r\n': print('carrige return/ linefeed')
        if linein == '\r' : print('carrige return')
        if linein == 'New Event\n':
            print('New Event', eventCount, ': file is',
            (eventCount/numEvents)*100, '% done.')
            eventCount += 1
            #insert event sleep time here
            continue
         linein = linein.split(' ')
         del(linein[::2])
         linein[2] = linein[2][:-1]
         linein[1] = float(linein[1])
         if linein[1] < 0: linein[1] = linein[1] * (-1)
         channel = channelLookup(linein[0], channelRefFileName)
         #serialPorts[channel[0]].write(str(channel[1],linein[2]))
         if timer0.isAlive:
            #use backup timer
            timer1 = threading.Timer(0.005, turnOffLED, [serialPorts, channel[0], channel[1], 0])
        timer1.start()
    else:
        #use primary timer
        timer0 = threading.Timer(0.005, turnOffLED, [serialPorts, channel[0], channel[1], 0])
        timer0.start()
    print('Sleeping:', linein[1]*timeScale)
    time.sleep(linein[1]*timeScale)

def channelLookup(channel, channelRefFile):
    channelRef = open(channelRefFile, 'r')
    for line in channelRef:
        if channel in line:
            linein = line
            break
    linein = linein.split('-')
    channelRef.close()
    return linein[1:]

def turnOffLED(serialPorts, arduino, pmt, bs):
    if bs: return -1
    #serialPorts[arduino].write(str(pmt,0))

def getNumEvents(eventFile):
    i = 0
    for lines in eventFile:
        if lines == 'New Event\n':
            i += 1
   return i

The above is run by:
import hawc
import datetime

timeScale = 0.001
#timeScale of 0.000001 results in runtime of 0:06:52.858136
#a timeScale of 0.001 is 9:28:34.837992
eventSleep = 0
maxPEs = 1000
serialPorts = [0, 1, 2, 3, 4]
channelRefFileName = 'Data/hawc-arduino_channel_lookup'
st = datetime.datetime.now()
print('Start time is', st)

eventFile = open('Data/events.txt', 'r')
hawc.runFile(eventFile, channelRefFileName, serialPorts, timeScale, maxPEs)

eventFile.close()

et = datetime.datetime.now()
print('End time is', et)
print('File has run for', et-st)
print('--------Done---------')

And here is some sample data that the program might handle (one file might be about 500000 lines):
Channel: 447 Time: 121.263 PEs: 2263.38
Channel: 445 Time: 118.556 PEs: 1176.54
Channel: 448 Time: 120.384 PEs: 1159.59
Channel: 446 Time: 122.798 PEs: 983.949
Channel: 499 Time: 129.983 PEs: 762.07

A: getNumEvents consumes the entire file, so when you go around reading it, its pointer is already at the end. Instead, reset the file pointer with seek, like this:
def runFile(eventFile, channelRefFileName, serialPorts, timeScale, maxPEs):
    timer0 = threading.Timer(.0001, turnOffLED, [0, 0, 0, 1])
    numEvents = getNumEvents(eventFile)
    eventFile.seek(0, 0)
    eventCount = 0
    for linein in eventFile:
        if linein == '': print('EOF')
        ....


text:
Q: How to search and replace string in a file in Perl The content of my input file is shown below:
abc\**def\ghi**\abc\!!!!!
abc\**4nfiug\frgrefd\gtefe\wf4fs**\abc\df3gwddw
abc\**eg4/refw**\abc\f3

I need to replace whatever string in between abc \ --------------\abc in my input file with ABC\CBA.
I have tried something like below to get the strings that need to be replaced. But I get stuck when I need to use the search and replace:
my $string1 = qr/abc\W+([^a]+)/;
my $string2 = map{/$string1/ => " "} @input_file; # The string that needs to be replaced
my $string3 = 'ABC\CBA'  # String in that. I want it to replace to

s/$string2/$string3/g

How can I fix this?

A: A one-liner to fix a file:
perl -plwe 's/abc\\\K.*(?=\\abc)/ABC\\CBA/' input.txt > output.txt

Or as a script:
use strict;
use warnings;

while (<DATA>) {
    s/abc\\\K.*(?=\\abc)/ABC\\CBA/;
    print;
}

__DATA__
abc\**def\ghi**\abc\!!!!!
abc\**4nfiug\frgrefd\gtefe\wf4fs**\abc\df3gwddw
abc\**eg4/refw**\abc\f3

The \K (keep) escape sequence means these characters will not be removed. Similarly, the look-ahead assertion (?= ... ) will keep that part of the match. I assumed you only wanted to change the characters in between.
Instead of \K one can use a look-behind assertion: (?<=abc\\). As a personal preference, I used \K instead.

A: perl -i -pe 's/this/that/g;'  file1

A: If you do not want the substitution to operate on the default variable $_, you have to use the =~ operator:
#!/usr/bin/perl
use warnings;
use strict;

my @input_file = split /\n/, <<'__EOF__';
abc\**def\ghi**\abc\!!!!!
abc\**4nfiug\frgrefd\gtefe\wf4fs**\abc\df3gwddw
abc\**eg4/refw**\abc\f3
__EOF__

my $pattern = qr/abc\\.*\\abc/;       # pattern to be matched
my $string2 = join "\n", @input_file; # the string that need to be replaced
my $string3 = 'ABC\CBA';              # string i that i want it to replace to

$string2 =~ s/$pattern/$string3/g;
print $string2;

A: #!/usr/bin/perl
use strict;
use warnings;

open my $fh,"<", "tryit.txt" or die $!;

while (my $line = <$fh>) {
    $line =~ s/(abc\\)(.*?)(\\abc)/$1ABC\\CBA$3/;
    print $line;
}

gives the following with the input data.
abc\ABC\CBA\abc\!!!!!
abc\ABC\CBA\abc\df3gwddw
abc\ABC\CBA\abc\f3

A: To address your comment about replacing text "inplace" in the file directly, you can use the -i switch for a one-liner. In a script, you can perhaps look at using Tie::File, which allows read-write access to lines of a file as (mutable) elements in an array. To copy Mike/TLP's answer:
#!/usr/bin/perl
use strict;
use warnings;

use Tie::File;

tie my @file, "Tie::File", "tryit.txt" or die $!;

# I think you have to use $_ here (done implicitly)
while (@file) {
    s/(abc\\)(.*?)(\\abc)/$1ABC\\CBA$3/;
    print;
}


text:
Q: Display ListViewItems as Circles What's the best way to display items in a listview as circles?
I want to embed the name of the item within the circle.
Do I use a ItemContainerStyle?
I assume I use a controltemplate. However, I'm confused as I consider its relationship with the ItemContainerStyle.
What's wrong with the following code?
<ListView ItemsSource="{Binding Contacts}"
          CanDragItems="True" DragItemsStarting="OnDragItemStarting">
    <ListViewItem  Style="{StaticResource ContactsListItemStyle}"  />
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <ContentControl Content="{Binding DisplayName}">
                    <ContentControl.Template>
                        <ControlTemplate>
                            <ContentControl>
                                <Grid>
                                    <Ellipse Fill="LightGray" Height="50" Width="50" />
                                    <Viewbox>
                                        <ContentControl Margin="20" Content="{TemplateBinding Content}" />
                                    </Viewbox>
                                </Grid>
                            </ContentControl>
                        </ControlTemplate>
                    </ContentControl.Template>
                </ContentControl>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

A: The following XAML works:
<Page.Resources>
       <ControlTemplate x:Key="ContentControlTemplate" TargetType="ContentControl">
            <ContentControl>
                <Grid>
                    <Ellipse Fill="LightGray" Height="200" Width="200" />
                    <Viewbox>
                        <ContentControl Margin="20" Content="{TemplateBinding Content}" />
                    </Viewbox>
                </Grid>
            </ContentControl>
        </ControlTemplate>
</Page.Resources>

        <ListView ItemsSource="{Binding Contacts}"
                  CanDragItems="True" DragItemsStarting="OnDragItemStarting">
            <ListViewItem  Style="{StaticResource ContactsListItemStyle}"  />
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <ContentControl Template="{StaticResource ContentControlTemplate}"
                                        Content="{Binding DisplayName}" />
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>


text:
Q: I want a shell scripts to delete ALL files in a dir, BUT NOT dir I am doing this
rm -r users/path/DIR/ *

and it deletes DIR.
I want to delete all contents of DIR without deleting DIR.
I also want to execute this shell script while being in root dir.
ANSWERED:   rm -rf   instead of rm -r

A: You have a space between users/path/DIR/ and *. The correct command is :
rm -r users/path/DIR/*

If you also want to delete hidden files run :
rm -r users/path/DIR/* users/path/DIR/.*


text:
Q: Converting Sybase Database to MSSQL Database Error loading database objects Microsoft SQL Server Migration Assistant I have been attempting to use the Microsoft SQL Server Migration Assistant for Sybase version 6.0 to migrate my Sybase databases to SQL Server. However, I have one database that in the UI shows "Error occurred while loading database objects", using the console version of the tool shows "FATALERR One of more objects specified as a command params were not found in metabase: .dbo" (and yes the error says "One of more" not "One or more"). All other databases load fine. I ran this tool using the console in the hopes of seeing a more verbose error, but the error still does not tell me why that database's objects cannot be loaded.
In the following link Microsoft states what sys objects in Sybase I need at least public rights on.
https://msdn.microsoft.com/en-us/library/hh302811(v=sql.110).aspx
The account I'm using is the SA account for the Sybase server so the user account has the appropriate rights. Any suggestions would be greatly appreciated.

A: I opened an incident with Microsoft, their recommendation was to run the SQL Server Migration Assistant (SSMA) from a workstation that did not have Microsoft SQL Server installed on the same machine. This fixed the problem, however there was no mention on the SSMA download site stating that the Migration Assistant needs to run on a separate computer. In addition, the error message could have been more verbose letting me know what the problem was instead of costing me one of my two annually allotted Microsoft incidents.


text:
Q: Dynamic switch case with Methods as Map Value - Java so my little project has a Scanner and two important methods:

*

*That shows the commands i can type in my scanner (runs other methods)

*A switch-case with the commands

And the following code:
static void showCommands(){
    System.out.println("You can enter the following commands: "
            + "\nCommands: Lists your commands. "
            + "\nInventory: Opens up your inventory"
            + "\nEquipment: Let's you equip your items"
            + "\nSpawnItem: Spawns a random item in your inventory"
            + "\nTravel: Travels your character"
            + "\nLocate: Locates your character"
            + "\nClose: Exits the game");

}

static void useCommands() {
    String input = "";
    Scanner sc = new Scanner(System.in);
    while (!input.equals("Close")) {
        input = sc.next();
        switch (input) {
        case "commands":
            showCommands();
            break;
        case "combatlevel":
            CombatLevel.showCombatLevel();
            break;
        case "totatlevel":
            TotalLevel.showTotalLevel();
            break;
        case "inventory":
            Inventory.showInventory();
            break;
        case "equipment":
            Equipment.showEquipment();
            break;
        case "equip":
            break;
        case "spawnitem":
            Item.spawnItem();
            break;
        case "travel":
            Map.travel();
            break;
        case "increaselevel":
            Player.getInstance().combatLevel.increaseCombatLevel();
            break;
        case "locate":
            Map.locate();
            break;
        case "close":
            sc.close();
            System.exit(0);
            break;
        }
    }
}

The problem is: the architecture is too static, since I always need to update both methods accordingly for each new command and itself it just feels not efficient.
So I wanted to ask if it is possible to maybe use a Map with a key, the String of the user input on my scanner, and the start the method dynamically as the value of the map.
Like:
HashMap<String, Method> test = new HashMap<>();
test.put("test", test());
I tried to do that but it didnt work out, since my test() method had to return another method which did not make sense to me.
Does anyone have any suggestions on how to fix that problem?
Cheers

A: Define an interface called Command that will represent the action performed. You can then store the relevant Command in a Map with the alias as the key. Feel free to look into the command pattern, it might have some more useful and conventional design.
interface Command {

    void execute();

}

class MyCommand implements Command {

    @Override
    public void execute() {

    }
}

Map<String, Command> commands = new HashMap<>();

commands.put("command", new MyCommand());

commands.put("helloWorld", () -> System.out.println("Hello World"));

Command command = commands.get("command");

Command helloWorld = commands.get("helloWorld");

command.execute();

helloWorld.execute();


text:
Q: How to handle pagination with JQuery and AJAX? On my site I have the links First, Prev, Next, and Last. These are empty links that are captured and handled by JQuery. However, still being very new to AJAX and JQuery, I'm not sure how to accomplish what I want. I believe I could get this working using post but the only problem is that I want the target page number to go in to the URL in this format:
http://www.mywebsite.com/index.php?page=3
Then on page load I would use the $_GET variable and with the page number I could request the appropriate tables from the database and display them to the user.
Basically what I'm asking is how to make simulate this behavior with JQuery.

A: You can do something like this:
Javascript:
post:
function pagination(page) {
    if (!page)
        var page = 1;

    $.post("index.php", { page: page }, function(data) {
        // data loaded, do something
   });
}

or get
function pagination(page) {
    if (!page)
        var page = 1;

    $.get("index.php?page=" + page, function(data) {
        // data loaded, do something
   });
}

Then, You just  have to call the javascript function:
Prev Next

A: As long as you're requesting this from the same site as the script, you might be able to get away with this.
To load remote content (Google Cross Site Scripting for limitations), jQuery has a simple function to do that:
$('#result').load('ajax/test.html');

This loads test.html into the item with the id of #ajax. Pretty simple.
In order to get the arguments, you can use this script (credit goes to http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html):
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

The usage information is avaliable there too.


text:
Q: How do I modify this page peel effect without messing it up? I am trying to adapt the page peel effect shown here. My fiddle is here
I'm trying to make 2 modifications:

*

*Increase the width to 90% (they have 800px)

*

*If I do this, then this screws up the dropshadow effect, showing some whitespace where the shadows should be

*Put the page peel on all 4 corners.

*

*I've tried all sorts of combinations of the classes: "shadow-bottom shadow-top", "shadow-right shadow-left", among others.

How do I accomplish both?

Bottom shadow, both sides

Freegan fixie banh mi, pickled art party trust fund iphone blog etsy occupy cardigan fap ethnic. Sartorial sriracha vinyl lo-fi cardigan. Tofu fingerstache vegan, shoreditch marfa pour-over occupy 8-bit american apparel four loko fixie lomo vice. Freegan irony chambray jean shorts PBR selvage. PBR messenger bag VHS, umami sustainable godard portland single-origin coffee. Wolf whatever butcher messenger bag yr american apparel fap. Tattooed master cleanse cred, narwhal gluten-free sriracha organic next level put a bird on it.

....full code on my jsfiddle link

A: I created a demo with the intended effects here.
EDIT: catered for variable width bug by fixing the percentage-based width of the original, which gave fixed values for every dimension except pseudo element width, at 40%. 40% of 800px (the container's specified width) = 320px, which is what we'll secify here to resolve the clipped shadows.
The other problem is that the original author wrote the code in such a way that shadows would only be applied to the .page-curl element: I separated out the CSS rules such that .page-curl only govern's the element's internal appearance.
The revised CSS means you can create as many elements as you want with shadow effects, without bringing in properties like padding, border, background, width, etc:
[class*=shadow] {
    position: relative;
}

[class*=shadow]:before,
[class*=shadow]:after {
    background: none;
    bottom: 12px;
    -moz-box-shadow: 0 10px 12px rgba(0, 0, 0, 0.5);
    -webkit-box-shadow: 0 10px 12px rgba(0, 0, 0, 0.5);
    box-shadow: 0 10px 12px rgba(0, 0, 0, 0.5);
    content: "";
    height: 10px;
    left: 12px;
    position: absolute;
    width: 320px;
    z-index: -1;
    -moz-transform: skew(-4deg) rotate(-4deg);
    -webkit-transform: skew(-4deg) rotate(-4deg);
    transform: skew(-4deg) rotate(-4deg);
}

[class*=shadow]:after {
    -moz-transform: skew(4deg) rotate(4deg);
    -webkit-transform: skew(4deg) rotate(4deg);
    transform: skew(4deg) rotate(4deg);
    left: auto;
    right: 12px;
}

Basically, this code says that if an element has a class containing the text shadow, we can give it these ::before and ::after elements. Next, the rules dictating specific directions have got the .page-curl class chucked out.
At this point we're still limited to 2 shadows per element (we can only have one ::before and one ::after element): the solution, then, is to create 2 nested divs:

So the 1st div takes care of the top and bottom shadows on the right, the 2ndtakes care of those on the left.
Incidentally, the 2nd has all the .page-curl properties, and the .container class on the 1st takes care of your 90% width requirement.

A: The peel shadow won't be as tall, but it still looks great! Make the following small changes on both of the following it will fix this for you:
Here is the jsFiddle for it
and here is what it looks like on the page
.shadow-top-bottom.shadow-left:after {
display: block;
bottom: auto;
top: 20px; /* change from top: 15px; to top: 20px;*/
right: auto;
left: 12px;
-moz-box-shadow: 0 -10px 12px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 -10px 12px rgba(0, 0, 0, 0.5);
box-shadow: 0 -10px 12px rgba(0, 0, 0, 0.5);}

.shadow-top-bottom.shadow-right:before {
display: block;
bottom: auto;
top: 20px; /* change from top: 15px; to top: 20px;*/
right: 12px;
left: auto;
-moz-box-shadow: 0 -10px 12px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 0 -10px 12px rgba(0, 0, 0, 0.5);
box-shadow: 0 -10px 12px rgba(0, 0, 0, 0.5);}


text:
Q: Service Stack returns IOException: The filename, directory name, or volume label syntax is incorrect We have created a servicestack API on .NetCore3.1 (https://www.example.com). When there is a called made to the api with https://www.example.com/http://test or https://www.example.com/php://test we get IOException instead of 404 response.
It looks like its looking for that specific folder where we host our api.
Is there any flag in HostConfig that we can use to disabled this validation?
Errors:

*

*https://www.example.com/http://test : IOException: The filename, directory name, or volume label syntax is incorrect. : '{location}\http:'

*https://www.example.com/php://test : IOException: The filename, directory name, or volume label syntax is incorrect. : '{location}\php:'

A: This should be resolved from this commit where ServiceStack will no longer attempt to access the file system for paths containing illegal characters.
This fix is available from v5.12.1+ that's now available on MyGet


text:
Q: Unable to get attribute value from an ActiveRecord model Trying to get a value from a object isn't working out.
  class Asset < ActiveRecord::Base
  attr_accessible :description,
                  :file,
                  :file_cache
  belongs_to :attachable,
             :polymorphic => true
  mount_uploader :file, AssetUploader

In console
  profile = Profile.first

  Profile Load (0.5ms)  SELECT `profiles`.* FROM `profiles` LIMIT 1 etc

profile.assets.inspect
Asset Load (0.6ms)  SELECT `assets`.* FROM `assets` WHERE `assets`.`attachable_id` = 1 AND `assets`.`attachable_type` = 'Profile'
 => "[#<Asset id: 1, description: nil, file: \"fa731ee80a.jpg\", attachable_id: 1, attachable_type: \"Profile\", created_at: \"2012-01-30 00:29:21\", updated_at: \"2012-02-07 22:13:17\">]"

How would I get the file attribute from this?
Tried numerous things but I just seem to be unable to figure it out
profile = Profile.first then profile.assets.first.file works

BUT
profile = Profile.where(:user_id => 2 ) then profile.assets.first.file returns a NoMethodError: undefined method `assets' for #<#

A: Quick answer: profile.assets.first.file
Actual answer: Your profile model should have a has_one :asset, :as => :attachable if each profile will only have one attached file, but it seems that you have a has_many.
Update
Try:
profile = User.find(2).profile
profile.assets

Or:
profile = Profile.where(:user_id => 2).first
profile.assets

A: Seems in _profiles.haml partial rendering @profiles
This seems to work

*

*@profile = User.find(profile.id).profile
= image_tag @profile.assets.first.file_url(:search) rescue nil

Not shure if its very clean though but for now it will do


text:
Q: Reference request for function by which to compute coefficients of continued fraction of algebaic number The simple continued fraction is in the form
$$[1;1,2,3,4,5,\dots]=1+\cfrac{1}{1+\cfrac{1}{2+\cdots}}, $$ for instance. Obviously,the coefficients $x_i$can be computed by computable function $x_i=f(i), i\in \mathbb{N},$ and, $i$ is the $i$th coefficients.
Is there any function by which to compute coefficients of continued fraction of irrational algebraic non-quadritic number like $\sqrt[3]{5}$? Any example is appreciated.

A: It's not very clear to me what the actual question is. If you know how to compute successive decimal approximations to a number like $\sqrt[3]{5}$, then surely you know how to compute its continued fraction approximants based on that (subtract integer part, reciprocate, repeat). One can certainly write down an algorithm which does all that, and that surely qualifies as a "function" that computes the continued fraction expansion, and that would be an answer to the apparent question as stated.
However, this is undoubtedly an inelegant approach, and it is surely of interest to develop algorithms that are more direct than the cumbersome route of first computing decimal expansions and from there continued fractions. This is not a research area of mine, but my casual interest has made me a little bit aware of some work in this area.
For many years, Bill Gosper has been promulgating the virtues of continued fraction representations and has developed methods and computer algorithms for performing exact arithmetic on them. Let me quote him first (interview from More Mathematical People, p. 112):

Khinchin, in his book, talks about how wonderful continued fractions are but says, "Of course, there is no way to do arithmetic with them." When I sort of talked longingly of finding an algorithm to do arithmetic with continued fractions, Schroeppel just turned to me and said, "Good luck." I'm sure he feels a little bit guilty for that. When I showed him the algorithm that I found, his very first reaction was, "Oh, feedback." And then he said, "Oh, it won't work." It took me a while to realize that, in fact, it did work, that you really can write an algorithm [in this case, a Newton's method] and have the thing eat its own output as input and just take the square root of a continued fraction outright without any successive approximation at all. And that's true of anything amenable to Newton's method. It's completely astounding. It looks like you're cheating God somehow, and it really works.

The first part of this quote refers to algorithms Gosper developed for how to add, subtract, multiply, divide two given continued fractions, or more generally how to compute the c.f. of expressions $\frac{axy + bx + cy + d}{exy + fx + gy +h}$ ("bihomographic transformations") directly in terms of the c.f.'s of $x, y$. This is explained in a number of places, e.g. by Gosper in his famous HAKMEM 239, or in somewhat more pleasantly formatted form in a number of places such as Ben Lynn's notes here or a senior thesis here. Marc Dominus also has some nice lecture notes.
For the second part about Newton's method: it seems harder to find well-developed accounts. The idea is briefly touched upon in a generally enthusiastic report here (page 6), but Ben Lynn (in the notes referenced above, in his section on algebraic numbers) seems to believe that a more practical algorithm to compute the c.f. of say $\sqrt[3]{5}$ is to write down the rational approximants of the root of $x^3 - 5$ based on Newton's method, which converge rather rapidly (quadratically), and convert those directly to continued fractions (which converge less rapidly -- linearly in fact).
Anyway, you might wish to explore the lore surrounding Gosper's algorithms.

A: This paper may be worth a look:
E. Bombieri and A. J. van der Poorten. Continued fractions of algebraic numbers. Computational algebra and number theory (Sydney, 1992), pp. 137–152. Kluwer Acad. Publ., 1995.
Also, R.P. Brent, Alfred J. van der Poorten, Herman J.J. te Riele: A comparative study of algorithms for computing continued fractions of algebraic numbers"   Algorithmic Number Theory (Talence, 1996), pages 35-47, Lecture Notes in Computer Science, 1122, Springer, Berlin, 1996.


text:
Q: When photons are moving at the speed of light, how come they change in position? From what i know, photons are moving at the speed of light and that means the time that photons are experiencing is zero, but here is the thing...
If the time is zero how can they travel astronomical distances? From the relation of distance with speed and time
D=C×t
Then, D=(3×10^8)×0=0m
How we can see (not physically) photons moving (or coming) from another galaxy?

A: Remember that length contraction also takes place:
If you were to run along side the photon at close to the speed of light, the distance between the galaxies would be contracted by the Lorentz Factor γ, which 'cancels' with the time dilation.
You could imagine that at the speed of light, the distance between the galaxies becomes zero, but you have do be careful with diving by zeroes.

A: I think the pitfall here is that you talk about "the time" when there is actually more than one time to consider. There's the time experienced by the photon, and a time experienced by anyone moving at sub-$c$ velocity.

This diagram from Wikipedia is a nice illustration. Imagine you have two friends, F1 and F2, that move at velocities $v'$ and $v''$. A photon is whizzing past all of you.That is the yellow line going through the 1st and 3rd quadrants. Now, the representation of the Lorentz transformation between different reference frames is that the axes of the frames that aren't yours seem to close around the photon world line like scissors. How you perceive a moving particle - the photon or your friends - is seen as their projections onto the space and time axes. Your friend F2 at $v''$ will have different projections onto your $ct$ and $x$ axes than onto the axes of your friend F1 moving at $v'$. Their space will seem shorter, and their time slower, to you, and you will measure $v''$ as higher than will F1. All of you will experience $c$ as the same, though.
But - and here comes the crucial point - At the speed of light, the spatial and time axes are the same axis. The scissors have closed completely. The projection onto the space axis along the direction of the time axis is not defined. Both time and distance are zero. That, however is only in ther reference frame of the photon. Meanwhile, in the other (black and blue) reference frames, the world line of the photon still has nice and well defined projections onto your time and space axes, and all is good.

A: The first fact that should be corrected is that photons are not created equal. Which means that they all don't travel at the speed of light. They travel near the speed of light. And we are talking about traveling 99.9 percent of the speed of light.
Some special photons that are still under research actually slow down exponentially over distance.
So why are we able to see?
Well due to the principal of reflection. The mass of material that photons bounce and are absorbed by actually redirects some of the light. This is why when you take a flashlight, turn it on and point it at the ground it will not be as bright as if it were to be the same distance from you and the ground but pointing towards your eyes.
So basically only half of the light that we see most of the time  is actually reflected.

A: Light moves at 3x10^8 m/s not an individual photon.
It is meaningless to talk about the velocity of an individual photon. It is a quantum particle. When it is detected at a distance x from the source, it has probability for travelling along any possible path from the source to the detector.  (See Feynman's QED) The time at which it was emitted by the source is unknown. So neither the distance travelled nor time taken are experimentally determinable.
When the velocity of light is measured it is the average for a large number of photons. Or if you prefer, a light wave


text:
Q: How can I optimize SSL session so I can reuse it later (if needed) to improve Client Server performance I have a server running on Windows Azure here with a large key (link is intended to demonstrate large key in SSL cert).  Based on this Security.SE conversation the larger key will be more expensive to setup and tear down from a CPU perspective.
Assuming I'm using a .NET client and a .NET server; what changes should I make (if any) to reduce the overhead of connecting / disconnecting an SSL perspective.
For the purpose of this conversation let's include these scenarios (add more if you can think of them)

*

*WebBrowser to IIS

*WCF client to WCF Server (IIS)

*WCF client to WCF TCP

*Sockets-based client to Sockets-based server

A: The cost of an initial handshake is basically fixed (given certain parameters).  The cost of a resumed handshake is approximately zero.
The way to improve performance is to increase the amount of sessions that are resumed sessions, and not initial sessions.  This amortizes the cost of the initial handshake across the resumed handshakes, reducing the average handshake cost.
The easiest way to increase the resumed handshake rate is to have a larger session cache size/timeout.  Of course, having a large session cache can create its own performance issues.  One needs to find a good balance between these two, and the best way to do that is with testing.

A: If the application is made to keep the WCF connections open, it may make sense to enable KeepAlive (it's disabled by default).
The TCP connection will be reused automatically when the keep-alive switch is turned on. For the 'ServicePoint Manager, you can use theSetTcpKeepAlive method to turn on the keep-alive option for a TCP connection. Refer to the following MSDN article:
ServicePointManager.SetTcpKeepAlive Method
http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.settcpkeepalive.aspx
From Microsoft:
Generally the difference, in the perspective of performance, between common HTTP and HTTPS lies in the handshake of a TCP connection. It takes longer time for an HTTPS handshake,  than HTTP. However, after the TCP connection is established, their difference is very trivial as a block cipher will be used in this connection. And the difference between a 'very high bit' cert and a common cert is more trivial. We've dealt with a lot of slow performance cases, but we seldom haves cases whose slow-performance problem is caused by more stronger cert, as the network congestion, the CPU high utilization, a large portion of ViewState data etc. are main characters of slow performance.
In the perspective of IIS, notice that in the IIS manager, there will be an option checked by default for a website, as 'Enable HTTP Keep-Alives'. This option ensures that the IIS and the client browser would keep the TCP connection alive for a time for certain HTTP requests. That is to say, for round-trips between an IIS server and the client, only the first request will be obviously slower than others, while the rest won't.

You can refer to following article about this setting:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d7e13ea5-4350-497e-ba34-b25c0e9efd68.mspx?mfr=true
Of course, I know for WCF, IIS is not a must to host applications for many scenarios, but on this point, I think they work similarly.


text:
Q: Leaflet issue: making layergroup of polylines not clickable i got an issue with making polylines in my layergroup not clickable...
as you can see in the code below i use the built in function of leaflet to go through the layergroup (route.eachLayer), and try to add the style 'clickable: false' but this doesn't seem to do anything...
//route = layergroup with all polylines
function disableclicking(){
    route.eachLayer(function(layer){
        layer.setStyle({clickable: false});
    });
}

when i try to use this code, it seems to change nothing (it does go in the loop though)
or at least, it doesn't change what i want...
what i want is that the polyline's class '.leaflet-clickable' is removed... and this doesn't seem to happen. Doesn't this class change when you change the style to not clickable or is there something wrong with my loop?

A: I had similar need and since the accepted answer has nothing to do with the question, I'll post the solution I came up with (in case somebody else arrives here from google).
function setClickable(target, value) {
    if(value && !target.options.clickable) {
        target.options.clickable = true;
        L.Path.prototype._initEvents.call(target);
        target._path.removeAttribute('pointer-events');
    } else if(!value && target.options.clickable) {
        target.options.clickable = false;

        // undoing actions done in L.Path.prototype._initEvents
        L.DomUtil.removeClass(target._path, 'leaflet-clickable');
        L.DomEvent.off(target._container, 'click', target._onMouseClick);
        ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'mousemove', 'contextmenu'].forEach(function(evt) {
            L.DomEvent.off(target._container, evt, target._fireMouseEvent);
        });

        target._path.setAttribute('pointer-events', target.options.pointerEvents || 'none');
    }
}

setClickable(myLayer, false);


text:
Q: Error while moving uploaded file to server and link address with PHP database I have create a PHP file which is run using AJAX for uploading user's file to the server and update it's link to the database table.
While running the file, I found that my PHP links file address with the database table successfully but the file is not moved in the destination folder that is 'uploads' folder. Unfortunately I'm unable to find the error. Could you help me in finding the error! MY PHP code is -
    <?php
session_start();
//error_reporting(0);
    $error = 0;
if($_FILES["image"]["name"] !='')
{
    $lastid = $_SESSION['lastid'];
    $img_name = $_FILES["image"]["name"];
    $tempname = $_FILES["image"]["tmp_name"];
    $img_size = $_FILES["image"]["size"];

    $img_ext = explode('.',$img_name);
    $ext_check = strtolower(end($img_ext));
    $ext_allwd = array('png','jpg','jpeg');
    $new_name = $lastid ."newname".".".$ext_check;
    $area = "uploads/".$new_name;

    if($ext_check !='jpg' || $ext_check!='jpeg' || $ext_check!='png'){
        $error = 1;
        echo "Only JPG, PNG or JPEG files are allowed.";
    }

    if($img_size > 512000 || $img_size < 51200){
        echo "File size must be 50kb to 500kb";
        $error = 1;
    }
    else{
        $error = 0;
    }

    if($error==0){

        // Create Connection
        include 'connect.php';
        $conn = mysqli_connect ($host, $dbusername, $dbpassword, $dbname);
        $sql = "UPDATE `admndata` SET `imagename` = '$area' WHERE id = '$lastid'";

        //link with Database
        if (mysqli_query($conn, $sql)) {

        //move uploaded file
        move_uploaded_file($tempname,$area);

        // close connection after finishing the job
        mysqli_close($conn);
        }
        else {
        echo "Error updating record: " . mysqli_error($conn);

        // close connection after an error!
        mysqli_close($conn);
        }
    }
}
?>

Edit : Code edited after accepting suggestions via comments.

A: Hey kindly check this coding this coding is working correctly it will upload image and save it to "uploads/uploaddc/" in my programing and its working absolutly correct. it will check if the same named image is in the "uploads/uploaddc/" folder then it will tell the user that this image is being in the folder and if the image name is different then it will upload it to folder without any error. I have shared it with you so that you can check you coding and find the missing query for you function
 <?php
    if (isset($_POST['uploaddc'])) {
//adjust as per your folder
        $target_dir = "uploads/uploaddc/";

//check this line with your coding and adjust as per you requirement
        $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);

//check this line with your coding and adjust as per you requirement
        $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

        $jobid = $_POST['jobid'];

        if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {

        } else {
            echo "Sorry, there was an error uploading your file.";}

        $checkifsame = "SELECT * FROM images WHERE jobid = '$jobid'";
        $ruencheckquery = mysqli_query($cons, $checkifsame);
        while ($row_category = mysqli_fetch_array($ruencheckquery)) {
            $imagename = $row_category['dcfile_name'];
            global $imagename;

        }

    // this function will tell if the same image is in the database

        if($imagename == $target_file){
            echo "Same Image in database . this image cannot be uploaded try other images";
        }else{
    // adjust as per your database
        $insert_product = "INSERT INTO images(jobid, dcfile_name)  VALUES ('$jobid','$target_file')";
        $run_query = mysqli_query($cons, $insert_product);
    }

    }
    ?>

in the end specially check you <form action="" method="POST" enctype="multipart/form-data"> because recently i had add put . or other wrong word which send query to database but didn't move the picture to the specific folder. so kindly also check in this section as well.
I will be very happy if it work other wise i will try to help you further


text:
Q: Курсор внутри тегов Sublime Text 3 Раньше после создания любого тега в ST3 например div+TAB курсор становился в центре

|

и если после этого нажимаешь ENTER то он становился вот так:

  |(тут курсор)

после обновления ST3, нажимая на ENTER закрывающий див просто переносится на новую строку вот так:

|

Как сделать, что бы было как раньше?
Установлены плагины Emmet и Tag

A: Preferences -> Key Bindings-User
{ "keys": ["enter"], "command": "auto_indent_tag", "context":
[
    { "key": "setting.auto_indent", "operator": "equal", "operand": true },
    { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
    { "key": "selector", "operator": "equal", "operand": "punctuation.definition.tag.begin", "match_all": true },
    { "key": "preceding_text", "operator": "regex_contains", "operand": ">$", "match_all": true },
    { "key": "following_text", "operator": "regex_contains", "operand": "^</", "match_all": true },
]
}


text:
Q: Why Media Creation Tools keep "redownloading windows" after failed upgrade? I use media creation tools to upgrade windows.
Upgrade fails for so many reasons. VMware installed and must be uninstalled. Sometimes unknown reasons.
I just try again. Every time I want to try again, it will "download" windows again.
Why should it be? It can't be checked that it has downloaded windows from before and the file is there?
Actually, where does the windows get downloaded anyway by media creation tools?
My SSD space in drive C is limited and I definitely want to save 8 GB of hard disk from that extra copy of windows.

A: You need minimum 16GB - 32GB of space to install Windows. Create a bootable USB instead of upgrading it directly


text:
Q: SharePoint 2016 with FBA credential prompts when opening Office documents Can someone, please, share their experience in solving the problem with Office applications prompting for credentials?
We've got FBA and Windows authentication in the default zone. Everything works fine. FBA works perfectly, Windows authentication works. However, when we are trying to open a Word document - we are presented with a login login page. For the sake of the argument, let's say it's OOB Login page. But we also have a custom login page that behaves exactly the same.
When clicking on any Word document (docx), we are prompted with the login page (see screenshot below). That is only half of the problem. The biggest problem is that even if we authenticate one more time, the login page pops up over and over. It does not matter if we login with FBA or Windows. We've tried all sorts of combinations. It just keeps prompting forever.
We can live with Word prompting us from time to time, but after entering credentials we are not logged in. Popup window never disappears. I want to reiterate that this is happening with the OOB login page as well.
More info

*

*If we download the Word document - it opens fine.

*We are accessing the SharePoint 2016 website via the Internet from the computers that are not joined to the SharePoint domain.

*We don't have ADFS or ISA

*The main SharePoint Zone has both Windows and FBA authentication

*We are using SharePoint FBA Pack from Codeplex

*We've got custom login page. But using OOB login page behaves the same way. We still get prompted over and over again when opening Word documents

Things I've tried

*

*Connected to the site using FBA and AD credentials

*Added site to the Local intranet and selected "Automatic log-on with current username and password"

*Tried multiple client computers

*Tried setting "Open in browser" and "Open in Client application"

*Clicked "Remember credentials"

*Enabled and disabled "Client integration"

*Disabled or enabled anonymous access

*Tried adding registry key AuthForwardServerList to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WebClient\Parameters

*Tried using custom or OOB login page

*Tried all browsers. They all behave same except for Firefox. It just openes the file in Word, but it's not connected to the website.

*Disabled or enabled "Site Lockdown"

*Tried adding  < verbs applyToWebDAV="false" >  < add verb="OPTIONS" allowed="false" />   <add verb="PROPFIND" allowed="false" />   </verbs> to web.config

*Restarted client computers

Any help will be greatly appreciated.

A: Looks like you are working with Office 2016. It has Modern Authentication enabled by default. There is a Registry-Key EnableADAL - try to disable it on your client. But be aware, this will break lots of cool stuff with Office365.
This is one of the many reasons why i do not like FBA: It's cheap, but has tons of drawbacks. Office-Integration is one of them. Implement WebApplicationProxy or even better AzureAD Application Proxy instead of FBA. It will save most or all of your external-sharing pains.

A: Here is the real solution that worked for me on two SharePoint 2016 farms with FBA.
Turns out that SecurityTokenService has SuppressModernAuthForOfficeClients property set to $false by default.
If we set it to $true and restart IIS - the miracle happens and Office accepts my credentials from now on.
$sts = Get-SPSecurityTokenServiceConfig
$sts.SuppressModernAuthForOfficeClients = $True
$sts.update()
iisreset

So I guess, this must be a crucial step when setting up FBA for SharePoint 2016. Without it - we just cannot work with office documents


text:
Q: looping audio file using timed script I want to play an audio file then after the audio file is finished playing wait 30mins and have it play the audio file again.  I would like to do this several times.
I know I could just make one large audio file but the file would be very large and I need to email to other people it's easier to make the audio file and use some type of script to do this.
Example Loop:
play audio file to the end then wait 30mins,
play audio file to the end then wait 30mins,
play audio file to the end then wait 30mins,
etc..

PS: The audio file could be any length.
I know about crontab
crontab -e
*/30 * * * * /path/to/your/command

But this doesn't wait for the audio file to finish playing or give me the ability to say how many times it should run.
I'm using ubuntu 14.04

A: It's pretty simple, or I'm missing something.  What you need is something like:
NTIMES=5

count=0
while [ $count -lt $NTIMES ]
do
  mplayer the_sound_file
  sleep 1800                         # 1800 seconds == 30 min
  count=`expr $count + 1`
done

I have used older syntax so that this will run on any bourne-like shell (not just bash).


text:
Q: Sync all Documents directory into iCloud Is there a way to make my Documents directory synchronized with iCloud?
I have setup all permissions and entitlements, but have no idea what to do next.
Could you please provide a swift code snippet or point into a direction I should look to?

A: You can use iCloud's CloudKit services for this.
Have a look at the Quick Start Guide for iCloud's Cloudkit here.

A: When I needed to keep NSUserDefaults in sync via iCloud in simple apps, I used: MKiCloudSync by Mugunth Kumar. While still Objective-C, it's pretty straightforward to use.
If you need iCloud Documents sync, you might check out iRareMedia/iCloudDocumentSync. Of course, this is a bit more work, but still easier than implementing all the methods by yourself.
Have a nice day,
@cdf1982

A: You can use iCloudDrive of iOS 8 to store documents in iCloud Drive..
Refer below links for iCloud set up for your app.
https://unionassets.com/iosnative/icloud-setup-25
http://www.raywenderlich.com/83116/beginning-cloudkit-tutorial
Refer below for saving document to iCloudDrive.
Save iOS 8 Documents to iCloud Drive
Refer below to view the documents which you have saved in iCloudDrive
https://github.com/iRareMedia/iCloudDocumentSync
Hope all the above links are useful to get the task done..!

A: The following 3 steps should get you going:
Step 1: Preparing the app to use iCloud Storage
Step 2: Learing to manage your files using the UIDocument Class
Step 3: Using iCloud Storage in your app
Cheers,
Istvan


text:
Q: Model not detected by Django, even with `app_label` referencing to an existing app I have a Django project with an application called application.
The app is installed in the INSTALLED_APPS as follows:
### application/settings.py

INSTALLED_APPS = [
    ...

    'application.apps.MyAppConfig',
]

with the AppConfig:
### application/apps.py

class MyAppConfig(AppConfig):
    name = 'application'
    verbose_name = 'My App'
    label = 'application'

    path = f"{os.environ.get('APP_DIR')}/application"
    default = True

I have the models defined like this:
### data/models/basemodel.py

from django.db import models

class MyBaseModel(models.Model):

   # ...  fields ...

   Meta:
      app_label: `application`

Project's tree:
main_dir/
  data/
    __init__.py
    models/
       __init__.py
       basemodel.py
  application/
    __init__.py
    apps.py
    urls.py
    settings.py
    ...

Django is not finding the models, and if I run makemigrations Django responds No changes detected, and on migrate, the app application does not appear on the Operations to perform.
I want to split the data layer from the logic and interface layers. In order to do so, I've the models and other data-related business inside data (outside any installed app)
The goal is to link the models to the app from there, without having to declare any model inside the application dir.
The Model should be detected so the Django detects migrations to apply.

Context:

*

*Django Application reference: doc

*Django Models reference: doc

A: I guess you want to have a single module per model ? If so, you need to import your models inside models\__init__ like so:
from .basemodel import BaseModel

I also suggest that you define __all__ inside your init file, in order to import your models easily in other parts of the app:
__all__ = ["BaseModel"]

from .basemodel import BaseModel


text:
Q: How to add a search bar to a react app that filter data from an api? I am working on a project however i need to add an input where a user can filter the list of students
by their name (both first and last name), I have gotten the data from the api the issue is figuring out how to filter the data as I am fairly new to react. Some help would be appreciated. Below is what I have so far.
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import StudentData from './student_data/StudentData'
import './App.css';

function App() {
  const [students, setStudents] = useState(null);
  const studentdata = 'https://www.hatchways.io/api/assessment/students';

  function getStudents(){
    fetch(studentdata)
      .then(resp => resp.json())
      .then(data => {
        setStudents(data);
      })
  }

  return (

Students

        <button className="fetch-button" onClick={getStudents}>
          Get Students
        </button>

          <input type="text" ></input>

      {students && students.students.map((student, index) => {
       var total = 0;
       for(var i = 0; i < student.grades.length; i++) {
        var grade = parseInt(student.grades[i]);
        total += grade;
       }
       const avg = total / student.grades.length;
       const average = avg.toString();

      return(

{student.firstName} {student.lastName}

EMAIL: {student.email}

COMPANY: {student.company}

SKILL: {student.skill}

AVERAGE:: {average}%

      )}
      )}

  );
}

export default App;

A: Modified the code little bit and check this helps with the filter.
import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [students, setStudents] = useState(null);
  const [filterData, setFilterData ] = useState(null);

  const studentdata = 'https://www.hatchways.io/api/assessment/students';

  function getStudents(){
    fetch(studentdata)
      .then(resp => resp.json())
      .then(data => {
        setFilterData(data.students);
        setStudents(data.students);
      })
  }

  const searchByName = (event) => {
    event.persist();
    // Get the search term
    const searchItem = event.target.value.trim();
    // If search term is empty fill with full students data
    if(!searchItem.trim()) {
      setFilterData(students);
    }
    // Search the name and if it found retun the same array
    const serachIn = (firstName, lastName) => {
      if(firstName.indexOf(searchItem) !== -1 || lastName.indexOf(searchItem) !== -1) {
        return true;
      }
      let fullName = firstName+" "+lastName;
      if(fullName.indexOf(searchItem) !== -1) {
        return true;
      }
      return false;
    };
    // Filter the array
    const filteredData = students.filter((item) => {
      return serachIn(item.firstName, item.lastName);
    });
    // Set the state with filtered data
    setFilterData(filteredData);
  }

   return (

Students

        <button className="fetch-button" onClick={getStudents}>
          Get Students
        </button>

          <input type="text" name="serachByName" onChange={(e) => searchByName(e)} ></input>

      {filterData && filterData.map((student, index) => {
       var total = 0;
       for(var i = 0; i < student.grades.length; i++) {
        var grade = parseInt(student.grades[i]);
        total += grade;
       }
       const avg = total / student.grades.length;
       const average = avg.toString();

      return(

{student.firstName} {student.lastName}

EMAIL: {student.email}

COMPANY: {student.company}

SKILL: {student.skill}

AVERAGE:: {average}%

      )}
      )}

  );
}


text:
Q: How many ways are there to express a natural as a sum of 3 others—but by induction? I have figured out an (inductive?) process, but I cannot express it formally:
There is always one possibility where $n$ is in the first place of our 3-tuple: $[n~~0~~0]$. Then I can subtract $k~(\leq n)$ from $n$, and distribute it between the two other spots. For that I have $k+1$ options (from $[k~~0]$ to $[0~~k]$).
Since $k$ can range from $0$ to $n$, I have $\sum_{k=1}^{n+1}k$ possibilities.

Exempli gratia:
For $1$ there are $
\begin{bmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{bmatrix}
$ 3 possibilities. The two "parts" are $[1~|~0~~0]$ and $\left[
\begin{array}{c|cc}
0 & 1 & 0 \\
0 & 0 & 1
\end{array}
\right]$.

The problem is, that if I use the above formula for induction, I would simply be proving Gauss' formula. It just doesn't feel like correct induction.

A: Well, the number of ways to write $m$ as $a+b$ are clearly $m+1$, ranging from $0+(m)$ to $(m)+0$.
So the number of ways to write $n$ as $a+b+c$ are given by:
$$ \sum_{c=0}^{n}(n-c+1)=\sum_{d=0}^{n}(d+1)=\sum_{k=1}^{n+1}k $$
by setting $d=n-c$ and $k=d+1$.


text:
Q: Difference between a device subscribing to an SNS topic, and a lambda function subscribing to a topic? Im currently trying to design a scalable push notification service, which can send notifications to 5-10 mil users in a very short time. I came across two AWS related architectures which got me confused.
Use case: Send a notification to all the users.
1) Each device subscribes to an SNS topic, and if we want to send a push to all users, we just publish to the topics endpoint. And SNS handles the rest(sending to the million users)
2) Lambda functions are subscribed to SNS topics. We send a message to an SNS topic containing all the device tokens/batches, and then lambda calls APN/Firebase endpoints.
I fail to see in what case the second architecture would be beneficial compared to the first?

A: Mobile push notification :
    sns endpoint will created based on user device token and you will get device token from Adm,Fcm,etc like push notification platform sdk and you can trigger push notification to perticular user based sns endpoint because each device have different endpoint and it created user device token and you will have track user device token and endpoint and userId and you can able to see aws sns mobile push notification console
  1) you can create manually also
  2) you can create endpoint using programmatically

you can refer below sdks to create via code https://docs.aws.amazon.com/sns/latest/dg/mobile-push-api.html
Lamda push notification
You can create sns topic in sns console and you can subscribe which lambda you want deliver notification
   basically if you want connect one lamda to another lamda you can use those case
example 1:
  you have micro service for sending otp to user and micro service deployed in different lambda and application recives sending otp request your application main lamda and now you need call otpservice lamda so you can create one sns topic and under subscription you can subscripe otp micro service lamda so main lamda will trigger otp service sns endpoint it will deliver notification micro service lamda