text:
Q: Find the correlation between $D_i$ and $D_j$ Consider a graph having n = 8 vertices labeled $1,2,...,8$. Suppose that each edge is independently present with probability $p$. The degree of vertex $i$, designated as $D_i$, is the number of edges that have vertex $i$ as one of its vertices. Find $Corr(D_i,D_j)$, the correlation between $D_i$ and $D_j$.
My Attempt
The formula for correlation is
$$Corr(X,Y)=\frac{Cov(X,Y)}{\sqrt{Var(X)Var(Y)}}=\frac{\mathbb{E}[XY]-\mathbb{E}[X]\mathbb{E}[Y]}{\sqrt{Var(X)Var(Y)}}$$
I'm not sure what kind of distribution to model $D_i$ and $D_j$ as. Should we split $D_i$ up into indicator variables? Where
$$I=\begin{cases}1&\text{if edge $(i,j)$ is present}\\0&\text{otherwise}\end{cases}$$
Then make the $D=\sum^{8}_{i=1} I_i$.
This makes the most sense to me, but I'm not sure how to proceed or if this is even the right approach.

A: $$\begin{split}\rho(D_i, D_j)&=\frac{Cov(D_i,D_j)}{\sqrt{Var(D_i)Var(D_j)}}\\
&=\frac{Var(I_{ij})}{\sqrt{Var(D_i)Var(D_j)}}\\
&=\frac{p(1-p)}{\sqrt{7p(1-p)\cdot 7p(1-p)}}\\
&=\frac17\end{split}$$
The second equality comes from the fact that the covariance between edges is 0 unless the edge is the same. The third: $I_{ij}$ is bernoulli with parameter $p$, and $D_i$ and $D_j$ are binomial with parameters $7$ and $p$.

A: Here's a sketch; if I have time, I'll complete this later.
I denote $I = I_{ij}$.
Let $E_{ij}$ be the edge from vertex $i$ to $j$. We know that $\mathbb{P}(E_{ij}\text{ is present}) = \mathbb{P}(I_{ij} = 1) = p$. In fact, we know that there are $7 + 6 + \cdots + 1 = 28$ possible edges, so that
$$\mathbb{P}(E_{ij}\text{ is present}) = \mathbb{P}(I_{ij} = 1) = p = \dfrac{1}{28}\text{.}$$
The degree of vertex $i$ is thus given by
$$D_i = \sum_{k \neq i}I_{ik}$$
where for each $i$, there are $7$ terms in the summation. Hence
$$\text{Cov}(D_i, D_j) = \text{Cov}\left(\sum_{k \neq i}I_{ik}, \sum_{\ell \neq j}I_{j\ell} \right) = \sum_{k \neq i}\sum_{\ell \neq j}\text{Cov}(I_{ik}, I_{j\ell})$$
For computing the covariance, $\mathbb{E}[I_{ik}]$ and $\mathbb{E}[I_{j\ell}]$ are easy to compute. For $\mathbb{E}[I_{ik}I_{j\ell}]$, note that $I_{ik}I_{j\ell} = 1$ if and only if $I_{ik} = 1$ and $I_{j\ell} = 1$, then use independence to calculate it. We don't care about the other cases, since otherwise, $I_{ik}I_{j\ell} = 0$ and they do not add to $\mathbb{E}[I_{ik}I_{j\ell}]$.


text:
Q: Using the Requests for PHP library, how can I set a custom user-agent? I'm doing some testing of Requests for PHP and I'd like to set a custom user-agent for a basic GET request.
Peeking at the source code, I thought perhaps this test would pass:
$url = 'http://httpbin.org/user-agent';
$user_agent = 'my-test-agent';

$options = array('useragent', $user_agent);
$response = Requests::get($url, array(), $options);
$json = json_decode($response->body, true);

$this->assertEqual($json['user-agent'], $user_agent);

However, http://httpbin.org/user-agent returns the default library value php-requests/1.6 as the user-agent.
Is it possible to do this or do I need to use the Requests_Session object as demonstrated here?

A: You have to define the options this way:
$options = array('useragent' => $user_agent);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linq Insert with string variable column name I want to pass a column name and value to a function that will update a table using LINQ.
I have the code below but don't know how to implement the string variable column name
private static void update(string key, string value)
    {
        AccessToken accessToken = new AccessToken();

        accessToken.<key variable should go here> = value;

        QBAccessTokensDataContext db = new QBAccessTokensDataContext();
        db.AccessTokens.InsertOnSubmit(accessToken);
        db.SubmitChanges();

    }

A: Add one more property to your class AccessToken with Key name and store the value


text:
Q: Extracting text in two dimensional array from a file in linux I've a text file in linux with following text
;ip address    hostname     put-location      alt-put-location                tftpserver
192.168.1.1    r01-lab1-net /mnt/nas1/fgbu/   /opt/fgbu/devicebackup          192.168.1.254
192.168.1.2    r01-lab2-net /mnt/nas2/fgbu/   /opt/fgbu/backup                192.168.1.222
...
...

Now I want to extract each value in an array for later use. for example if i run following command
echo arry[2][2]

it should give output like following:
r01-lab2-net

one way is to use for loop but i fail to understand how will i move to next line. also please let me know if there is any better way using awk. or any other way to get these values in bash.

A: bash doesn't support 2 dimensional arrays, but you can use other bash utilities.
For ex. awk has support for 2 dimensional array. Read more about it here: http://porthos.ist.utl.pt/docs/gawk/gawk_9.html#SEC128


text:
Q: Failure sending mail - c# - godaddy I'm trying to send email using the following code. It is hosted in godaddy.
MailMessage mail = new MailMessage("from@gmail.com", "to@gmail.com");
MailMessage mail = new MailMessage("from@gmail.com", "to@gmail.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.Subject = "Test email";
string body;
using (var sr = new StreamReader(HttpContext.Current.Server.MapPath("~/App_Data/Template/") + "Email.html"))
{
    body = sr.ReadToEnd();
}
string messageBody = string.Format(body, name, expDate);
mail.Body = messageBody;
Attachment doc = new Attachment(HttpContext.Current.Server.MapPath("~/App_Data/class_3b.pdf"));
mail.Attachments.Add(doc);
client.Send(mail);

But I'm getting error:

{System.Net.Sockets.SocketException (0x80004005): 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 74.125.130.109: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, Exception&
  exception)}

A: You need to authenticate. See Send Email via C# through Google Apps account for example. Google even check that the authentication address and the "from" address corresponds...

A: To send mail using System.Net.Mail, you need to configure your SMTP service in your application's web.config file using these values for mailSettings:
<system.net>
    <mailSettings>
      <smtp from="your email address">
        <network host="relay-hosting.secureserver.net" port="25" userName="your email address" password="******" defaultCredentials="true"/>
      </smtp>
    </mailSettings>
  </system.net>

Code Behind:
MailMessage message = new MailMessage();
message.From = new MailAddress("your email address");

message.To.Add(new MailAddress("your recipient"));

message.Subject = "your subject";
message.Body = "content of your email";

SmtpClient client = new SmtpClient();
client.Send(message);


text:
Q: What are type projections useful for? What are type projections in Scala useful for? Why does Scala's type system support both type projections and path dependent types? What was the rationale behind this design decision?

A: One thing type projections can be used for is partial type application:
({type λ[x]=Tuple2[Int,x]})#λ

A: Not a complete answer, but here are some uses for type projections that I have encountered:

*

*Type level metaprogramming. For examples, see Michid's series (parts I, II, III), Jesper's implementation of HList, and the series at Apocalisp.

*A workaround to enable type inference (for examples, here are some previous SO questions 1, 2, 3).

*A way to bundle a bunch of types into a single type parameter. For example, in a matrix library I'm developing, I define trait Scalar { type A; type B; type C; ... } and then pass it as a single parameter to my matrix trait, trait Matrix[S <: Scalar] ... The individual types can be referred to as S#A, S#B, and so on. Between two matrices of type Matrix[S], for the same S, these types will be compatible (unlike what would be the case with path dependent types).


text:
Q: executing javascript code thought chrome dev tools protocol I'm trying to execute some javascript code through CDTP and PyChromeDevTools library.
The following code works:
from terminal:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222

import PyChromeDevTools
chrome.Network.enable()
chrome.Page.enable()

script="t='hi,';c='this code works on the same line';console.log(t,c)"
chrome.Runtime.evaluate(expression=script)

I have some trouble when I need to inject complex js code not on the same line, for example function with javascript requests ecc..
script="t='hi,';
c='this code works not on the same line don't work ';
console.log(t,c)"
chrome.Runtime.evaluate(expression=script)

is it possible equal javascript file to runtime evaluate ? like this:
chrome.Runtime.evaluate(expression=file.js)

documentation of CDTP
https://chromedevtools.github.io/devtools-protocol/

A: You should just load a js code from a file into str variable
def load_text(filename, mode='r', encoding='utf-8'):
    with open(filename, mode, encoding=encoding) as f:
        txt = f.read()
return txt

file_js = load_text('file.js')
chrome.Runtime.evaluate(expression=file_js)


text:
Q: creating a new column datatype in rails I might have not been searching for the right words in order to get an answer, so you were my last chance.
I am looking to create a new datatype in rails, for example:
t.israeli_id
which gets to pass a customized validation method, and adds errors according to it.
I will be using this datatype in several tables, so making it a string, and passing the validation function in each model.rb would be so much not DRY.
I am using Postgresql, just in case that would matter.

A: Nope, you are approaching this in a wrong way. Database knows nothing about your application logic and it can only do basic validation (not null, etc.).
All of your application-specific validation, error messages and other stuff - it goes into your model. If you need that in several models and don't want duplicating the code, then create a model concern, HasIsraeliId or something. That's what concerns are for.
# app/models/concerns/has_israeli_id.rb
module HasIsraeliId
  extend ActiveSupport::Concern

  included do
    validate :some_field, whatever_condition: true
  end
end

# app/models/user.rb
class User < ApplicationRecord
  include HasIsraeliId
end


text:
Q: PyroCMS custom libraries and CI SuperObject It should be simple, but it's not.
I have a library that is hoping to use other libraries, but something ain't jiving.
Both libs live in system/cms/libraries because as far as I can tell, addons/shared_addons/libraries is utterly useless and the libraries need to be autoloaded (it seems that system/cms is essentially system/application but please correct me if wrong). An aside: just for kicks I put a library in shared_addons/libaries just to see if I could call if from a module; I couldn't. Why is it there?
Lib1
-needs db
-needs lib2
Lib2
-needs session
Here's what happens. Controller [module] loads; calls lib1 which calls lib2 which throws an error. Lib1 is to be called by all module controllers. Lib2 uses session data that is set earlier on and is only called by lib1.
In lib2 I use $CI=get_instance() to supposedly enable CI libs (e.g. database, session). However, I can't get past "Fatal error: Call to a member function userdata() on a non-object"; which is called by
//system/cms/libraries/lib2.php
$this->CI =& get_instance();
//$this->load->library('database'); == "can't find class database"
$ekeyLoc = $this->CI->session->userdata('ronery');

now if I run this in a module controller, it works as expected.
So googling that error, a lot of "db not loaded"'s come up. Just to make sure, I tried to load the database, but because eff me, it can't find class 'database' NB: database is being autoloaded.
When you assign CodeIgniter super object, I'm assuming it's grabbing the whole jabloney, right? I thought so. But to make sure, I decided to try and load the database class in a module/controller, which turns out, because eff me, couldn't be found.
I tried looking through the pyroCMS docs to find out about any trickery, but there ain't much, and none helpful to my situation.
Why can't I load a core library from a module controller?
Why can't I load a core library into a custom library in system/cms/libraries?
Why doesn't the CodeIgniter super object I assign contain session/db crap?
Why can't I load a library from /addons/shared_addons/library?
Why would a call to $this->session->userdata() work from a module controller, but not from a library in the system/cms/libraries folder even though CodeIgniter super object has been assigned?
Thanks.

After 2 days with no answer, I find it both frustrating and hilarious that continuing to search for help inevitably leads to this question being the top google result. FML.

A: First things first:
$this->load->library('database');

That is not valid CodeIgniter code, like their documentation says it should be:
$this->load->database();

As you've already pointed out though this is autoloaded so there is no need to do that anyway.
Why can't I load a core library from a module controller?
You can.
Why can't I load a core library into a custom library in system/cms/libraries?
You can.
Why doesn't the CodeIgniter super object I assign contain session/db crap?
It does.
Why can't I load a library from /addons/shared_addons/library?
This was not possible in 1.3.x but should have been fixed in 1.3.2, if not has been fixed since in 2.0.
I do not know what you are doing or why you are having such problems, but without any example code or a description of what version of PyroCMS you are using I cannot help any further.
If you have been stuck for two days why have you not posted on our forums? If you HAVE posted on our forums (I didn't see anything about it) you should have put a link in this post to your forum thread to help other people answer the questions.
This is not the first time anyone has been stuck on the internet but you act like it is. Come on, you know how this works! :)


text:
Q: Swipe event overriding touch events on ipad I have got a contact form with few inputs, but seems like the following code is overriding the touch event, so the submit button (or any element where the user have to touch, also the input text to type some question) does not work.
$.fn.swipeEvents = function() {
      return this.each(function() {

        var startX,
            startY,
            $this = $(this);

        $this.bind('touchstart', touchstart);

        function touchstart(event) {
          var touches = event.originalEvent.touches;
          if (touches && touches.length) {
            startX = touches[0].pageX;
            startY = touches[0].pageY;
            $this.bind('touchmove', touchmove);
          }
          event.preventDefault();
        }

        function touchmove(event) {
          var touches = event.originalEvent.touches;
          if (touches && touches.length) {
            var deltaX = startX - touches[0].pageX;
            var deltaY = startY - touches[0].pageY;

            if (deltaX >= 50) {
              $this.trigger("swipeLeft");
            }
            if (deltaX <= -50) {
              $this.trigger("swipeRight");
            }
            if (deltaY >= 50) {
              $this.trigger("swipeUp");
            }
            if (deltaY <= -50) {
              $this.trigger("swipeDown");
            }
            if (Math.abs(deltaX) >= 50 || Math.abs(deltaY) >= 50) {
              $this.unbind('touchmove', touchmove);
            }
          }
          event.preventDefault();
        }

      });
    };

Deleting the following code, the user can use the touch event on inputs, so I suposed it is the problem, but it breaks the "One Page Scroll" function.
EDIT:
I found a solution, but could someone explain me if I am doing it right or not?
I just deleted event.preventDefault();
What does event.preventDefault(); exactly?
(testing around I found out it was the problem), but I am not sure about if that event is useless or in the other hand I just broke the script.
In the other hand, it works on Ipad & Screen Browser.


text:
Q: indexOf element in array problem [google apps script] I'm pretty new to programming with GAS and I believe that the solution should be simple. However...
An array named listWP is basically return value of some function and parsed as an argument to another function. Inside array are various strings, some marked with "c-". I need to find the first and last element with such marking. But I'm allways getting -1 as the result. The code is:
Logger.log(Array.isArray(listWP));   //returns true
var firstC=listWP.indexOf('c');
var lastC=listWP.lastIndexOf('c-');

Content of array listWP is

A: Here's one option.

*

*filter your array first to get all strings with 'c-' prefix.

*Get the index of the first and the last filtered strings in your original array using indexOf()
Sample Code:
function getIndex(){
  var listWP = [ 'URG', 'c-I', 'c-II', 'c-II','c-III' ];
  //Filter array list with prefix 'c-'
  var filteredList = listWP.filter(function(str){return str.indexOf('c-') != -1;});
  Logger.log(filteredList);
  var firstC = listWP.indexOf(filteredList[0]);
  var lastC = listWP.indexOf(filteredList[filteredList.length - 1]);
  Logger.log(firstC);
  Logger.log(lastC);
}

Your code returns -1 since you are actually looking for 'c' and 'c-' in your array.
What the proposed solution does, is to filter first the array if it contains a specific string/char. Notice that I used indexOf() in a string to check if  the prefix 'c-' exist in the string.

A: I realized that indexOf() doesn't work for partial match.
Using .findIndex() would be great option for first match, but I also need the last one (element and index, so by reversing array I'd loose the index).
The working version is:
var allCs=listWP
              .map(function(element, index) { if(element.includes('c-')) {return index} })
              .filter(index => index != null);
  var firstC=allCs[0];
  var lastC=allCs[allCs.length-1];

A: Since you're not looking for an exact match, you should use findIndex(). It will return the index of the first element that matches the condition.

const listWP = [ 'D1', 'c-I', 'URG' ];
const index = listWP.findIndex(item => item.startsWith('c'));
console.log(index);


text:
Q: CSS3 Transition: Different transition for *IN* and *OUT* (or returning from transitioned state) Original Question... updated working code below:
I have a loading image which comes up during an ajax load event. The image shows/hides by adding or removing a "loading" class to the body element. Currently, the loading image animates background-size from 0 to 100%, and fades in the opacity (vice versa for the 'return' transition).
What I want to accomplish, though, is to have the background-size transition happen instantly (not transition) on the fade out, so:

*

*Fade in: opacity from 0 to 1 in .2s, background size from 0 to 100% in .2s

*Fade out: opacity from 1 to 0 in .2s, background size from 100% to 0 should happen instantly
#loader {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -1;
    opacity: 0;
    -moz-opacity: 0;
    transition: all .2s ease-in-out
}

#loader .image {
    width: 400px;
    height: 138px;
    display: block;
    position: absolute;
    z-index: 2000;
    top: 50%;
    left: 50%;
    margin: 0;
    background: url(assets/images/loading.png) no-repeat;
    background-size: 0 0;
    transition: all .2s ease-in-out;
    -webkit-animation: pulse 400ms ease-out infinite alternate;
    -moz-animation: pulse 400ms ease-out infinite alternate;
    -o-animation: pulse 400ms ease-out infinite alternate;
    animation: pulse 400ms ease-out infinite alternate
}

.loading #loader {z-index: 1000; background-color: rgba(255,255,255,.7)}

.loading #loader .image {
    background-size: 100% 100%;
    margin: -69px 0 0 -200px;
    transition: opacity .2s ease-in-out
}

I've changed transition property for this selector .loading #loader .image to "opacity" rather than "all", but it still performs the background-size transition.
Does anyone know how to achieve the different fade in and fade out transitions described above with css3? Thanks!

Updated Working Code
The issue was breaking out the individual properties (margin, background) into a comma separated list. I believe using transition: all will prevent you from being able to do different IN and OUT transitions.
#loader {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -1;
    opacity: 0;
    -moz-opacity: 0;
    .transition(opacity,.4s);
}

#loader .image {
    width: 400px;
    height: 138px;
    display: block;
    position: absolute;
    z-index: 2000;
    top: 50%;
    left: 50%;
    margin: 0;
    background: url(assets/images/loading.png) no-repeat;
    background-size: 0 0;

    -webkit-transition: margin .4s ease-in-out;
    -moz-transition: margin .4s ease-in-out;
    -o-transition: margin .4s ease-in-out;
    -ms-transition: margin .4s ease-in-out;
    transition: margin .4s ease-in-out;

    -webkit-animation: pulse 400ms ease-out infinite alternate;
    -moz-animation: pulse 400ms ease-out infinite alternate;
    -o-animation: pulse 400ms ease-out infinite alternate;
    animation: pulse 400ms ease-out infinite alternate
}

.loading #loader {z-index: 1000; background-color: rgba(255,255,255,.7)}

.loading #loader .image {
    background-size: 100% 100%;
    margin: -69px 0 0 -200px;

    -webkit-transition: background .4s ease-in-out, margin .4s ease-in-out;
    -moz-transition: background .4s ease-in-out, margin .4s ease-in-out;
    -o-transition: background .4s ease-in-out, margin .4s ease-in-out;
    -ms-transition: background .4s ease-in-out, margin .4s ease-in-out;
    transition: background .4s ease-in-out, margin .4s ease-in-out;
}

A: Here is a simplified test case:
div {
    background: blue;
    opacity: 0;
    transition: opacity 2s ease-in-out;
}

div.loading {
    opacity: 1;
    background: red;
    transition: opacity 2s ease-in-out, background 1s ease-in;
}

Notice how the opacity fades the same in and out, but the background only fades in, and immediately turns blue on fade out.
I used :hover as an example, but it should work the same when adding and removing classes with JavaScript.
Demo
If you'd like a more specific example please provide a reduced test case on dabblet or Jsfiddle.


text:
Q: Class 'Html' not found error with updated composer laravel 5.5.21 version. I could not find a resource to correct my error. In my view with the following snippet:
Html::link('http://test.com')

I get the Class 'Html' not found error. My laravel version is 5.5.21.

A: Anybody who are using laravel 5.* have to use laravelcollective/html because Package illuminate/html is abandoned, you should avoid using it.
your composer.json file should contain following code in require section(as i am using laravel 5.2 it will be mentioned as 5.2)
"laravelcollective/html": "5.2.*"

run composer update
config/app.php should contain following code in providers array:
'providers' => [
                       Collective\Html\HtmlServiceProvider::class,

]

and aliases should contain:
'aliases' => [

                'Form' => Collective\Html\FormFacade::class,
                'HTML' => Collective\Html\HtmlFacade::class,
]


text:
Q: How to set background color for all elements with the same class individually based on custom attribute I have multiple elements with the class .hours and they all have a color attribute with a hex value like so:
.
How can I use jQuery to set the background color of all the elements individually so that the element over has the color #FFFFFF and the element
 gets the background color #666666?
My attempt: $('.hours').css('background-color', this.attr.color);

A: try with this
$('.hours').each(function(){
   var t = $(this);
    t.css('background-color', t.attr('color'));
  });
})

A: Pure JS solution (for this jQuery is rather ineffective in my opinion...):
document.querySelectorAll('.hours').forEach(function(el) {
    el.style.backgroundColor = el.getAttribute('color');
});

A: You can use .each to refer to every element and it's color attribute

$('.hours').each(function() {
  let elem = $(this);
  elem.css('background', elem.attr('color'));
});
.hours {
  border: 1px solid black;
  height: 100px;
  width: 100px;
  display: inline-block;
}

A: $(".hours").each(function(){
  let $this= $(this);
  let color=$this.attr("color");
  $this.css("background-color", color);
});

A: Not really what you asked, but the same can be achieved without JS, just with pure CSS and custom properties:

div {
  --color: #e2001a; /* default color */
  background-color: var(--color);
  height: 40px;
}

Example: http://jsfiddle.net/e1fwtcdz/1


text:
Q: Problem to realize a specific regex filter for Fail2ban service I can't find the good regex to match the element that i want to identify
example of my log file to analyze :
[20190625-10:20:20] [INFO ] A connection received from: ::ffff:192.168.1.32 port 52166
[20190625-10:19:22] [INFO ] xrdp_wm_log_msg: login failed for display 0
[20190625-10:20:20] [INFO ] A connection received from: ::ffff:192.168.1.32 port 52166
[20190625-10:20:20] [INFO ] A connection received from: ::ffff:192.168.1.32 port 52167
[20190625-10:21:19] [INFO ] A connection received from: ::ffff:192.168.1.32 port 52176
[20190625-10:21:19] [INFO ] A connection received from: ::ffff:192.168.1.32 port 52177

I want to find the regex to detect a line of this style :
[20190625-11:47:51] [INFO ] A connection received from: ::ffff:192.168.1.32 port 55737

I have tested failregex = ^.*ffff:<HOST> port *$
Not ok

Results
=======

Failregex: 0 total

Ignoreregex: 0 total

Date template hits:

Lines: 6 lines, 0 ignored, 0 matched, 6 missed
[processed in 0.01 sec]

|- Missed line(s):
|  [20190625-10:20:20] [INFO ] A connection received from: ::ffff:192.168.1.32 port 52166
|  [20190625-10:19:22] [INFO ] xrdp_wm_log_msg: login failed for display 0
|  [20190625-10:20:20] [INFO ] A connection received from: ::ffff:192.168.1.32 port 52166
|  [20190625-10:20:20] [INFO ] A connection received from: ::ffff:192.168.1.32 port 52167
|  [20190625-10:21:19] [INFO ] A connection received from: ::ffff:192.168.1.32 port 52176
|  [20190625-10:21:19] [INFO ] A connection received from: ::ffff:192.168.1.32 port 52177

A: I'm not quite sure about it, just guessing that we might want an expression similar to:
(\[[0-9]{8}.+?A connection received from: ::ffff:.+?port\s+[0-9]+)

with an s flag.
Please see the demo for additional explanation.


text:
Q: Flutter IconButton set size after initialization I have a  ButtonBar which has either 5 or 6 buttons.
I.e. it always has 5 buttons and based on a condition, it gets an extra 6th button.
I want to assign an icon size to each button (each button has the same size), but the problem is that the iconSize is dependent on the number of buttons in the bar (since I always need the buttonbar to be exactly one row)
var iconSize = MediaQuery.of(context).size.width / 5 / 2;

var buttons = <IconButton>[];

// Add 5 buttons
buttons.add(
  IconButton(
      icon: Icon(
        Icons.settings,
      ),
      color: Colors.white,
      iconSize: iconSize,
      onPressed: () {
        _goToSettings(context);
      }),
);
// add 4 more
...

// Maybe add a 6th button
buttons.add(IconButton(
 ...
));,

if(myCondition) { buttons.Add(IconButton(...)); }

So iconSize should simply be iconSize = MediaQuery.of(context).size.width / buttons.length / 2;
But the problem is, the length of the array buttons is known only after butons is filled. But once buttons is filled, I cannot set the iconSize any longer
 var size = MediaQuery.of(context).size.width / buttons.length / 2`
 for(var x in buttons){
      x.iconSize = size; // iconSize is final.
 }

Isn't there a clean way to know the size beforehand or to set the size afterwards?
I am aware I can simply do this
var iconSize = MediaQuery.of(context).size.width / (myCondition)?6:5 / 2;

But this is a code smell. It does not scale. What if there are other conditions? I simply want the length of the acutal array as it will be and then set the icon size.
I also cannot assign the IconButton.iconSize to a variable and later on change it. The previous value will still be used.

A: There are of course many different ways to solve this problem, here goes one:
Instead of creating a list of created IconButtons, create a list of functions that return an icon button:
var buttonBuilders = <IconButton Function()>[];
late double iconSize;

Now add functions that create your buttons:
buttonBuilders.add(
  () => IconButton(
    icon: Icon(
      Icons.settings,
    ),
    color: Colors.white,
    iconSize: iconSize,
    onPressed: () {
      _goToSettings(context);
    },
  ),
);

Now that you have your list you can determine what is the appropriate iconSize:
iconSize = MediaQuery.of(context).size.width / buttonBuilders.length / 2;

Now you can either just use the buttonBuilders list and call each element when using it or turn it to a buttons list:
final buttons = buttonBuilders.map((b) => b()).toList();


text:
Q: How can I turn this txt file to a pandas DataFrame? I receive txt file in below structure every week:
txt file
And I would like to turn it into Dataframe which looks like below:
Dataframe
The challenging part is:

*

*The date of some LICENSE is different from others such as CQ_XHO_N1 which doesn't have data on 4 Feb 2016.

*When I receive more txt file next week I need to append the data on the existing dataframe and update the total percentage.

Thanks for the help!

A: As MrSmily2019 said you will want to use https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html.
It does more than just CSV, it can do text. Additionally you can turn text files into csv. You file seems to be "TAB" delimited (how it know to separate) instead of comma. You can adjust the settings so it knows to do it on the appropriate character.
And example of how you would have to modify it is:
pandas.read_csv(filename, sep='\t', lineterminator='\r')


text:
Q: Synchronize reads and writes using ADO.NET and the Access Database Engine I'm using ADO.NET to communicate with a Microsoft Access Database (using the ODBC driver).
Because of the asynchronous write/read behaviour of Jet, sometimes, if you use different connections, (for instance one for writing and another for reading), a small delay between writes on one connection being read on a second connection could happen.
As explained here => https://support.microsoft.com/en-us/kb/200300
Unfortunately, the solution proposed is only valid for ADO (not ADO.NET).
Using transactions seems to reduce the issue but not to solve it.
Any ideas to solve this problem in ADO.NET?

A: The answer for ODBC is right at the end of the Microsoft Support document you cited:

Use the following method to synchronize writes and reads between 2 connections with the Microsoft Access ODBC driver ...

*

*The writer must make the database updates (with or without a transaction) and then close it's connection.

*The reader must close and re-open it's connection prior to attempting to read the data.


text:
Q: How can I stop People from getting to my files but still allow a program to read the files inside of it? I creating a program that plays games and I don't want people to go into a certain folder How can I stop People from getting into a folder but still allow a program to read the files inside of it?
you see the program extracts files from a .zip file(disguised as a .bin file) to a folder somewhere in you PC and I wanna know how to stop people from ever getting to those file.
the way that I was using was the password folder code with a .bat file
cls

@ECHO OFF

title Folder Locker

if EXIST "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" goto UNLOCK

if NOT EXIST Locker goto MDLOCKER

:CONFIRM

echo Are you sure u want to Lock the folder(Y/N)

set/p "cho=>"

if %cho%==Y goto LOCK

if %cho%==y goto LOCK

if %cho%==n goto END

if %cho%==N goto END

echo Invalid choice.

goto CONFIRM

:LOCK

ren Locker "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"

attrib +h +s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"

echo Folder locked

goto End

:UNLOCK

echo Enter password to Unlock folder

set/p "pass=>"

if NOT %pass%==TYPE_YOUR_PASSWORD_HERE goto FAIL

attrib -h -s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"

ren "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" Locker

echo Folder Unlocked successfully

goto End

:FAIL

echo Invalid password

goto end

:MDLOCKER

md Locker

echo Locker created successfully

goto End

:End

but that stops the Program from reading into it!
Is there any other way?


text:
Q: Two HD's, Truecrypt full disk encryption, formatting and installing windows like the title says, I have two physical drives, C: and D;. Both are full disk encrypted with Truecrypt. I would like to format C: and install windows, I'm upgrading from windows 7 to windows 8.1 and want to start fresh.
Do I need to decrypt both drives? C: mounts automatically on boot, but the D: I mount manually after boot. Can I just format c:, then install windows normally, then reinstall Truecrypt and be able to mount D:? Do I need to copy anything from the current C: drive in order to be able to remount the D: drive? I already have everything on C: that I want to keep backed up on an external HD.
TL:DR
I guess my main questions is, will formatting C: affect my access to D: after I get windows installed?
I don't want to spend 3 days decrypting c: if I don't have to.
I'm asking here to double-check things before I take the plunge.

A: If the true crypt volume(d:) is encrypted with only password then you can decrypt/mount it anywhere I.e no dependency on c: . You can format c: . If you have a key file to decrypt the d: then just backup that file before touching anything

A: AFAIK, TrueCrypt volumes are independent of the OS. Hence you can mount your TrueCrypt encrypted volume in any computer where you can run TrueCrypt.


text:
Q: Why do issue view page requires an extra refresh to see the customfield value? I am updating my custom field pro-grammatically if custom field is left blank. I found a question on stack related to this which helped in saving/updating custom field value correctly.I referred this stack question .
As I said I am updating custom field if it is left blank. So I have written some java  code which checks if custom field is null if yes then I am generating some values using java code and updating and saving value in database. This all is working fine. I am doing this all when create issue.
But when issue page is rendered the respective custom field is not displayed,it need an extra page refresh for that. After page reload the custom field is rendered on page with correct value.
Any ideas? Why page reload is required ?
Can some point me to write direction ?
I am using JIRA 6.0.x
I am writing code in MyCustomField extends AbstractSingleFieldType class and using its getVelocityParameters method

A: Check your log files for errors seen the first time the screen is loaded? May also be errors shown in the JavaScript console? Otherwise strip everything back to be as simple as possible and then add complexity back in until it breaks in the same way.


text:
Q: What is compatible Font for both Linux and Windows by their default? What is compatible font that works in both Linux and Windows (in my case Ubuntu 14.04 and Windows 7) by their default (without adding any font addition in both OS)?

A: We'll start with two commands to get the available fonts
fc-list : family | sort -u > ubuntu-fonts
wget -qO- $H='Accept-Language: en-us,en;q=0.5' $H='Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' $H='Connection: keep-alive' -U 'Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2' --referer=/ https://www.microsoft.com/typography/Fonts/product.aspx?PID=161 | grep -Po '(?<=FMID=\d{4}">)[^<>]+' | sort -u > windows-fonts

You could probably do something more clever if you were on Windows but I am not so I have to settle for grepping the online documentation.
I'm also running my version of this on a Ubuntu Live DVD.
Anyway we have two sorted files so we can just compare them to see which fonts exist in both files and we get our answer
$ comm -12 ubuntu-fonts windows-fonts
Symbol

So to answer your question: they share one font
But even then, I bet that's just a name clash.
This is obviously a problem for developers and designers. You want everything to look the same everywhere and not having a common base makes that a lot harder. There are a few options:

*

*Rasterise or vectorise your graphics so they're static graphics rather than text. Depending on the situation this might even be faster but it's also usually a lot less accessible. Screen-readers, for example, won't be able to parse them.

*If you can, use WebFonts or otherwise bundle the font along with your application. This will need a permissive enough license for the font you want to use so that could be expensive or limiting, depending on the fonts you use. It also uses more bandwidth but that hasn't stopped the web embracing them.

*Use similar fonts. There exist lists of near-interchangeable defaults but Graphic Design might be the place to ask.

Which of these best applies really depends on what you're doing... But it's impossible to realistically assume any one font will exist somewhere else.
You should also consider that the same font might not render the same in each situation. For example, there are various antialiasing techniques that make a web page look quite different from platform to platform.
It's really annoying.
All you can do is test try to make things as consistent as possible on any one platform.


text:
Q: Stepper Motor with Raspberry Pi only works with some delay times with GPIOZero I am experimenting with connecting Stepper Motor 28BYJ-48 with ULN2003 Driver board to Raspberry Pi Model 3 B using Python and GPIOZero.  I hacked together some code that works, using a few different examples I found, and I can now get the motor to turn in either direction. There is a time delay problem, however.  When turning counterclockwise, the code works using any delay time from 2 milliseconds all the way out to 50.  In the clockwise direction however, it ONLY works at 2 and 3 millisecond delay, but no others. Very weird.
Code looks like this (very rough - just trying to prove the concept):
import time
import sys
from gpiozero import OutputDevice as stepper

def moveBackward(stepCounter):

  while True:
      stepDir = -1
      for pin in range(0,4):
         xPin=stepPins[pin]          # Get GPIO
         if seq[stepCounter][pin]!=0:
            xPin.on()
         else:
            xPin.off()

      stepCounter += stepDir
      print(stepCounter)
      if (stepCounter < 0):
          stepCounter = stepCount+stepDir

      time.sleep(waitTime)     # Wait before moving onimport time

def moveForward(stepCounter):
  while True:
      stepDir = 1
      for pin in range(0,4):
          xPin=stepPins[pin]          # Get GPIO
          if seq[stepCounter][pin]!=0:
             xPin.on()
          else:
             xPin.off()

      stepCounter += stepDir
      if (stepCounter >= stepCount):
          stepCounter = 0

      time.sleep(waitTime)

IN1 = stepper(17)
IN2 = stepper(22)
IN3 = stepper(23)
IN4 = stepper(24)

stepPins = [IN1,IN2,IN3,IN4] # Motor GPIO pins

stepDir = 1        # Set to 1 for clockwise
                       # Set to -1 for anti-clockwise
mode = 0            # mode = 1: Low Speed ==> Higher Power
                       # mode = 0: High Speed ==> Lower Power

if mode:              # Low Speed ==> High Power
  seq = [[1,0,0,1], # Define step sequence as shown in manufacturers datasheet
         [1,0,0,0],
         [1,1,0,0],
         [0,1,0,0],
         [0,1,1,0],
         [0,0,1,0],
         [0,0,1,1],
         [0,0,0,1]]
else:                    # High Speed ==> Low Power
  seq = [[1,0,0,0], # Define step sequence as shown in manufacturers datasheet
         [0,1,0,0],
         [0,0,1,0],
         [0,0,0,1]]
stepCount = len(seq)

if len(sys.argv)>1: # Read wait time from command line
   waitTime = int(sys.argv[1])/float(1000)
   print(waitTime)
else:
   waitTime = 0.004    # 2 miliseconds was the maximun speed got on my tests
stepCounter = 0

while True:                          # Start main loop

  moveBackward(stepCounter)  # counterclockwise
  #moveForward(stepCounter)  # clockwise

A: So I found this code which works nicely - not sure what the problem above is caused by.
https://github.com/custom-build-robots/Stepper-motor-28BYJ-48-Raspberry-Pi/commit/d8f6b5f3ee4d6b22d3fe40d81d0be09287c97c89


text:
Q: Delimiters of program arguments? What is the syntax to delimit the arguments of a C program.
For example, if I type :
./myprogram 1 2 3 | grep result

The | grep result will be interpreted as arguments (and passed as argv). So how to terminate the arguments after 3 ?

A: I don't think that's true. The shell is the one interpreting the command line arguments and passing them to the corresponding commands as it (the shell) is parsing them.
So your C program, when it finally get's executed will only see the arguments 1, 2, and 3. The pipe and everything after is the responsibility of the shell, and will not get passed in as arguments to the C program.
Here's an example, using a bash shell and bash shell script.
Example (shell script)
A sample script, test.bash:
#!/bin/bash

file=somefile
[ -f $file ] && rm $file
for var in "$@"
do
  echo "$var" >> $file
done

cat $file

Now run the script, results are store in a file, somefile:
$ ./test.bash 1 2 3 '4 5'
1
2
3
4 5

Run it with additional command line arguments:
$ ./test.bash 1 2 3 '4 5' | echo hi
hi

$ cat somefile
1
2
3
4 5

In both cases the script, test.bash only saw the arguments leading up to the pipe (|). The Bash shell was responsible for parsing the commands, and so it never presented anything after, including the pipe (|).
Example (c program)
In case there's any questions about using a shell script, here's a c program that takes the command line arguments and you can see the same behavior with it as well.
The c program is called testc.c:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  printf("Program name: %s\n", argv[0]);

  while ((argc > 1))
  {
    printf("%s\n",&argv[1][0]);

    ++argv;
    --argc;
  }
  return (0);
}

Compile it like so:
gcc testc.c -o testc

Use it like so:
./testc
1
2
3
4 5

$ ./testc 1 2 3 '4 5' | echo hi
hi

You can see in the above that only the first 4 arguments are presented to my c program, testc.


text:
Q: Accesing Private Methods in java? how to implement such a functionality to access private members ?
Java checks access permissions during compilation only. Are you surprised? I was surprised very much to find out this fact.
So you can create skeleton of the third party class (even with empty implementations.). The interesting method should be protected instead of private. Now write your subclass and compile it against your stub. Then package only your subclass and try to run it with the "real" class. It should work.
I have tried it when I had to access private method or field and it worked fine for me.
ref. https://stackoverflow.com/a/4440051/1312423

A:
Java checks access permissions during compilation only. Are you surprised?

Yes, because it checks the access modifier at runtime as well.

I start with
public class AnotherClass {
    protected static void printMe() {
        System.out.println("Hello World");
    }
}

public class Main {
    public static void main(String... args) {
        AnotherClass.printMe();
    }
}

and it compiles and runs.
If I change the printMe() to be private without re-compiling Main it does compile but when I run Main I get.
Exception in thread "main" java.lang.IllegalAccessError: tried to access method AnotherClass.printMe()V from class Main
    at Main.main(Main.java:22)


text:
Q: Android Studio 1.1, simple junit test setup I have read around, there are a number of extensive answers (like this one) but the Android world evolves so fast that they seem to be a bit outdated and the official documentation still refers to Eclipse with ADT.
I am running AS 1.1 and I am trying to setup simple junit tests to run on the emulator, without Robolectric. If I don't include junit in my build.gradle, it can't find @After, @Before and @Test and I get package org.junit does not exist. Upon adding
// unit tests
androidTestCompile 'junit:junit:4.11'

the error becomes
Error:duplicate files during packaging of APK
[...]/app/build/outputs/apk/app-debug-test-unaligned.apk
Path in archive: LICENSE.txt
Origin 1: [...]/.gradle/caches/modules-2/files-2.1/org.hamcrest/hamcrest-core/1.3/42a25dc3219429f0e5d060061f71acb49bf010a0/hamcrest-core-1.3.jar
Origin 2: [...]/.gradle/caches/modules-2/files-2.1/junit/junit/4.11/4e031bb61df09069aeb2bffb4019e7a5034a4ee0/junit-4.11.jar
You can ignore those files in your build.gradle:
android {
  packagingOptions {
    exclude 'LICENSE.txt'
  }
}

Following the console suggestion of excluding LICENSE.txt, it then works but it feels like a hack. So I'm wondering, am I maybe missing something? Thanks.

A: Android Studio unit testing support comes in 1.1 Beta 4 (release announcement) with Gradle plugin version 1.1.0-rc1.
More info in official document.
However it is experimental feature for now. E.g. it breaks installDebug gradle task.
For using JUnit in instrumentation tests there is good guide for Espresso library and another covering new AndroidJUnitRunner.

A: If it's any use I set up a boiler plate project allowing the use of Unit tests and Espresso tests by the use of switching build variants. You won't need the use of any third party plugins with this.
https://github.com/hitherejoe/Android-Boilerplate


text:
Q: Model item DateTime plus 2 Year I have a model like:
public string GroupName {get;set;}
public DateTime? AssignDate {get;set;}

I add this model to a View. For Model Item AssignDate, I want to add plus 2 years. So if the assigndate is 01/Jan/2019 then the View is 01/Jan/2021.
@Html.DisplayFor(modelItem => item.AssignDate)

Does anyone have an idea for this thing?
Thank you.

A: Because your DateTime object is nullable check if it is null first using .HasValue (a bool).
After than you can simply add years to the object with .AddYears(int). Documentation on AddYears here.

A: I got the answer:
So I remove @Html.DisplayFor and change to the following code:
@item.AssignDate.Value.AddYears(2).ToString("yyy-MM-dd")

Cheers,


text:
Q: color error in converting a transparent png to jpg in php with glib I try to convert a partly transparent png to a jpg in php with gdlib. I found two snippets to help me with that, but both methods have the same problem: The half transparent colors are darker and do not look right. Here a enlarged sample from photoshop: left the png (with white in background instead of transparent), right the converted png to jpg with both snippets I used:
difference png (left) to jpg (right)
Here the original Png-File: golf.png
Any help would be really appreciated!
$input_file = "card/golf.png";
$output_file1 = "card/golf1.jpg";
$output_file2 = "card/golf2.jpg";

$image = imagecreatefrompng($input_file);

$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagejpeg($bg, $output_file1, 100);
imagedestroy($bg);
imagedestroy($image);

list($width, $height) = getimagesize($input_file);
$image = imagecreatefrompng($input_file);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output,  255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $image, 0, 0, 0, 0, $width, $height);
imagejpeg($output, $output_file2, 100);
imagedestroy($output);

A: You're suffering from quantization. JPEG does not handle this type of image well at all. If you want to lessen the color changes you need to adjust your quantization tables. If you use all 1s for the quantization tables you don't get the color changes.


text:
Q: Creating Android TV app to take HDMI port data and send it into my Custom App Trying to create an Android TV app that will take input from the HDMI port and display it into a videoView.
I have loaded a library file of Realtek and created a stream service.
The hardware is Realtek RTD1295
Inside the MainFragment, the HDMI Manager is being created.
The onStart method is given as follows:
@Override
public void onStart() {
    super.onStart();

    if (preferences == null) {
        preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    }

    // halt startup if we don't have all needed permissions
    if (!checkPermissions()) {
        return;
    }

    if (hdmiSurfaceHolderCallback == null) {
        hdmiSurfaceHolderCallback = new HdmiSurfaceHolderCallback();
        surfaceHolder.addCallback(hdmiSurfaceHolderCallback);
    }

    if (hdmiHotplugReceiver == null) {
        hdmiHotplugReceiver = new HdmiHotplugReceiver();
        getActivity().registerReceiver(hdmiHotplugReceiver, new IntentFilter(HDMIRxStatus.ACTION_HDMIRX_PLUGGED));
    }

    if (checkHdmiReadyHandler == null) {
        checkHdmiReadyHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                checkHdmiReady();
                return true;
            }
        });
    }

    if (hdmiRxManager == null) {
        hdmiRxManager = new RtkHDMIRxManager(); //Line 128 Of MainFragment
    }

    if (streamActivityReceiver == null) {
        streamActivityReceiver = new StreamActivityReceiver();
        getActivity().registerReceiver(streamActivityReceiver, new IntentFilter(STREAM_ACTIVITY_INTENT));
    }

    if (preferencesChangeListener == null) {
        preferencesChangeListener = new SharedPreferenceChangeListener();
        preferences.registerOnSharedPreferenceChangeListener(preferencesChangeListener);
    }
}

There are two issues,

*

*First run of the app is successful always. But from second time on
wards it always throws the same error.

*HDMI input is never detected even when the app runs for the first time.

The current Development is based on this project
The Error Log is as follows:
    Process: com.hydra.sid.hdmistreamer, PID: 5757
                                                                      java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.hydra.sid.hdmistreamer-1/base.apk", zip file"/data/app/com.hydra.sid.hdmistreamer-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.hydra.sid.hdmistreamer-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.hydra.sid.hdmistreamer-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.hydra.sid.hdmistreamer-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.hydra.sid.hdmistreamer-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.hydra.sid.hdmistreamer-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.hydra.sid.hdmistreamer-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.hydra.sid.hdmistreamer-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.hydra.sid.hdmistreamer-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.hydra.sid.hdmistreamer-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.hydra.sid.hdmistreamer-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.hydra.sid.hdmistreamer-1/lib/x86, /vendor/lib, /system/lib]]] couldn't find "librealtek_runtime.so"at java.lang.Runtime.loadLibrary(Runtime.java:367)
                                                                          at java.lang.System.loadLibrary(System.java:1076)
                                                                          at com.realtek.hardware.RtkHDMIRxManager.<clinit>(RtkHDMIRxManager.java:30)
                                                                          at com.hydra.sid.hdmistreamer.layout.MainFragment.onStart(MainFragment.java:128)
                                                                          at android.app.Fragment.performStart(Fragment.java:2244)
                                                                          at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1002)
                                                                          at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
                                                                          at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1130)
                                                                          at android.app.FragmentManagerImpl.dispatchStart(FragmentManager.java:1958)
                                                                          at android.app.FragmentController.dispatchStart(FragmentController.java:163)
                                                                          at android.app.Activity.performStart(Activity.java:6259)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                          at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:148)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: I had also developed this type of project and got same error in my situation this happed because the media box that i was using had not support realtek hardware so check your box support and use the Realtek  support  then your app will able to find realtek lib from system


text:
Q: Using eval to println elements of library-dependencies in SBT 0.12.x shell Trying to master SBT and Scala makes my live tough at times when simple things in theory turn themselves into not so simple in practise.
I'm working with Apache Spark 0.9.0-incubating that uses SBT 0.12.4.
While poking around in their SBT build configuration I ran across an issue of how to println elements of library-dependencies in SBT (interactive) shell. It's a more general question of how to eval more complex Scala expressions in sbt shell?
> external-mqtt/library-dependencies
[info] List(org.scala-lang:scala-library:2.10.3, io.netty:netty-all:4.0.13.Final, org.eclipse.jetty:jetty-server:7.6.8.v20121106, org.eclipse.jetty.orbit:javax.servlet:2.5.0.v201103041518, org.scalatest:scalatest:1.9.1:test, org.scalacheck:scalacheck:1.10.0:test, com.novocode:junit-interface:0.9:test, org.easymock:easymock:3.1:test, org.mockito:mockito-all:1.8.5:test, commons-io:commons-io:2.4:test, commons-io:commons-io:2.4, org.eclipse.paho:mqtt-client:0.4.0)

I managed to do the following
> eval libraryDependencies in externalMqtt
[info] ans: sbt.SettingKey[Seq[sbt.ModuleID]] = sbt.Scoped$$anon$1@aa3170e

but am struggling with getting the Seq[sbt.ModuleID] out of sbt.SettingKey.
A concise explanation on how to proceed would be very appreciated. Thanks.

A: Instead of you using eval, if you first drop into:
consoleProject

then you can attach .eval to settings, so e.g.
> consoleProject
[info] Starting scala interpreter...
[info]
import sbt._
import Keys._
import currentState._
import extracted._
import cpHelpers._
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_51).

scala> (fullClasspath in Compile).eval.foreach(println)
Attributed(/Users/tisue/Dropbox/repos/euler/target/scala-2.10/classes)
Attributed(/Users/tisue/.sbt/boot/scala-2.10.3/lib/scala-library.jar)

This doesn't answer your question directly; I don't know how to make eval do what you want. As documented at http://www.scala-sbt.org/release/docs/Detailed-Topics/Console-Project.html , and as actually visible in the above transcript, consoleProject does a number of imports that bring useful names and implicits into scope, which is what makes the above work.  You might expect that eval would evaluate code you pass it in a context where the same identifiers and implicits are in scope, but it doesn't. (I tried putting the same imports into a call into eval but it didn't work.)
Not the greatest answer — perhaps someone else can be more authoritative.


text:
Q: React website not showing after deployment with firebase Trying to deploy for the first time to firebase , I looked in alot of guides on youtube and stackoverflow did the same as they did but keep getting blank page after deploy the app.
This is my process:
-yarn build
-firebase login
-firebase init
That's how i filled the init:

*

*Hosting: Configure and deploy Firebase Hosting sites
2.What do you want to use as your public directory? build
3.Configure as a single-page app (rewrite all urls to /index.html)? No
4.File build/404.html already exists. Overwrite? No
5.File build/index.html already exists. Overwrite? (y/N) No
I tried few ways sometimes i change some of them to Yes still the same result
-firebase deploy
That how my files looks like:

This is the code of my Router:
const App = () => {
  return (

      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/about" exact component={About} />
        <Route path="/brands" exact component={Brands} />
        <Route path="/guide" exact component={Guide} />
        <Route path="/contact" exact component={Contact} />

        <Route
          render={function() {
            return
Not found
;
          }}
        />
      </Switch>

  );
};

The error i have:

Update:
This is the screen now:

Update:
The new error:

A: It's possible the index.html file in build got overwritten during the firebase init process. When that happens, firebase overwrites the files with its default template structures and hence the reason for that template. If the index.html file in the public folder still has your required template, delete the build folder, alongside the files and folders generated by firebase(not really a requirement, but just to keep stuff cleaner and fresher) i.e .firebase folder, .firebaserc and firebase.json file, and then:

*

*run npm run build or yarn build, depending on your package manager

*run firebase login and fill necessary requirements (skip if already logged in)

*run firebase init

*select the Hosting option (navigate using arrow keys, select using spacebar. Enter after selection)

*select an existing firebase app or create a new one

*type build for the folder choice

*type/select yes for single page app option

*type/select no to avoid overwriting of files by firebase

*run firebase serve --only hosting for testing

*run firebase deploy

A: Go to your firebase.json file and make sure that the 'public' key under "hosting" is set to "build" like below:
"hosting": {
"public": "build"
}

It was likely set to "public" by default when you ran firebase init. In which case it would look like this:
"hosting": {
"public": "public"
}

The problem with the default is that React places all your static assets in the 'build' directory when you run npm run build, so that is where you want to point firebase to.
I had the same issue and this worked for me.

A: I tried to deploy to github before doing it with firebase , So an "homepage:" field was left in the package.json. all i needed to do was to delete this field and rebuild and redeploy and everything is working

A: *

*First you npm build or yarn build depending on what you use.

*Then firebase login.

*Then firebase init - choose hosting, then choose build instead of the public that is generated automatically for you.

*Then you choose yes and then no.

*And then you deploy.

A: you'll need to set proper HTTP caching headers for service-worker.js file in firebase.json file or you will not be able to see changes after first deployment (issue #2440). It should be added inside "hosting" key like next. See this:
https://create-react-app.dev/docs/deployment/#firebase

A: *

*Run:

% firebase login
% firebase init

*Select 'hosting - with firebase'

*Choose Yes to overwrite

*Choose Build

*Choose no to Deploy with Github

*Run:
% npm run build
% firebase deploy

A: Same error I got then my problem solved with following step
run npm run build or yarn build, depending on your package manager
run firebase login and fill necessary requirements (skip if already logged in)
run firebase init
select the Hosting option (navigate using arrow keys, select using spacebar. Enter after selection)
select an existing firebase app or create a new one
type build for the folder choice
type/select yes for single page app option
type/select no to avoid overwriting of files by firebase
run firebase serve --only hosting for testing
run firebase deploy

A: I don't know the exact reason of the issue (Page was blank and was giving 404 Error) but somehow, I solved it. The reason of this issue could be (according to my assumptions):

*

*By running command (npm run build) just before (firebase deploy
command)

*Setting public directory option to public or build instead of using
dist

*Setting (Configure as a single-page app (rewrite all urls to
/index.html)? No)

*Setting (File dist/index.html already exists. Overwrite? Yes)

The steps that I followed to solve this issue are:
Pre-requisite:

*

*delete .firebase folder

*copy your project's index.html file content/code and replace it with
the build folder's index.html file content because these two files
should have same content/code

Step 0): npm run build (For React App)
Step 1): npm install -g firebase-tools
Step 2): firebase login (If you are already login, then there is no need for this step)
Step 3): firebase init
Step 4): Are you ready to proceed? Yes
Step 5): What do you want to use as your public directory? dist
Step 6): Configure as a single-page app (rewrite all urls to /index.html)? Yes
Step 7): Set up automatic builds and deploys with GitHub? No
Step 8): File dist/index.html already exists. Overwrite? No
Step 9): firebase deploy


text:
Q: A question re: "A Mathematician Plays the Stock Market" Excerpt here:

A contrived but interesting illustration of a self-fulfilling belief involves a tiny investment club with only two investors and ten possible stocks to choose from each week. Let's assume that each week chance smiles at random on one of the ten stocks the investment club is considering and it rises precipitously, while the week's other nine stocks oscillate within a fairly narrow band.
George, who believes (correctly in this case) that the movements of stock prices are largely random, selects one of the ten stocks by rolling a die (say an icosahedron -- a twenty-sided solid -- with two sides for each number). Martha, let's assume, fervently believes in some wacky theory, Q analysis. Her choices are therefore dictated by a weekly Q analysis newsletter that selects one stock of the ten as most likely to break out. Although George and Martha are equally likely to pick the lucky stock each week, the newsletter-selected stock will result in big investor gains more frequently than will any other stock.
The reason is simple but easy to miss. Two conditions must be met for a stock to result in big gains for an investor: It must be smiled upon by chance that week and it must be chosen by one of the two investors. Since Martha always picks the newsletter-selected stock, the second condition in her case is always met, so whenever chance happens to favor it, it results in big gains for her. This is not the case with the other stocks. Nine-tenths of the time, chance will smile on one of the stocks that is not newsletter-selected, but chances are George will not have picked that particular one, and so it will seldom result in big gains for him. One must be careful in interpreting this, however. George and Martha have equal chances of pulling down big gains (10 percent), and each stock of the ten has an equal chance of being smiled upon by chance (10 percent), but the newsletter-selected stock will achieve big gains much more often than the randomly selected ones.

I don't see how picking what the newsletter recommends (Martha) would yield gains more frequently than a random choice (George). Consider if the newsletter itself were just rolling a die to make its selection -- then there's no difference between Martha or George in their approach.
I'm wary to suggest Paulos has made an error here, so I'm assuming I'm the one who's erred. Can anyone see where I've gone wrong? Thank you.
Here's from the next page in the book:

Reiternated more numerically, the claim is that 10 percent of the time the newsletter-selected stock will achieve big gains for Martha, whereas each of the ten stocks has only a 1 percent chance of both achieving big gains and being chosen by George. Note again that two things must occur for the newsletter-selected stock to achieve big gains: Martha must choose it, which happens with probability
  $1$, and it must be the stock that chance selects, which happens with probability $1/10$th. Since one multiplies probabilities to determine the likelihood that several independent events occur, the probability of both these events occurring is $1 \times 1/10$, or 10 percent. Likewise, two things must occur for any particular stock to achieve big gains via George: George must choose it, which occurs with probability $1/10$th, and it must be the stock that chance selects, which happens with probability $1/10$th. The product of these two probabilities is $1/100$th or 1 percent.
Nothing in this thought experiment depends on there being only two investors. If there were one hundred investors, fifty of whom slavishly followed the advice of the newsletter and fifty of whom chose stocks at random, then the newsletter-selected stocks would achieve big gains for their investors eleven times as frequently as any particular stock did for its investors. When the newsletter-selected stock is chosen by chance and happens to achieve big gains, there are fifty-five winners, the fifty believers in the newsletter and five who picked the same stock at random. When any of the other nine stocks happens to achieve big gains, there are, on average, only five winners.
In this way a trading strategy, if looked at in a small population of investors and stocks, can give the strong illusion that it is effective when it is only chance at work.

A: What's key is the sentence
"the news-letter selected stock will result in big investor gains more frequently than will any other stock."
The question is not "whether the newsletter selected stock does better than a randomly chosen stock". The question is: given the investment strategies of George and Martha, whether any other choice of stock will outperform for the investing club as a whole the newsletter stock.
To make extremely explicit: Given a sequence of stock choices $s_1, s_2, \ldots, s_n$, we count the number of times that $s_i$ hit it big while it is in the portfolio of Martha and add to it the number of times that $s_i$ hit it big while it is in the portfolio of George.
For the Q-analysis sequence, at every stage there is 1/10 chance that the chosen stock hits it big. When that happens, there is a 1/10 chance that George picked that stock. This means that in general there is a 11% chance that the stock picked by the Q-newsletter will result in observed investOR gains.
If you choose any sequence of stocks that avoids the Q-analysis sequence, at every stage there is still a 1/10 chance that the chosen stock hits it big. When that happens, there is 0 chance that Martha picked it, but there is a 1/10 chance that George picked it. This means that in general there is a 1% chance that any non-Q-analysis sequence will result in observed investOR gains.

Obviously, this weird result will no longer hold if you have a large number of investors each following divergent investment strategies (say, if everyone picks stocks at random).

Another way to think about this is: you want to think about the question "If a tree falls in a forest and no one is around to hear it, does it make a sound?", but the book is talking about the question "If a tree falls in a forest and no one is around to hear it, does anyone hear a sound?" The answer to this second question is definitely "no".

A: The book is nonsense.  The statement "the newsletter selected stock will result in big investor gains more often than any other stock" is wrong because the George selected stock will result in big investor gains just as often as the newsletter selected stock.  The book says the newsletter is no smarter than George.  We can do the same calculation centered on George and find that George gets big gains $10\%$ of the time and any other stock only achieves big investor gains $1\%$ of the time because the newsletter only buys it $10\%$ of the time.  If we had nine Georges, who conspired to each choose a different stock than the others and the newsletter, each stock would be bought every week and each stock would result in big investor gains $10\%$ of the time.  The problem is the book's interpretation of "any other stock".

A: Per the author's final sentence in the excerpt, their point seems to be: "If you do math incorrectly, you can see unexpected results." Any reasonable analysis would of course compare strategies and investment returns, and it would find the approaches to be comparable.


text:
Q: Persisting an object across multiple sessions in ASP.Net MVC What is the best way of persisting a collection of objects across multiple sessions in ASP.Net MVC?  I'd like to have a collection in which many users can "take the next X" from the collection - e.g. process the next X records that someone else isn't using - so it will have to persist in the service layer across multiple sessions of the the application.
It's an internal website, so there's no worry of users getting to things they're not supposed to, it will only be used by those who should have access to the data.
Considering using a static object in the service layer, but I'm not sure how/whether that will persist across sessions, or am I approaching this entirely the wrong way and should I be using the database to store the information instead?

A: Yes, this definitely seems like a concern for the database - storing this in memory (ala your static variable approach) does not allow load balancing and the information will be lost each time IIS recycles the App Pool.

A: I would rather go the DB way. Always consuming from the same place and avoid having to keep track with multiple lists. You can get the Next X from the DB and flag them and move to the next ones


text:
Q: Upload file to server from android 11 I used this example (http://reecon.wordpress.com/2010/04/25/uploading-files-to-http-server-using-post-android-sdk/) to upload file from android device to server, it works fine on android 8. But it does not work with android 11. Can any one help me? :(

A: I got the solution. I use this example:
Uploading files to HTTP server using POST on Android.
in a thread. it works fine. It a new experience for me and I share this for you too. :)


text:
Q: How to packagingExcludes css with regex if css is minified <packagingExcludes>%regex[.*(\w)(?!=\.min)\.css]</packagingExcludes>

I need to exclude xxx.css if it has xxx.min.css, but this doesn't work.

e.g. main.css, main.min.css, table.css, main-14.css, main-14.min.css.

Bold is equal to the current files selected.
What am I doing wrong?
UPDATE: I can get the filename .*(\/)(?<filename>\S+)(?=.min) in group filename. So, how can I do a global search with this filename and do this in one %regex[...] script?


text:
Q: Node.js: Two different applications competing to become servers? Good day, everyone.
I wanted to know if this was possible in Node.js. Suppose I have two different node applications, and they are both going to compete to be a server on a certain port. Whichever reaches the port first becomes the server, and the other one automatically becomes a client of that server.
Here is a simple diagram of what I am trying to explain:

So in this example, process 1 becomes the server because it reached the port first. Process 2 automatically becomes Process 1's client. However, I also want the functionality that if anything happens to Process 1 and the connection fails, then Process 2 becomes the new server on that same port.
Here is a diagram on what I mean:

Here is the code I have so far:
var net = require('net');

var TIMEOUT_TIME = 3000; // in milliseconds
var PORT_NUMBER = 1337;

// Attempt to create server.
var application1 = net.createServer(function (socket) {
  socket.write('Hello Server 1\r\n');
  socket.end("hello");
  console.log("Someone connected to Server 1. \n");
  socket.pipe(socket);
});

application1.listen(PORT_NUMBER, function(){
    console.log("\nServer 1 is now the official server. \n");
    setTimeout(function() {
        application1.close();
        console.log("Server 1 has been closed.");
    }, TIMEOUT_TIME);
})
.on('error', function(err) {
    console.log('there was an error.');
    if(portIsUsed(err)) {
        console.log("Port Was In Use! (This is Server 1 trying to connect.)");
        net.connect(PORT_NUMBER, function() {
            console.log("Server 1 connected to port.\n");
        });
    }
})
.on('end', function() {
    console.log("server 1 disconnected from port");
});

// Attempt to create server.
var application2 = net.createServer(function (socket) {
  socket.write('Hello Server 2\r\n');
  socket.end("hello");
  console.log("someone went into application2.");
  socket.pipe(socket);
});

application2.listen(PORT_NUMBER, function() {
    console.log("\nServer 2 is now the official server. \n");
})
.on('error', function(err) {
    if(portIsUsed(err)) {
        console.log("Port Was In Use! (This is Server 2 trying to connect.)\n");
        net.connect(PORT_NUMBER, function() {
            console.log("Server 2 connected to port.\n");
        })
        .on("end", function() {
            // code here for when the connection ends?
        });
    }
})
.on('end', function() {
    console.log("server 2 disconnected from port");
});

function portIsUsed(err) {
    return err.code === "EADDRINUSE";
}

Application2 successfully detects the EADDRINUSE error (because Application1 connects first, so the port is used), but how do I make become the new server in the case that Application1 drops? I tried using .on("end", ...) inside the .on("error",...) in application2, but its not working.
Is this even possible in Node.js, due to its single-threaded nature? In the Node API I saw that cluster was used to work on more than 1 thread if I had a multicore machine. Should I use that instead?
I'm new to Node.js, so any help pointing me the right way would be appreciated.
Thank you,

A: I saw You're trying to write same app twice to be able handle request and balance between them.
So thats solution:
write normal single-threaded app and then run it using pm2 (https://github.com/Unitech/pm2):
install
npm install pm2 -g

run
pm2 start app.js -i max

use keymetrics (https://keymetrics.io/):
pm2 interact public_key secret_key

doing app that trying to dominate on port is not good approach, even when You're switching roles from server to client.
it's better to know that one app runs on one port and another on second port and it's normal.


text:
Q: Property 'name' does not exist on type 'EventTarget' - React + TypeScript This is my code:
<Button
  disabled={filter === 'Active'}
  size='md'
  color='primary'
  name='Active' // complete = false
  onClick={this.handleFilterClick}
>
  Active
</Button>

On my function handler I get error on the event:
handleFilterClick = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    // continue here
     const { name } = e.target;

It says:
Property 'name' does not exist on type 'EventTarget'.

I also tried:
(e:  React.MouseEvent<HTMLInputElement, MouseEvent> &  React.MouseEvent<HTMLButtonElement, MouseEvent>)

What is the event type for button? In JavaScript, this works, it can accept name but I don't know why not typescript?

A: event.target is the element from which element is dispatched, which necessarily doesn't have to be the HTMLButtonElement defined in the event.
However, if you use event.currentTarget, you will see that this error goes away:
const { name } = event.currentTarget;

If you have to use event.target itself, you would have to cast the object:
const { name } = event.target as HTMLButtonElement;

From the typings:
/**
  * currentTarget - a reference to the element on which the event listener is registered.
  *
  * target - a reference to the element from which the event was originally dispatched.
  * This might be a child element to the element on which the event listener is registered.
  * If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239
*/

A: While the solution proposed by @Agney will probably work in most cases, it failed me when I was using event delegation – the property I want to access was on the child element, which was event.target, not event.currentTarget.
I appease the TS compiler with broadening the type of event.target:
const handleMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
  // Hey, compiler, the event target can have any of the properties of an SVG element:
  const target: EventTarget & React.SVGProps<SVGSVGElement> = e.target
  if (target.id) {
    // ...
  }

The example is using id property instead of name, but the principle is the same. The compiler error is gone.


text:
Q: Regex - lowercase alphanumeric and forward slash I have a regular expression that allows lowercase alphanumeric characters, however now I need to add a forward slash.
My current regex is ^[a-z0-9]+$.
I've tried ^[a-z0-9\/]+$ but it's not working.

A: Use
var pat = "^[a-z0-9/]+$";

No need to escape the / in C# patterns.
See IDEONE demo:
var pat = "^[a-z0-9/]+$";
Console.WriteLine(Regex.IsMatch("abc122/", pat)); // TRUE


text:
Q: React context value not available in child class component I have declared a React context in indexa.js and I'm trying to access the context value set in App.js in Employee.js. But it's not rendering the value I'm new to React. Please help me out. Thanks in advance
//index.js
export const employeeContext = React.createContext();
const AppContextInteration = <App></App>
ReactDOM.render(AppContextInteration, document.getElementById('root'));

//App.js
export class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            EmpId: 1,
            EmpName: 'xxx'
        }
    }

    render() {
        return (

 App Component

 Employee Id : {this.state.EmpId}

                <employeeContext.Provider value={this.state} >
                     <Employee/>
                </employeeContext.Provider>

        )
    }
}

//Employee.js

export class Employee extends React.Component {
    context = employeeContext;
    constructor(props) {
        super(props);
        console.log();
    }
    render() {
        return (

Employee Component

 Employee Id  : {this.context.EmpId}

        )
    }
}

A: you can use Context.Consumer
<MyContext.Consumer>
  {value => /* render something based on the context value */}
</MyContext.Consumer>

https://reactjs.org/docs/context.html
I prefer using functional component with useContext hook (this is very easy to implement)
you may refer React hooks tutorial(useContext)

A: As you said you are new to react, still you have worked so well almost.This error occurs may be you haven't import context(employeeContext) in your employee component, if you already imported then i suggest you to use convert it into function component and use (useContext) hook that would be much better, performance and understanding wise.
Thanks
link: https://www.youtube.com/watch?v=UjjtvroahBU&list=PLC3y8-rFHvwisvxhZ135pogtX7_Oe3Q3A&index=17&ab_channel=Codevolution


text:
Q: Dropout Implementation: Do all images in a batch get the same mask in Caffe? I just wanted to confirm whether all the images in a mini-batch get the same dropout mask or not.
For clarification:  Suppose a 1000 sized vector is passed through the Dropout layer with a mini batch size of 100.
Now, the 21st and 31st elements of the 1st image's vector gets dropped out.
Is it necessary that the 21st and 31st elements will get dropped for all the remaining 99 images in the batch? Or is it the case that every image gets a separate mask?

A: No, each image in a batch gets an independent, completely random mask.
Actually, the Dropout layer doesn't even care about the shape of its input: It counts the number of elements in the bottom Blob (i.e. for a batch size of 10 images, 3 channels and 224x224, it would be 10 * 3 * 224 * 224 = 1505280), and generates the same number of independent random numbers.


text:
Q: Removing element from JS array of objects So I have something like this defined
var myList = [];

//I populate it like this
myList.push({ prop1: value1,
                      prop2: value2,
                      prop3: value3
});

Is it possible to remove items from the list, based on prop1 value w/o searching through the array?

A: No.  You must loop over the array in some fashion, checking the properties of each object within, and perform removal as you hit them.

A: Here you go:
myList = myList.filter( function ( obj ) {
    return obj.prop1 !== value;
});

where value is the value that you're testing against.
Live demo: http://jsfiddle.net/LBYfa/
So, if the value of the 'prop1' property is equal to the value that you're testing against, obj.prop1 !== value will evaluate to false and that element will be filtered out.

A: Does this help:

Array.prototype.remove = function(s) {
  var i = this.indexOf(s);
  if(i != -1) this.splice(i, 1);
}

A: Is it required that myList have index of integral type? Might you instead use key => value pairs - that is, an associative array with the value of prop1 as the key? How likely is it that prop1 will be unique? If it's unlikely, consider implementing a multimap.


text:
Q: how to exit when I return laravel Validation? i' new to laravel here I have created a registration API and private function for validation but not show validation.
that is my validation function
`private function validateInfo($request, $toValidate) {

        $validator = Validator::make($request->all(), $toValidate);
        if ($validator->fails()) {
            $errors = $validator->errors()->toArray();
            $values = array_values($errors);
            $arr = [];
            foreach ($values as $errorlst)
                array_push($arr, $errorlst[0]);
            $error = implode(',', $arr);
            return response()->json(['error' => true, 'message' => $error], 400);
            exit;
        }
    }`

call function under switch case :-
 switch ($request->user_type) :
            case "teacher":
                $this->validateInfo($request, [
                    'first_name' => 'required',
                    'last_name' => 'required',
                    'telephone' => 'required',
                    'country' => 'required',
                    'date_of_birth' => 'required|date',
                    'email' => 'required|email|unique:users',
                    'password' => 'required|min:6',
                ]);
                break;
            case "student" :
                $this->validateInfo($request, [
                    'first_name' => 'required',
                    'last_name' => 'required',
                    'telephone' => 'required',
                    'country' => 'required',
                    'date_of_birth' => 'required|date',
                    'email' => 'required|email|unique:users',
                    'password' => 'required|min:6',
                ]);
                break;
        endswitch;

it is not showing validation error. Any Mistake?
Thank You

A: Instead of this you can create a form request to validate your request.
class UserRequest extends FormRequest
{
    protected function failedValidation(Validator $validator) {
        throw new HttpResponseException(
                    response()->json([
                        "message" => implode(',',$validator->errors()->all())
                    ], 422));
    }

    public function rules() {
        return  [
            'first_name' => 'required',
            'last_name' => 'required',
            'telephone' => 'required',
            'country' => 'required',
            'date_of_birth' => 'required|date',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);
    }
}

Please check docs for more info.

A: You Need to return For Display Like
switch ($request->user_type) :
            case "teacher":
              return $this->validateInfo($request, [
                    'first_name' => 'required',
                    'last_name' => 'required',
                    'telephone' => 'required',
                    'country' => 'required',
                    'date_of_birth' => 'required|date',
                    'email' => 'required|email|unique:users',
                    'password' => 'required|min:6',
                ]);
                break;
            case "student" :
              return $this->validateInfo($request, [
                    'first_name' => 'required',
                    'last_name' => 'required',
                    'telephone' => 'required',
                    'country' => 'required',
                    'date_of_birth' => 'required|date',
                    'email' => 'required|email|unique:users',
                    'password' => 'required|min:6',
                ]);
                break;
        endswitch;


text:
Q: Why does the appearance of the Windows Phone 8 virtual keyboard screw up my page layout? I have a C# Windows Phone app with a ComponentOne rich text box as the main content element.  If there's enough text in the text box that some of it scrolls out of view when the virtual keyboard rolls up, the text box shrinks in size, not temporarily, permanently.  I don't have any sizechanged event handlers or anything like that at all.  Note, if the amount of text in the rich text box does not result in the any text getting pushed vertically off the screen when the virtual keyboard appears, than the problem does not occur.
Here's the XAML for the page:
<phone:PhoneApplicationPage
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
            xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:SpeechRecoControl="clr-namespace:SpeechRecoControl.Controls;assembly=SpeechRecoControl_WP8"
            xmlns:RichTextBox="clr-namespace:C1.Phone.RichTextBox;assembly=C1.Phone.RichTextBox.8"
            xmlns:UserControls="clr-namespace:VoiceEditBox_WP8.UserControls;assembly=VoiceEditBox_WP8" x:Name="rootFrame"
            x:Class="SuperNote.Pages.NoteEntry"
            FontFamily="{StaticResource PhoneFontFamilyNormal}"
            FontSize="{StaticResource PhoneFontSizeNormal}"
            Foreground="{StaticResource PhoneForegroundBrush}"
            SupportedOrientations="Portrait" Orientation="Portrait"
            mc:Ignorable="d"
            shell:SystemTray.IsVisible="True"
            DataContext="{Binding Source={StaticResource Locator}, Path=Main}"
            >

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <!--TitlePanel contains the name of the application and page title-->

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Margin="12,0,12,0">
            <UserControls:VoiceEditBox x:Name="vebNote"  />
        </Grid>
    </Grid>

    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar x:Name="appbarMain" IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton x:Name="btnUndo" IconUri="/Assets/Images/Icons/Command-Undo.png" Text="Undo" Click="btnUndo_Click"  />
            <shell:ApplicationBarIconButton x:Name="btnRedo" IconUri="/Assets/Images/Icons/Command-Redo.png" Text="Redo" Click="btnRedo_Click" />
            <shell:ApplicationBarIconButton x:Name="btnMicrophone" IconUri="/Assets/Images/Icons/turn-microphone-on.png" Text="Turn Mic On" Click="btnMicrophone_Click"/>
            <shell:ApplicationBarIconButton x:Name="btnSelection" IconUri="/Assets/Images/Icons/Text-Normal.png" Text="Select" Click="btnSelection_Click"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem x:Name="menuitemAttachPhoto" Text="Attach Photo" Click="menuitemAttachPhoto_Click"/>
                <shell:ApplicationBarMenuItem x:Name="menuitemViewAttachments" Text="View Attachments" Click="menuitemViewAttachments_Click" />
                <shell:ApplicationBarMenuItem x:Name="menuitemHelp" Text="Help"/>
                <shell:ApplicationBarMenuItem x:Name="menuitemTest" Text="Test" Click="menuitemTest_Click"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>
</phone:PhoneApplicationPage


text:
Q: Lucene Query to find tokens with given distance I have indexed the file content as a string in Luence (4.9), Following are some example data which were indexed in Lucene.
Info Object
{
  String ID;
  String infoData;
}

ID infoData
1 Distance so far travelled 10KM
2 Distance travelled 5Miles
3 distance covered 100 Meter
 doc.add(new TextField("id", info.getID(), Field.Store.YES));
 doc.add(new TextField("pdata", infoData.toString().replaceAll("(?m)^\\s", ""), Field.Store.NO));
 writer.addDocument(doc);

I am trying to search the following terms and expecting the output first record but I am not getting anything:
Term query - Distance KM
Expected output - ID = 1

 SpanNearQuery query = new SpanNearQuery(new SpanQuery[] { new SpanTermQuery(new Term("pdata", "Distance")),
            new SpanTermQuery(new Term("pdata", "KM")) }, 3, true);
    TopDocs hits = searcher.search(query, 20);
    ScoreDoc[] scoreDocs = hits.scoreDocs;
    System.out.println("Results  :" + hits.totalHits);
    for (ScoreDoc match : scoreDocs)
    {

        Document doc = searcher.doc(match.doc);
        System.out.println(doc.get("id"));

    }

Is there something I am missing?


text:
Q: Why does iOs Safari show full size of background-image? I'm working on a site where you have some boxes with background-images as thumbnails. I have to use background-image because the CMS we are working on is pretty old-dated and the client won't change (mon€y is the main-problem).
i figured out a strange behavior in the iOs Safari on the iPad2 & iPhone5 (latest iOS) and don't know why.
Here's my code:

a img,
.thumb,
figcaption,
a:hover .thumb {
  -webkit-transition: all .3s;
  -moz-transition: all .3s;
  -ms-transition: all .3s;
  -o-transition: all .3s;
  transition: all .3s;
}
.thumb {
  height: 250px;
  margin-bottom: 28px;
  overflow: hidden;
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
}
figcaption {
  background-color: #b61910;
  background-color: rgba(182, 25, 16, .85);
  position: absolute;
  height: 39px;
  bottom: 35px;
  color: white;
  width: calc(100% - 30px);
}
figcaption h3 {
  font-style: normal;
  position: absolute;
  bottom: 5px;
  margin-top: 0;
  margin-bottom: 0;
  padding: 10px 0 0 5px;
  transition: transform 0.3s;
  transform: translate3d(0, 0%, 0);
}
a:hover h3 {
  transform: translate3d(0, -20%, 0);
  text-shadow: 1px 1px 1px #000;
}
a:hover figcaption {
  height: 5px;
}
a:hover .thumb {
  background-size: 120% 120%;
  opacity: .8
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />

Product-Title

On my Desktop it shows the whole image but on iOS it looks like it shows the original size inside the thumbnail-box.
How can i solve this problem?
Any help would be great :)
Thanks
moesphemie

A: Maybe? https://css-tricks.com/forums/topic/full-page-backgrounds-on-ios-background-size-cover/
Code:
  background: url(images/bg.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;


text:
Q: Perl - How to remove new lines stored in perl hash? Currently I am stuck with this problem when i use datadumper to print my perl hash which I imported from a spreadsheet, some of the hash print into multiple lines with carriage return symbol(^M) as source cell had new line in it. I have managed to remove the carriage symbol, but those new lines still persists. I have tried doing this to my string, it only manages to remove carriage return symbol ^M, but new lines still exist.
$title = $sheet->{Cells}[0][$col]{Val};
$num = $sheet->{Cells}[$row+1][$col]{Val};

$title =~ s/\r//g;
$num =~ s/\r//g;
$title2 = chomp($title);
$num2 = chomp($num);

The output i get when i print is this
$VAR1 = {
          '' => {
                  'JOHN
has a car' => {
                             'SUV' => A red coloured
2022 suv from
japan

I expect to get
$VAR1 = {
          '' => {
                  'JOHN' => {
                             'SUV' => A red coloured 2022 suv from japan

A: You could use \R instead of \r, that should handle any likely combination of carriage return and newline.  It was released in Perl 5.10:

\R matches a generic newline; that is, anything considered a linebreak sequence by Unicode. This includes all characters matched by \v (vertical whitespace), and the multi character sequence "\x0D\x0A" (carriage return followed by a line feed, sometimes called the network newline; it's the end of line sequence used in Microsoft text files opened in binary mode). \R is equivalent to (?>\x0D\x0A|\v).


text:
Q: What is the form of the roots for a cubic equation of only the cubic variable? For a quadratic equation $y^2=x+b$ we can say that the solutions for $y$ are
$$y_1=\sqrt{x+b}$$
$$y_2=-\sqrt{x+b}$$
For any cubic equation $y^3=x+b$, what is the form of its roots is going to be?

A: Nominally…
$$y=\sqrt[3]{x+b}$$
But there is a caveat. There are three solutions; one is as above, over the reals, but the other two are complex. Let $\omega$ satisfy $\omega^3=1$ but $\omega\ne1$ (thus $\omega=-\frac12\pm\frac{\sqrt3}2i$). Then all the solutions for $y$ are
$$\sqrt[3]{x+b},\ \omega\sqrt[3]{x+b},\ \omega^2\sqrt[3]{x+b}$$
where the cube root is taken to be real, as presented above.