text:
Q: How to get foreground running app in Android by BroadcastReceiver I am using scheduleAtFixedRate in my Service to get foreground running app in every 2 second
Timer timer  =  new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {

        public void run()
        {

            chatHead.post(new Runnable() {
                public void run() {
                    List<ActivityManager.RunningTaskInfo> procInfos = activityManager.getRunningTasks(1);

                    if (procInfos.get(0).topActivity.getPackageName().equals("com.xyz")) {

                        chatHead.setVisibility(ImageButton.VISIBLE);

                    } else {
                        chatHead.setVisibility(ImageButton.GONE);

                    }
                }
            });

        }
    }, 2000, 3000);

This is taking too much CPU and I am getting warnings by clear master app. I also dont want to use timer here... is there any way I can get running app by BroadcastReiver or any simple way?

A:
I want to put a floating icon over calculator.. whenever calculator is my top app.. my floating icon should be visible

Then make your top app notify your floating calculator (i.e. by sending Intent) so it knows to show up.

A: Use Alarm Concept instead
void setalarm()
{
    AlarmManager am = (AlarmManager) getApplicationContext()
            .getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(getApplicationContext(), ServiceSync.class);
    i.putExtra("ping", true);
    PendingIntent pI = PendingIntent.getService(this, 666, i,
            PendingIntent.FLAG_UPDATE_CURRENT);
    try {
        am.cancel(pI);
    } catch (Exception e) {
    }
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 2000,
            pI);
}


text:
Q: Is there a way of calling a trait method on enum variants that have a field that implements the trait? My enum has 40ish variants with about half of them implementing the trait, but here is a simpler example:
trait CheeseBoard {
    fn say_cheese(self);
}

struct Cheese {
    name: String,
}

impl CheeseBoard for Cheese {
    fn say_cheese(self) {
        println!("I am {}", self.name);
    }
}

struct Person {
    name: String,
}

impl CheeseBoard for Person {
    fn say_cheese(self) {
        println!("{} says cheese!", self.name);
    }
}

enum CheesyPerson {
    Cheese(Cheese),
    Person(Person),
    UncheesyNonperson,
}

fn main() {
    let _a = [
        CheesyPerson::Cheese(Cheese {
            name: "Gouda".into(),
        }),
        CheesyPerson::Person(Person {
            name: "Peer".into(),
        }),
        CheesyPerson::UncheesyNonperson,
    ];
    todo!("Call say_cheese on items in _a where the enum variant has exactly one field that implements the CheeseBoard trait.")
}

A: This isn't directly possible in Rust; it has no mechanism to even match on "any enum possibility that has a single value," let alone that implements a particular trait.
The cleanest way I can think of to implement this is with a helper method that gives back a Option<&dyn CheeseBoard>:
impl CheesyPerson {
    fn get_cheese_board(&self) -> Option<&dyn CheeseBoard> {
        match self {
            Self::Cheese(v) => Some(v),
            Self::Person(v) => Some(v),
            _ => None,
        }
    }
}

Now you can do something like this:
for v in _a.iter().filter_map(|v| v.get_cheese_board()) {
    v.say_cheese();
}

Note this requires changing your CheeseBoard::say_cheese method because right now it takes self by value, consuming the CheeseBoard in the process.  The method needs to take self by reference.
trait CheeseBoard {
    fn say_cheese(&self);
    //            ^
    // Add this to take self by reference
}

(Playground)

A: Thank @cdhowie, your comment saves me from another hours of torment!
In case anyone wraps the enum with another layer of struct, ensure that you borrow the enum, not copy it. For example,
struct RoomForOne(CheesyPerson);

impl RoomForOne {
    fn get_cheese_board(&self) -> Option<&dyn CheeseBoard> {
        match &self.0 { // & here is important!
            CheesyPerson::Cheese(v) => Some(v),
            CheesyPerson::Person(v) => Some(v),
            _ => None,
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tailwind: div is expanding when it has to many children I'm new to Tailwind and I don't know why my div is expanding when it should just get the remaining width from the row. If I put too many children inside the div, the whole page expands.

<!doctype html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

            Button

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

I want the page to look like this:
Result I want to achieve
The upper right part of the page should only add a scroll bar if too many items have been added, instead of expanding the page.
Thank you for your help!

A: I have added min-w-0 and overflow-auto to your code to fix the issue.

<!doctype html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

            Button

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item

                item


text:
Q: I am trying to send emails through gmail host by using google oauth 2.0, where to use the access code instead of user password to send emails I am trying to send emails through gmail host by using google oauth 2.0, I am confused where to use the access code instead of user password to send emails,
this code is used to open up the consent screen and ask for permissions,
    Dim Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" & googleplus_redirect_url & "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile%20https://mail.google.com/%20https://www.googleapis.com/auth/gmail.send&client_id=" + googleplus_client_id
    Session("loginWith") = "google"
    Response.Redirect(Googleurl)

after getting permissions, this is how I obtained access code,
                If url <> "" Then
                    Dim queryString As String = url.ToString()
                    Dim delimiterChars As Char() = {"="c}
                    Dim words As String() = queryString.Split(delimiterChars)
                    Dim code As String = words(1)

                    If code IsNot Nothing Then
                        Dim webRequest As HttpWebRequest = CType(webRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
                        webRequest.Method = "POST"
                        Parameters = "code=" & code & "&client_id=" & googleplus_client_id & "&client_secret=" + googleplus_client_secret & "&redirect_uri=" + googleplus_redirect_url & "&grant_type=authorization_code"
                        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(Parameters)
                        webRequest.ContentType = "application/x-www-form-urlencoded"
                        webRequest.ContentLength = byteArray.Length
                        Dim postStream As Stream = webRequest.GetRequestStream()
                        postStream.Write(byteArray, 0, byteArray.Length)
                        postStream.Close()
                        Dim response As WebResponse = webRequest.GetResponse()
                        postStream = response.GetResponseStream()
                        Dim reader As StreamReader = New StreamReader(postStream)
                        Dim responseFromServer As String = reader.ReadToEnd()
                        Dim serStatus As GooglePlusAccessToken = JsonConvert.DeserializeObject(Of GooglePlusAccessToken)(responseFromServer)
                        If serStatus IsNot Nothing Then
                            Dim accessToken As String = String.Empty
                            accessToken = serStatus.access_token

                            If Not String.IsNullOrEmpty(accessToken) Then
                                getgoogleplususerdataSer(accessToken)
                            End If
                        End If
                    End If
                End If

and using the below code to send emails:
                        mm.Subject = LetterSubject.Text
                        Dim body As String
                        body = LetterBody.Text
                            mm.Body = body
                        Dim smtp As New Mail.SmtpClient()
                        smtp.Host = "smtp.gmail.com"
                        smtp.EnableSsl = True
                        smtp.Port = 587
                        smtp.UseDefaultCredentials = False
                        Dim service = New GmailService(New BaseClientService.Initializer With {.HttpClientInitializer = cred})
                        Dim NetworkCred As New NetworkCredential(SenderEmailAddress.Text, SenderPassword.Text)
                        smtp.Credentials = NetworkCred
                        smtp.Send(mm)

Can someone please help me how to use token here to send emails without using the user gmail password?

A: Imports System
Imports System.Threading.Tasks
Imports Google.Apis.Discovery.v1
Imports Google.Apis.Discovery.v1.Data
Imports Google.Apis.Services

    Class Program
        <STAThread>
        Private Shared Sub Main(ByVal args As String())
            Console.WriteLine("Discovery API Sample")
            Console.WriteLine("====================")

            Try
                New Program().Run().Wait()
            Catch ex As AggregateException

                For Each e In ex.InnerExceptions
                    Console.WriteLine("ERROR: " & e.Message)
                Next
            End Try

            Console.WriteLine("Press any key to continue...")
            Console.ReadKey()
        End Sub

        Private Async Function Run() As Task
            Dim service = New DiscoveryService(New BaseClientService.Initializer With {
                .ApplicationName = "Discovery Sample",
                .ApiKey = "[YOUR_API_KEY_HERE]"
            })
            Console.WriteLine("Executing a list request...")
            Dim result = Await service.Apis.List().ExecuteAsync()

            If result.Items IsNot Nothing Then

                For Each api As DirectoryList.ItemsData In result.Items
                    Console.WriteLine(api.Id & " - " + api.Title)
                Next
            End If
        End Function
    End Class
     ''Your Authentication key should be static
''Dim NetworkUserName As String= "apikey"
       ' Dim YOUR_API_KEY_HERE As String = "SG.EEyBZDVAS622C6Rt7yu1sw.jwRdfkjJddfsJfgfsyuJuyuHutytr876RuQsffhghdf1d"


text:
Q: Difference in return order? In Javascript is there a difference between:
return setTimeout(this._onTimeout, 1000*secs);

and
setTimeout(this._onTimeout, 1000*secs);
return;

The former does not always run the timeout, but the latter always does. So it feels like there is a difference, but my google-fu is failing to find the reason.

A: > return setTimeout(this._onTimeout, 1000*secs);

and

> setTimeout(this._onTimeout, 1000*secs); return;

The former does not always run the timeout, but the latter always does

You have that backwards. If the code executes correctly, the first will always return a reference to the setTimeout that can be used to cancel it. The second will always return undefined. Any other behaviour is not confomrant with ECMA–262.
If you are getting some other behaviour, there are errors in the code or what you have posted isn't what is being run.

A: If it were being used like this:
var obj = {
  set1 : function(secs) {
    return setTimeout(this._onTimeout, 1000*secs);
  },
  set2 : function(secs) {
    setTimeout(this._onTimeout, 1000*secs);
    return;
  },
  _onTimeout : function() {
     alert("worked");
  }
};
clearTimeout(obj.set1(1));
clearTimeout(obj.set2(1));

Only the second line would cause _onTimeout to actually fire.

A: There is absolutely no difference.
Try to run this code:
(function() {
    return setTimeout(function(){console.log(1)}, 500);
})();
(function() {
    setTimeout(function(){console.log(2)}, 500);
    return;
})();

return doesn't affect on setTimeout call in JS interpreter.


text:
Q: Symantec Class 3 G4 intermediate certificate missing from ca-certificates/ca-certificates-java I hope that you can help.
I did a search and didn't find this exact issue.
A vendor of ours recently updated their SSL certificate using a Symantec intermediate certificate.  Our java process was no longer able to access the site due to PKIX path being invalid.
I ensured both packages were up to date, but this certificate is not present.
I was able to update our local certificate root store manually, but would like to see if this can be updated in the apt-repo.
Thanks for your help.
Bill Campbell

A: Ubuntu does not have the Symantec CA certificates in /usr/share/ca-certificates/mozilla/ direcotry. So, one thing what we can do is we can export the Symantec CA certificate from mozilla, since Mozilla and Chrome has Symantec CA certificates by default and you can put it under the directory /usr/share/ca-certificates/mozilla/ with crt extension and update the path in /etc/ca-certificates.conf the run the command
sudo update-ca-certificates

Then you should be able to access the website which is using the certificate signed by Symantec. Let me know if you need more on export CA from mozilla and import to ubunut ssl directory.


text:
Q: CSS Animating an element while hvoering something else I've found plenty of answers to this question, but none of them have worked for my case. I can't help but feel I'm missing something basic.
HTML

  TEST Home
  About
  Something else

CSS
nav {
    display: flex;
    margin: auto;
    /* margin-top: 30px; */
    padding: 12px 0;
    position: relative;
    max-width: 800px;
    height: 50px;
    background-color: purple;
    border-radius: 0;
}
nav a {
    height: 100%;
    font-size: 15px;
    display: inline-block;
    position: relative;
    z-index: 1;
    text-decoration: none;
    text-transform: uppercase;
    text-align: center;
    color: white;
    cursor: pointer;
}
nav .animation {
    position: absolute;
    height: 100%;
    top: 0;
    z-index: 0;
    transition: all 0.5s ease 0s;
}

nav i {
    /* position: absolute; */
    height: 100%;
    top: 0;
    z-index: 0;
    transition: all 0.5s ease 0s;
    color: black;
}

a:nth-child(1) {
    width: 100px;
}
a:nth-child(2) {
    width: 150px;
}
a:nth-child(3) {
    width: 150px;
}

/* somehow invert this color when the nav a element is hovered */
.fa-home {
    color: green;
}
.fa-home:hover {
    color: white;
}
/* I expected this to work, but it doesn't */
nav a:nth-child(1):hover ~ .fa-home {
    background-color: white;
}
nav a:nth-child(1):hover ~ .animation {
    width: 100px;
    left: 0;
    background-color: green;
}
nav a:nth-child(2):hover ~ .animation {
    width: 150px;
    left: 100px;
    background-color: #d3b814;
}
nav a:nth-child(3):hover ~ .animation {
    width: 150px;
    left: 250px;
    background: rgb(249, 11, 70);
}

What I want is for the green TEST text, left of Home, to change colour when hovering the link.
I've used the ~ modifier to move the background colour around - but I can't get it to work with the I tag (which is a font-awesome icon, but couldn't get codepen to import it properly).
I'm currently able to turn it white while hovering the I tag, but not the link itself.
Finally, here's the original navbar code for those interested.

A: The selector is wrong
Change
nav a:nth-child(1):hover ~ .fa-home {
    background-color: white;
}

To this:
nav a:nth-child(1):hover > .fa-home {
    color: white;
}


text:
Q: On change select box option event is slow Am having a drop-down with the class name user_status.
On the change event of this seletion, there is a dialog popup is coming.
Here is the code.
$('.user_status').change(function(){
    $('#dialog-confirm').dialog({
        title     : 'Change Status',
        resizable : false,
        width     : 250,
        height    : 120,
        modal     : true,
        buttons   : {
            'Yes': function() {
                dialog_obj.dialog('close');
            },
            'No': function() {
                $(this).dialog('close');
            }
        }
    });
});

My problem is Its very slow(may take 3 or 4 seconds) to come this popup on the change event. How Can I fast this popup on change event?

A: define your dialog before and just open the jquery dialog on event like this (untested code):
var jDialog =  $('#dialog-confirm').dialog({
        title     : 'Change Status',
        resizable : false,
        width     : 250,
        height    : 120,
        modal     : true,
        autoOpen  : false,
        buttons   : {
            'Yes': function() {
                dialog_obj.dialog('close');
            },
            'No': function() {
                $(this).dialog('close');
            }
        }
    });
$('.user_status').change(function(){
   jDialog.dialog('open');
});


text:
Q: Can you give some advise about 3D simulation engine (choose best one but how?) in winforms 3d and wpf 3d? Can you give some advise winforms 3d and wpf 3d?
Question:
i try to write a simulation program 3D in windows forms i have some knowledge about
CsGL (OpenGl wrapper)
DirectX
OPenTk

Also
SlimDx
OgreDotNet

WPF :
Balder

i have 2 question:
1) do you give some advise about above engines to create some simulation. Or any other best engine or wrapper class
2) Can i use Balder in  Windows Forms?

A: If you need only visualization, I can recommend you opensource visualization library VTK
But if you also need geometry computing (meshing, intersection and so on), I can advice another open source library OpenCascade
As example of using both of it, go to SALOME project. The last one also can be used as a platform of simulating application, but it's based on Qt library.


text:
Q: Hide file from tacking area in Git I cannot hide special files from git status command
For example, I don't want to have phpstorm.php in my project and I added it to gitignore
But when I use git status command, That shows the message as follow:
Untracked files:
(use "git add ..." to include in what will be committed)
phpstorm.php
Actually, I want to have phpstorm.php but hide from git status
Thanks

A: Add /phpstorm.php or phpstorm.php as a line in your .gitignore file.
/phpstorm.php matches the phpstorm.php file of the same folder with .gitignore.
phpstorm.php matches all that files, e.g. including someFolder/phpstorm.php.
See gitignore Documentation for more information.


text:
Q: Regulated Power Supply I am supposed to simulate this circuit (regulated power supply 5V), however I am not understanding what's the point of the resistor R. Is it a load resistor? Cause i thought these needed to be before the regulator.

A: If you look at a typical 7805 datasheet  you'll find a statement like
Note: Minimum load current for regulation is 5 mA
If the circuit is expected to maintain a 5V output with a load going right down to zero, the resistor R ensures that enough current is drawn from the 7805 to guarantee that the 5mA minimum is met. In this case a 1000 Ohm resistor would be needed.
It's often not seen in the real world because the 7805 will normally be built into a circuit that will always take at least the minimum load.

A: As you adjust \$R\$ in your simulation, you should be able to see the input voltage (across \$C\$) go up or down, but the voltage across \$R\$ should remain relatively constant.


text:
Q: TypeScript Compiler API - How to get usages of function args I need to find all the properties that are used from function's argument, i.e. i have a function
function test(arg) {
    console.log(arg.a);

    if (arg.b.c) {
        console.log(arg.d);
    }

    console.log(arg.e)
}

and i need to get so to say tree of the properties that have been used
{
    a: {
        b: {
            c
        }
        d,
        e
    }
}

maybe there are some similar tools that can do something like this, or maybe there are some info about compiler API that could provide such information.
Thanks.


text:
Q: Ajax Reading from a Database Dynamically I'm developing a website/database solution which gives the administrator the option to sign into the webpage and perform actions on the database.
Currently they can add/delete/run pre-defined queries, however to 'edit' records in a table, I would like them to specify the primary key (ID) and then have ajax read in the values associated with that record and allow them to be changed.
What's the best way to go about this? Any pointers would be great!

A: Firstly, you'll probably want to use a Javascript framework such as jQuery which takes care of a lot of the heavy lifting for you.
The main API methods you'll be concerned with are

*

*serialize to convert your form data into a string to be passed to your PHP script

*Ajax to perform the Ajax call (passing in details of the data you're changing)


text:
Q: Show discontinuous points of increasing function on $[0,1]$ is $F_\sigma$set Problem: Let $f$ be an increasing function on $[0,1]$, Show discontinuous points of $f$ on $[0,1]$ is $F_\sigma$ set. But it is not always a $G_\delta$ set.
My thoughts: It is easy to prove that there exist a injective mapping from $A=\{x\in[0,1]|f\text{ is discontinuous at } x\}$ to $\mathbb{Q}$. So $A$ is most a countable set. Since $\mathbb{Q}$ is $F_\sigma$ set, so is subset(Is it right?). And similarly, since $\mathbb{Q}$ is not a $G_\delta$set, so the subset.

A: Yes, it's true that the set of discontinuities of $f$ is countable. And every countable subset of $\mathbb R$ is clearly an $F_\sigma.$ So we have the first claim.
The second claim is false. For a counterexample, take an $f$ with just one discontinuity. Now just note that a one point set is a $G_\delta.$


text:
Q: Recoding a character variable that is a sentence with a ? on the end I am trying to recode character variables that have spaces in them and one has a ? on the end to something simpler.
I want to recode the variables: Income group, WBL INDEX, Is there legislation specifically addressing domestic violence?
Ive tried this:
plyr::mapvalues(WB_data, from = c("Income group","WBL INDEX", "Is there legislation specifically addressing domestic violence?"), to = c("Income_group", "WBI_index", "DVL"))
and I get this error code:
Error in plyr::mapvalues(WB_data, from = c("Income group", "WBL INDEX", : x must be an atomic vector.
What does this mean and how do I solve this?


text:
Q: Cassandra split brain partition We are running a 6-node cassandra cluster across two AWS availability zones (ap-southeast-1 and ap-southeast-2).
After running happily for several months, the cluster was given a rolling restart to fix a hung repair, and now each group thinks the other is down.
Cluster Information:
    Name: MegaportGlobal
    Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch
    Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
    Schema versions:
        220727fa-88d2-366f-9473-777e32744c37: [10.5.13.117, 10.5.12.245, 10.5.13.93]

        UNREACHABLE: [10.4.0.112, 10.4.0.169, 10.4.2.186]

Cluster Information:
    Name: MegaportGlobal
    Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch
    Partitioner: org.apache.cassandra.dht.Murmur3Partitioner
    Schema versions:
        3932d237-b907-3ef8-95bc-4276dc7f32e6: [10.4.0.112, 10.4.0.169, 10.4.2.186]

        UNREACHABLE: [10.5.13.117, 10.5.12.245, 10.5.13.93]

From Sydney, 'nodetool status' reports that most Singapore nodes are down:
Datacenter: ap-southeast-2
==========================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address      Load       Tokens  Owns    Host ID                               Rack
UN  10.4.0.112   9.04 GB    256     ?       b9c19de4-4939-4112-bf07-d136d8a57b57  2a
UN  10.4.0.169   9.34 GB    256     ?       2d7c3ac4-ae94-43d6-9afe-7d421c06b951  2a
UN  10.4.2.186   10.72 GB   256     ?       4dc8b155-8f9a-4532-86ec-d958ac207f40  2b
Datacenter: ap-southeast-1
==========================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address      Load       Tokens  Owns    Host ID                               Rack
UN  10.5.13.117  9.45 GB    256     ?       324ee189-3e72-465f-987f-cbc9f7bf740b  1a
DN  10.5.12.245  10.25 GB   256     ?       bee281c9-715b-4134-a033-00479a390f1e  1b
DN  10.5.13.93   12.29 GB   256     ?       a8262244-91bb-458f-9603-f8c8fe455924  1a

But from Singapore, all Sydney nodes are reported as down:
ap-southeast-2
==========================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address      Load       Tokens  Owns    Host ID                               Rack
DN  10.4.0.112   8.91 GB    256     ?       b9c19de4-4939-4112-bf07-d136d8a57b57  2a
DN  10.4.0.169   ?          256     ?       2d7c3ac4-ae94-43d6-9afe-7d421c06b951  2a
DN  10.4.2.186   ?          256     ?       4dc8b155-8f9a-4532-86ec-d958ac207f40  2b
Datacenter: ap-southeast-1
==========================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address      Load       Tokens  Owns    Host ID                               Rack
UN  10.5.13.117  9.45 GB    256     ?       324ee189-3e72-465f-987f-cbc9f7bf740b  1a
UN  10.5.12.245  10.25 GB   256     ?       bee281c9-715b-4134-a033-00479a390f1e  1b
UN  10.5.13.93   12.29 GB   256     ?       a8262244-91bb-458f-9603-f8c8fe455924  1a

Even more confusing, 'nodetool gossipinfo' executed in Sydney reports that everything is fine with Status - Normal:
/10.5.13.117
  generation:1440735653
  heartbeat:724504
  SEVERITY:0.0
  DC:ap-southeast-1
  LOAD:1.0149565738E10
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RACK:1a
  STATUS:NORMAL,-1059943672916788858
  RELEASE_VERSION:2.1.6
  NET_VERSION:8
  RPC_ADDRESS:10.5.13.117
  INTERNAL_IP:10.5.13.117
  HOST_ID:324ee189-3e72-465f-987f-cbc9f7bf740b
/10.5.12.245
  generation:1440734497
  heartbeat:728014
  SEVERITY:0.0
  DC:ap-southeast-1
  LOAD:1.100647505E10
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RACK:1b
  STATUS:NORMAL,-1029869455226513030
  RELEASE_VERSION:2.1.6
  NET_VERSION:8
  RPC_ADDRESS:10.5.12.245
  INTERNAL_IP:10.5.12.245
  HOST_ID:bee281c9-715b-4134-a033-00479a390f1e
/10.4.0.112
  generation:1440973751
  heartbeat:4135
  SEVERITY:0.0
  DC:ap-southeast-2
  LOAD:9.70297176E9
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RACK:2a
  RELEASE_VERSION:2.1.6
  STATUS:NORMAL,-1016623069114845926
  NET_VERSION:8
  RPC_ADDRESS:10.4.0.112
  INTERNAL_IP:10.4.0.112
  HOST_ID:b9c19de4-4939-4112-bf07-d136d8a57b57
/10.5.13.93
  generation:1440734532
  heartbeat:727909
  SEVERITY:0.0
  DC:ap-southeast-1
  LOAD:1.3197536002E10
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RACK:1a
  STATUS:NORMAL,-1021689296016263011
  RELEASE_VERSION:2.1.6
  NET_VERSION:8
  RPC_ADDRESS:10.5.13.93
  INTERNAL_IP:10.5.13.93
  HOST_ID:a8262244-91bb-458f-9603-f8c8fe455924
/10.4.0.169
  generation:1440974511
  heartbeat:1832
  SEVERITY:0.0
  DC:ap-southeast-2
  LOAD:1.0023502338E10
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RACK:2a
  RELEASE_VERSION:2.1.6
  STATUS:NORMAL,-1004223692762353764
  NET_VERSION:8
  RPC_ADDRESS:10.4.0.169
  INTERNAL_IP:10.4.0.169
  HOST_ID:2d7c3ac4-ae94-43d6-9afe-7d421c06b951
/10.4.2.186
  generation:1440734382
  heartbeat:730171
  SEVERITY:0.0
  DC:ap-southeast-2
  LOAD:1.1507595081E10
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RACK:2b
  STATUS:NORMAL,-10099894685483463
  RELEASE_VERSION:2.1.6
  NET_VERSION:8
  RPC_ADDRESS:10.4.2.186
  INTERNAL_IP:10.4.2.186
  HOST_ID:4dc8b155-8f9a-4532-86ec-d958ac207f40

The same command executed in Singapore does not include a STATUS for any nodes in Sydney:
/10.5.12.245
  generation:1440974710
  heartbeat:1372
  SEVERITY:0.0
  LOAD:1.100835806E10
  RPC_ADDRESS:10.5.12.245
  NET_VERSION:8
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RELEASE_VERSION:2.1.6
  STATUS:NORMAL,-1029869455226513030
  DC:ap-southeast-1
  RACK:1b
  INTERNAL_IP:10.5.12.245
  HOST_ID:bee281c9-715b-4134-a033-00479a390f1e
/10.5.13.117
  generation:1440974648
  heartbeat:1561
  SEVERITY:0.0
  LOAD:1.0149992022E10
  RPC_ADDRESS:10.5.13.117
  NET_VERSION:8
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RELEASE_VERSION:2.1.6
  STATUS:NORMAL,-1059943672916788858
  DC:ap-southeast-1
  RACK:1a
  HOST_ID:324ee189-3e72-465f-987f-cbc9f7bf740b
  INTERNAL_IP:10.5.13.117
/10.4.0.112
  generation:1440735420
  heartbeat:23
  SEVERITY:0.0
  LOAD:9.570546197E9
  RPC_ADDRESS:10.4.0.112
  NET_VERSION:8
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RELEASE_VERSION:2.1.6
  DC:ap-southeast-2
  RACK:2a
  INTERNAL_IP:10.4.0.112
  HOST_ID:b9c19de4-4939-4112-bf07-d136d8a57b57
/10.5.13.93
  generation:1440734532
  heartbeat:729862
  SEVERITY:0.0
  LOAD:1.3197536002E10
  RPC_ADDRESS:10.5.13.93
  NET_VERSION:8
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RELEASE_VERSION:2.1.6
  STATUS:NORMAL,-1021689296016263011
  DC:ap-southeast-1
  RACK:1a
  INTERNAL_IP:10.5.13.93
  HOST_ID:a8262244-91bb-458f-9603-f8c8fe455924
/10.4.0.169
  generation:1440974511
  heartbeat:15
  SEVERITY:0.5076141953468323
  RPC_ADDRESS:10.4.0.169
  NET_VERSION:8
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RELEASE_VERSION:2.1.6
  DC:ap-southeast-2
  RACK:2a
  INTERNAL_IP:10.4.0.169
  HOST_ID:2d7c3ac4-ae94-43d6-9afe-7d421c06b951
/10.4.2.186
  generation:1440734382
  heartbeat:15
  SEVERITY:0.0
  RPC_ADDRESS:10.4.2.186
  NET_VERSION:8
  SCHEMA:7bf335ee-61ae-36c6-a902-c70d785ec7a3
  RELEASE_VERSION:2.1.6
  DC:ap-southeast-2
  RACK:2b
  INTERNAL_IP:10.4.2.186
  HOST_ID:4dc8b155-8f9a-4532-86ec-d958ac207f40

During restart, each node can see the remote DC for a little while:
INFO  [GossipStage:1] 2015-08-31 10:53:07,638 OutboundTcpConnection.java:97 - OutboundTcpConnection using coalescing strategy DISABLED
INFO  [HANDSHAKE-/10.4.2.186] 2015-08-31 10:53:08,267 OutboundTcpConnection.java:485 - Handshaking version with /10.4.2.186
INFO  [HANDSHAKE-/10.4.0.169] 2015-08-31 10:53:08,287 OutboundTcpConnection.java:485 - Handshaking version with /10.4.0.169
INFO  [HANDSHAKE-/10.5.12.245] 2015-08-31 10:53:08,391 OutboundTcpConnection.java:485 - Handshaking version with /10.5.12.245
INFO  [HANDSHAKE-/10.5.13.93] 2015-08-31 10:53:08,498 OutboundTcpConnection.java:485 - Handshaking version with /10.5.13.93
INFO  [GossipStage:1] 2015-08-31 10:53:08,537 Gossiper.java:987 - Node /10.5.12.245 has restarted, now UP
INFO  [HANDSHAKE-/10.5.13.117] 2015-08-31 10:53:08,537 OutboundTcpConnection.java:485 - Handshaking version with /10.5.13.117
INFO  [GossipStage:1] 2015-08-31 10:53:08,656 StorageService.java:1642 - Node /10.5.12.245 state jump to normal
INFO  [GossipStage:1] 2015-08-31 10:53:08,820 Gossiper.java:987 - Node /10.5.13.117 has restarted, now UP
INFO  [GossipStage:1] 2015-08-31 10:53:08,852 Gossiper.java:987 - Node /10.5.13.93 has restarted, now UP
INFO  [SharedPool-Worker-33] 2015-08-31 10:53:08,907 Gossiper.java:954 - InetAddress /10.5.12.245 is now UP
INFO  [GossipStage:1] 2015-08-31 10:53:08,947 StorageService.java:1642 - Node /10.5.13.93 state jump to normal
INFO  [GossipStage:1] 2015-08-31 10:53:09,007 Gossiper.java:987 - Node /10.4.0.169 has restarted, now UP
WARN  [GossipTasks:1] 2015-08-31 10:53:09,123 FailureDetector.java:251 - Not marking nodes down due to local pause of 7948322997 > 5000000000
INFO  [GossipStage:1] 2015-08-31 10:53:09,192 StorageService.java:1642 - Node /10.4.0.169 state jump to normal
INFO  [HANDSHAKE-/10.5.12.245] 2015-08-31 10:53:09,199 OutboundTcpConnection.java:485 - Handshaking version with /10.5.12.245
INFO  [GossipStage:1] 2015-08-31 10:53:09,203 Gossiper.java:987 - Node /10.4.2.186 has restarted, now UP
INFO  [GossipStage:1] 2015-08-31 10:53:09,206 StorageService.java:1642 - Node /10.4.2.186 state jump to normal
INFO  [SharedPool-Worker-34] 2015-08-31 10:53:09,215 Gossiper.java:954 - InetAddress /10.5.13.93 is now UP
INFO  [SharedPool-Worker-33] 2015-08-31 10:53:09,259 Gossiper.java:954 - InetAddress /10.5.13.117 is now UP
INFO  [SharedPool-Worker-33] 2015-08-31 10:53:09,259 Gossiper.java:954 - InetAddress /10.4.0.169 is now UP
INFO  [SharedPool-Worker-33] 2015-08-31 10:53:09,259 Gossiper.java:954 - InetAddress /10.4.2.186 is now UP
INFO  [GossipStage:1] 2015-08-31 10:53:09,296 StorageService.java:1642 - Node /10.4.0.169 state jump to normal
INFO  [GossipStage:1] 2015-08-31 10:53:09,491 StorageService.java:1642 - Node /10.5.12.245 state jump to normal
INFO  [HANDSHAKE-/10.5.13.117] 2015-08-31 10:53:09,509 OutboundTcpConnection.java:485 - Handshaking version with /10.5.13.117
INFO  [GossipStage:1] 2015-08-31 10:53:09,511 StorageService.java:1642 - Node /10.5.13.93 state jump to normal
INFO  [HANDSHAKE-/10.5.13.93] 2015-08-31 10:53:09,538 OutboundTcpConnection.java:485 - Handshaking version with /10.5.13.93

Then, without any errors, the nodes are marked as down:
INFO  [GossipTasks:1] 2015-08-31 10:53:34,410 Gossiper.java:968 - InetAddress /10.5.13.117 is now DOWN
INFO  [GossipTasks:1] 2015-08-31 10:53:34,411 Gossiper.java:968 - InetAddress /10.5.12.245 is now DOWN
INFO  [GossipTasks:1] 2015-08-31 10:53:34,411 Gossiper.java:968 - InetAddress /10.5.13.93 is now DOWN

We have tried multiple restarts, but the behaviour remains the same.
*edit
It looks to be related to the Gossip protocol... Turning on extra debug shows that the PHI values are steadily increasing:
TRACE [GossipTasks:1] 2015-08-31 16:46:44,706 FailureDetector.java:262 - PHI for /10.4.0.112 : 2.9395029255
TRACE [GossipTasks:1] 2015-08-31 16:46:45,727 FailureDetector.java:262 - PHI for /10.4.0.112 : 3.449690761
TRACE [GossipTasks:1] 2015-08-31 16:46:46,728 FailureDetector.java:262 - PHI for /10.4.0.112 : 3.95049114
TRACE [GossipTasks:1] 2015-08-31 16:46:47,730 FailureDetector.java:262 - PHI for /10.4.0.112 : 4.451317456
TRACE [GossipTasks:1] 2015-08-31 16:46:48,732 FailureDetector.java:262 - PHI for /10.4.0.112 : 4.952114357
TRACE [GossipTasks:1] 2015-08-31 16:46:49,733 FailureDetector.java:262 - PHI for /10.4.0.112 : 5.4529339645
TRACE [GossipTasks:1] 2015-08-31 16:46:50,735 FailureDetector.java:262 - PHI for /10.4.0.112 : 5.953951289
TRACE [GossipTasks:1] 2015-08-31 16:46:51,737 FailureDetector.java:262 - PHI for /10.4.0.112 : 6.4547808165
TRACE [GossipTasks:1] 2015-08-31 16:46:52,738 FailureDetector.java:262 - PHI for /10.4.0.112 : 6.955600038
TRACE [GossipTasks:1] 2015-08-31 16:46:53,740 FailureDetector.java:262 - PHI for /10.4.0.112 : 7.456422601
TRACE [GossipTasks:1] 2015-08-31 16:46:54,742 FailureDetector.java:262 - PHI for /10.4.0.112 : 7.957303284
TRACE [GossipTasks:1] 2015-08-31 16:46:55,751 FailureDetector.java:262 - PHI for /10.4.0.112 : 8.461658576
TRACE [GossipTasks:1] 2015-08-31 16:46:56,755 FailureDetector.java:262 - PHI for /10.4.0.112 : 8.9636610545
TRACE [GossipTasks:1] 2015-08-31 16:46:57,763 FailureDetector.java:262 - PHI for /10.4.0.112 : 9.4676926445

The PHI values steadily increase after a restart, until they exceed the failure threshold and are marked as DOWN.
Any suggestions on how to proceed?

A: For a laggy network, raise the phi failure detection threshold to 12 or 15. This is commonly required in AWS, especially cross region.

A: The problem turned out to be the network links into AWS, specifically the network MTU.  Due to a subtle problem with our routing configuration, the data path became asymmetrical between Sydney and Singapore AWS.
I guess the lesson learned is that if the modes are happy within a DC and not between DCs, then it is likely the network, and things like MTU matter, even if pings and telnet etc look OK.
Thanks to Jeff and Stefan for your input - I'll buy you a beer if you ever find yourself in Brisbane!


text:
Q: dynamic add form field in flutter I want this in flutter but I did not get add phone number when click on [+] button. When I've called Phone widget I got this error:

W/AccessibilityBridge(16228): can't invoke getChildId with reflection

below is my code:
RaisedButton(
          child: Text(
            '+',
            style: TextStyle(fontSize: 20.0),
          ),
          shape: RoundedRectangleBorder(
              side: BorderSide(
                  color: Colors.black26,width: 1.0,
                  style: BorderStyle.solid),
              borderRadius: BorderRadius.circular(10.0)),
          onPressed: () {
            Phone();
            print('add phone is pressed');
          },
          color: Colors.white,
        ),

  class Phone extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(right: 8.0),
      child: TextFormField(
        keyboardType: TextInputType.phone,
        decoration: const InputDecoration(
          contentPadding:
          EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(10.0),
            ),
            borderSide: BorderSide(color: Colors.white, width: 0.1),
          ),
          filled: true,
          icon: Icon(
            Icons.phone,
            color: Colors.black,
            size: 20.0,
          ),
          labelText: 'Phone Number',
          labelStyle: TextStyle(
              fontSize: 15.0,
              height: 1.5,
              color: Color.fromRGBO(61, 61, 61, 1)),
          fillColor: Color(0xffD2E8E6),
        ),
        maxLines: 1,
      ),
    );
  }
}

A: You are applying completely wrong logic here. You can't directly return widget in an widget onPressed() function.
example abstract of your code to add TextFormField:
class MyClass extends StatefulWidget {
  @override
  _MyClassState createState() => new _MyClassState();
}

class _MyClassState extends State<MyClass> with SingleTickerProviderStateMixin {
  List<Widget> _phoneWidgets = List<Widget>();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Text(
          '+',
          style: TextStyle(fontSize: 20.0),
        ),
        shape: RoundedRectangleBorder(
            side: BorderSide(
                color: Colors.black26, width: 1.0, style: BorderStyle.solid),
            borderRadius: BorderRadius.circular(10.0)),
        onPressed: () {
          setState(() {
            _phoneWidgets.add(Phone(
              fieldName: 'Phone Number',
            ));
          });
        },
      ),
      body: Padding(
          padding: EdgeInsets.symmetric(horizontal: 25, vertical: 30),
          child: Column(
            children: List.generate(_phoneWidgets.length, (i) {
              return _phoneWidgets[i];
            }),
          )),
    );
  }
}

class Phone extends StatelessWidget {
  String fieldName;
  Phone({this.fieldName = ''});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(right: 8.0),
      child: TextFormField(
        keyboardType: TextInputType.phone,
        decoration: InputDecoration(
          contentPadding:
              EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(10.0),
            ),
            borderSide: BorderSide(color: Colors.white, width: 0.1),
          ),
          filled: true,
          icon: Icon(
            Icons.phone,
            color: Colors.black,
            size: 20.0,
          ),
          labelText: fieldName,
          labelStyle: TextStyle(
              fontSize: 15.0,
              height: 1.5,
              color: Color.fromRGBO(61, 61, 61, 1)),
          fillColor: Color(0xffD2E8E6),
        ),
        maxLines: 1,
      ),
    );
  }
}

A: I edited the accepted answer to add getting the value in each dynamically created field. I added dynamically created textfield controllers.
class DynamicTextFieldPage extends StatefulWidget {
  const DynamicTextFieldPage({Key? key}) : super(key: key);

  @override
  _DynamicTextFieldPageState createState() => _DynamicTextFieldPageState();
}

class _DynamicTextFieldPageState extends State<DynamicTextFieldPage>
    with SingleTickerProviderStateMixin {
  final List<Phone> _phoneWidgets = <Phone>[];
  List<String> listOfTextEntries = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Dynamic Fields "),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Text(
          '+',
          style: TextStyle(fontSize: 20.0),
        ),
        shape: RoundedRectangleBorder(
            side: const BorderSide(
                color: Colors.black26, width: 1.0, style: BorderStyle.solid),
            borderRadius: BorderRadius.circular(10.0)),
        onPressed: () {
          setState(() {
            //add Phone objects dynamically here while setting up a controller in there.
            _phoneWidgets.add(Phone(
              fieldName: 'Phone Number ${_phoneWidgets.length + 1}',
              controller: returnController(
                  "phoneController ${_phoneWidgets.length + 1}"),
            ));
          });
        },
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 30),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ListView(
                  shrinkWrap: true,
                  children: List.generate(_phoneWidgets.length, (i) {
                    return _phoneWidgets[i];
                  }),
                ),
                Center(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: ElevatedButton(
                      style: MyButtonStyles(width: 120, height: 38)
                          .myElevatedButtonStyle(),
                      child: const Text('Submit'),
                      onPressed: () {
                        showTextFieldEntries();
                      },
                    ),
                  ),
                ),
              ]),
        ),
      ),
    );
  }

  TextEditingController returnController(String controllerName) {
    final controllerName = TextEditingController();
    return controllerName;
  }

  //You can see the list of text entries from here.
  void showTextFieldEntries() {
    //listOfTextEntries = _phoneWidgets.map((i)=>i.controller.text.trim()).toList();
    _phoneWidgets.map((i) {
      //i.controller.text.trim();
      print("these are the listOfTextEntries ${i.controller.text.trim()}");
    }).toList();

    //print("these are ${listOfTextEntries[0]}");
  }
}

class Phone extends StatelessWidget {
  final String fieldName;
  final TextEditingController controller;

  const Phone({Key? key, this.fieldName = '', required this.controller})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(right: 8.0, bottom: 10.0),
      child: TextFormField(
        controller: controller,
        keyboardType: TextInputType.phone,
        decoration: InputDecoration(
          contentPadding:
              const EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0),
          enabledBorder: const OutlineInputBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(10.0),
            ),
            borderSide: BorderSide(color: Colors.white, width: 0.1),
          ),
          filled: true,
          icon: const Icon(
            Icons.phone,
            color: Colors.black,
            size: 20.0,
          ),
          labelText: fieldName,
          labelStyle: const TextStyle(
              fontSize: 15.0,
              height: 1.5,
              color: Color.fromRGBO(61, 61, 61, 1)),
          fillColor: const Color(0xffD2E8E6),
        ),
        maxLines: 1,
      ),
    );
  }
}


text:
Q: .net core 2.0 does not publish nuget dll In .net core 2.0 I add some nuget package.Project work in local but does not work in server-production.I click solution and click publih to folder and move that folder to server.But in published folder there is no this nuget dll
how can I publish that nuget dll?In that folder I didnt find that dll
C:\Users\HC.nuget\packages

A: I think the problem is all of those packages are included in the ASP.NET Core Implicit Store.  These are only present however, if the SDK is present on the target machine.   If this is the case you have 3 options.

*

*Install the .NET Core SDK (not just the runtime) on the target machine.  In this case the implicit store will be present.

*Set the following property to false:

<PropertyGroup>
 <PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
</PropertyGroup>

This will cause the build to include dependencies that are in the implicit store so that the final published product only relies on the .NET Core Runtime and not the API.

*Build a self-contained deployment
This will bundle everything (runtime and implicit dependencies) into your application.


text:
Q: Fortran: Variable initialization wwith parenthesis I am trying to understand a Fortran90 code. In the code, I found this expression for initializing a variable:
integer :: time(8)
What is meant by this? What does the parenthesis do?

A: That syntax declares an INTEGER rank one array of size eight.
(In Fortran terminology that source does not initialize anything and it is a declaration, not an expression.)


text:
Q: In the PCB design, how should the a2 terminal island of a triac in the 252 sheath be? For the A2 terminal of the triac in pcb design, I want to use both the front and back surfaces of the pcb. How should the vias be between the back and front surface?(actually zone areas in surfaces)I am using kicad.
Package : TO-252
Max voltage:220Vac
Max Amps:16 A

A:
TO-252 package

The TO-252 series packages are surface-mount technology (SMT) and come in 3, 4, 5 and possibly more pins.
Page 4 of this document describes a typical footprint (literal pin size, not pad size!), where the pins are 1.5 x 2.5mm.  Yours may be different.
For any SMT device, the mating pads should be a little bigger to allow for a proper solder fillet.  So for this device, say 1.8 x 3.0mm.
Given that all pads are larger than the pins, the amount of distance separating them on the printed circuit board (PCB) decreases.  This distance (called "creepage" and "clearance") determines the safe operating voltage.

*

*Clearance distance is the shortest separation in the air between two conducting parts.

*Creepage distance is the shortest separation along the surface of an insulating material between two conducting parts.

Sometimes these are the same (as in the case of PCB traces) but the distinction can be very important.
Ok so the minimum distance between the exposed tracks/pads/pins determines the maximum operating voltage.
The IPC-2221A Generic Standard on Printed Board Design section 6.3 Electrical Clearance, is the same table as shown in KiCAD's PCB calculator, Electrical Spacing tab:

For a B2 class board (we're considering minimum distance on exposed pins/pads), 2.5mm is needed for 301-500V. This range was chosen because 240VAC (RMS) has a peak absolute voltage of 339.5V.
So, if the PCB can be designed and assembled with at least 2.5mm distance between A1, A2, and everything else near them, then it will not arc-over.
Note that contaminants on the PCB (such as water and metal dust) can reduce this and cause failure. For that reason, high-voltage tracks such as these are sometimes covered with conformal coating, to prevent such a possibility.

Max voltage:220Vac Max Amps:16 A

I'm not sure if you can find a TO-252 TRIAC capable of handling 16A. A preliminary check shows most TO-252 TRIACs stop at 8A, likely because these surface-mount components are cooled by the PCB.  And paralleling them is not a good idea, as if one fires just a nanosecond before the other, it will get a surge of current beyond it's rating and likely explode.
For instance, the LittelFuse QJxx04xx_Series are good for 8A. I did find a TN1515-600B SCR at 15A but anyways.
Your question is about trace ampacity and via ampacity. KiCAD has a trace calculator:

For 16A, a (single) trace on an external layer, 20mm long, will have to be 13.76mm wide for it to rise 10°C.
Now you could use two tracks (I think what you are trying to do), one on top and one on bottom, and almost divide this by two. I'd suggest giving them 10% more though, because the heating of one will slightly heat the other due to proximity. So traces on both sides = 6.88mm, so say 7mm.
As for via ampacity (since you have to get all that current to one side of the PCB), there are many calculators for this on the 'web such as this one.  Using that calculator, one 18mil via could handle 2.56A. Always factor in some safety margin, so say 2A.  Each 18mil via handles 2A, so 16A/2 = 8. Place 8 of these vias between the two tracks near the pin.


text:
Q: apache not serving static content correctly I have been working on my own mvc framework to further my web app learning, but am having trouble serving static resources. I am trying to have a single entry point into the application, aka a front controller, so in my project / I have an .htaccess file that redirects all requests to the app/ folder where another .htaccess passes the request uri to index.php (in app/) who delegates the request to the appropriate controllers.
However, when I try to serve up static content, such as javascripts or cascading style sheets, I still get redirected through app/index.php. I am also getting "favicon.ico does not exist in /var/www" errors in /var/log/apache2/errors.log (maybe because of symlink to ~/www?). I do not expect to because of the following .htaccess file in the root directory of my project root:
<IfModule mod_rewrite.c>
  Options -Indexes +FollowSymLinks
  RewriteEngine On

  RewriteBase /

  # ----------------------------------------------------------------------
  # Suppress the "www." at the beginning of URLs
  # ----------------------------------------------------------------------
  # The same content should never be available under two different URLs - especially not with and
  # without "www." at the beginning, since this can cause SEO problems (duplicate content).
  # That's why you should choose one of the alternatives and redirect the other one.
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

  #----------------------------------------------------------------------
  # Route static resources to respective files
  #----------------------------------------------------------------------
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond public/$0 -f
  RewriteRule ^.+\.(jpg|gif|png|ico|css|js)$ /public/$0 [L]

  #----------------------------------------------------------------------
  # Redirect all other requests to the app folder
  #----------------------------------------------------------------------
  RewriteRule   ^$    app/   [L]
  RewriteRule   (.*)  app/$1 [L]
</IfModule>

and here is the .htaccess in my app/ folder:
<IfModule mod_rewrite.c>
  RewriteEngine On

  # ensure request is not path to filename or directory
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d

  # redirect all requests to index.php?url=PATHNAME
  RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

Why can't I serve static content correctly? This would make sense to me if I wasn't trying to sent all static requests to public/, which is where my css, jpg, png, js, etc files reside. But I have a RewriteCond rule in there to send the requests for such files to the public dir... Confusing?

A: Assuming, from what I understood, that your project structure is the following:

/
/.htaccess
/app/.htaccess
/app/index.php
/public/static.js (for example)

Here is what I come up with, hoping it'll solve your problem:
the .htaccess in the root folder:
<IfModule mod_rewrite.c>
    Options -Indexes +FollowSymLinks
    RewriteEngine On

    RewriteBase /

    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

    RewriteRule ^public/.+\.(jpg|gif|png|ico|css|js)$ - [L]
    RewriteRule ^(.*)$ app/$1 [L]
</IfModule>

And the .htaccess in the app folder is unchanged.
Every request starting with public and being a file with the listed extensions won't be redirected which is done with the dash character.
The last rule allows to redirect a request to the app/index.php file.
I think the resulting behaviour is the expected one:

*

*static files in the public directory are not redirected,

*files with another extension in the public directory will be
redirected to app/index.php (maybe for some error treatment),

*requests not starting with public will be redirected to
app/index.php.


text:
Q: Changing number of index in DataFrame? i am trying to change the output of the following code:
import numpy as np
import pandas as pd
from pandas import Series, DataFrame, Panel, bdate_range, DatetimeIndex, date_range
from pandas.tseries.holiday import get_calendar
from datetime import datetime, timedelta
import pytz as pytz
from pytz import timezone

start =  datetime(2013, 1, 1)

hr1 = np.loadtxt("Spot_2013_Hour1.txt")

index = date_range(start, end = '2013-12-31', freq='B')
Allhrs = Series(index)
Allhrs = DataFrame({'hr1': hr1})
df = Allhrs
indexed_df = df.set_index(index)
print indexed_df

The error:
  File "<ipython-input-61-c7890d8ccb07>", line 17, in <module>
    indexed_df = df.set_index(index)

  File "/Applications/anaconda/lib/python2.7/site-packages/pandas/core/frame.py", line 2390, in set_index
    frame.index = index

  File "/Applications/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 1849, in __setattr__
    object.__setattr__(self, name, value)

  File "properties.pyx", line 65, in pandas.lib.AxisProperty.__set__ (pandas/lib.c:38491)

  File "/Applications/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 400, in _set_axis
    self._data.set_axis(axis, labels)

  File "/Applications/anaconda/lib/python2.7/site-packages/pandas/core/internals.py", line 1965, in set_axis
    'new values have %d elements' % (old_len, new_len))

ValueError: Length mismatch: Expected axis has 365 elements, new values have 261 elements

The problem:
I have a time series which i load from a txt file. The time series consists of 365 elements, i.e. all days of the year 2013. I need this txt file as it is because i need to analyse each day.
Additionally i need to analyse specific days of the year 2013. So i want to change the reading of the data, i.e. i want to see only business days. Additionally it would be great to see/print specific days.
Help appreciated

A: First, create a DataFrame (or Series) with all the days of the year:
index = date_range(start='2013-1-1', end='2013-12-31', freq='D')
df = pd.DataFrame(hr1, index=index)

Next, use df.asfreq('B') to downsample df to business days:
import numpy as np
import pandas as pd

# hr1 = np.loadtxt("Spot_2013_Hour1.txt")
hr1 = np.random.random(365)
index = date_range(start='2013-1-1', end='2013-12-31', freq='D')
df = pd.DataFrame(hr1, index=index)

indexed_df = df.asfreq('B')
print(indexed_df)

To set the frequency to business days while excluding certain days, you could use offsets.CustomBusinessDay:
import pandas.tseries.offsets as offsets
holidays = ['2013-10-03' , '2013-12-25']
business_days = offsets.CustomBusinessDay(holidays=holidays)
custom_df = df.asfreq(business_days)

Thus, custom_df has two days fewer than indexed_df
In [12]: len(custom_df)
Out[12]: 259

In [13]: len(indexed_df)
Out[13]: 261

and "holidays" like '2013-10-03' are missing:
In [18]: '2013-10-03' in indexed_df.index
Out[18]: True

In [19]: '2013-10-03' in custom_df.index
Out[19]: False

It's also useful to know that the reindex method can be used to subselect rows. For example, you can subtract specific days from indexed_df.index:
idx = indexed_df.index - pd.DatetimeIndex(holidays)
custom_df2 = df.reindex(idx)

The result, custom_df2 is equal to custom_df:
In [35]: custom_df2.equals(custom_df)
Out[35]: True

but note that the indexes are a bit different:
In [36]: custom_df.index
Out[36]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01, ..., 2013-12-31]
Length: 259, Freq: C, Timezone: None

In [37]: custom_df2.index
Out[37]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01, ..., 2013-12-31]
Length: 259, Freq: None, Timezone: None

The custom_df as Freq: C, while custom_df2 has Freq: None. The freq is used by certain methods, such as snap and to_period. But these methods also allow you to specify the desired frequency as an argument, so in practice I have not found this difference to be a big deal.


text:
Q: Getting error on using Skype4ComLib Hi I am using Skype4ComLib to retrieve Skype contacts but I am getting error:

Retrieving the COM class factory for component with CLSID
  {830690FC-BF2F-47A6-AC2D-330BCB402664} failed due to the following
  error: 80040154 Class not registered (Exception from HRESULT:
  0x80040154 (REGDB_E_CLASSNOTREG)).

Skype is installed on my machine.
any idea?

A: I recently experienced the exact same error message, and it was simply as a result of my .NET project being compiled for "Any CPU" by default.
The SKYPE4COM library is a 32bit only binary, and as such you should make sure that the project you intend to use it with is specifically compiled for "x86" architecture.
As soon as I did this, the error message just went away.
Simply right-click on your project and select "properties". Then under the "Build" tab, choose "x86" where it says "platform target". This process may vary with your version of Visual Studio, but is correct as of version 2012.

A: Have you registered the DLL?  Take a look at this Blog
From above blog:

In the command prompt type : regsvr32 Skype4COM.dll or "regsvr32
  C:\Program Files\Common Files\Skype\Skype4COM.dll"

Also try taking a look at this SO Question


text:
Q: Ring of integers modulo $n$ with a property for the zero divisors. This is a follow-up of Is $a+b$ a unit if $a,b,a-b$ are zero divisors?
Let $n$ be a natural number such that the ring $R:=\mathbb{Z}/(n \mathbb{Z})$ has the following property:
$$a,b,a-b\in Z \implies a+b \in Z$$
where $Z$ are the zero-divisors of $\mathbb{Z}/(n \mathbb{Z})$.
User @lhf made the observation that $R$ seems to have this property exactly when $n$ has less than three prime divisors.
I am interested if this can be made into a proof.
Edit:
Here is a partial result if $\omega(n)=1$, hence $n=p^\alpha$  is a prime power:
If $a,b,a-b\in Z$ then we must have:
$p^{a_0} = \gcd(a,n)>1$,$p^{b_0} = \gcd(b,n)>1$,$p^{c_0} = \gcd(a-b,n)>1$
for $a_0,b_0,c_0\ge 1$. From this it follows that:
$$a = x p^{a_0}, b = y p^{b_0}, a-b=zp^{c_0}$$
and we get:
$$a+b = (a-b)+2b = zp^{c_0} + 2yp^{b_0} = p^{d_0}(zp^{c_0-d_0}+2yp^{b_0-d_0})$$
with $d_0 = \min(c_0,b_0) \ge 1$ since $b_0,c_0 \ge 1$.
Hence $\gcd(a+b,n)>1$ and $a+b \in Z$.

A: Theorem. There exist $a,b\in\mathbb{Z}/n\mathbb{Z}$ for which $a,b,a-b$ are zero divisors but $a+b$ isn't if and only if $n$ has at least $3$ distinct prime factors.
Proof. First assume $n$ has only $1$ or $2$ prime factors. If $a,b,a-b$ are each zero divisors, then they are each divisible by one of these one or two primes, so a pair of them share a prime divisor by the pigeonhole principle. If $a,b$ share it, then $a+b$ is a zero divisor, but if $a,a-b$ or $b,a-b$ share it then so does the third since $b=a-(a-b)$ and $a=(a-b)+b$, so same conclusion.
Now assume $n$ has at least $3$ distinct prime factors. Then we can write $n=ABC$ where $A,B,C$ are pairwise coprime and $C$ is odd. Since the Chinese Remainder Theorem says
$$ \mathbb{Z}/n\mathbb{Z}\cong (\mathbb{Z}/A\mathbb{Z})\times(\mathbb{Z}/B\mathbb{Z})\times(\mathbb{Z}/C\mathbb{Z}), $$
so we can work in this ring instead. Then set $a=(0,1,-1)$ and $b=(1,0,-1)$, which are both nonunits since they have a coordinate $0$, then verify $a-b=(-1,1,0)$ is also a nonunit for the same reason, but $a+b=(1,1,-2)$ is a unit since it is a unit in each coordinate.

I got this example from looking at the case $(A,B,C)=(3,4,5)$. The first example I found were the numbers $a=9$ and $b=4$, with $a-b=5$ and $a+b=13$. I took both of these values and found they corresponded to $(0,1,-1)$ and $(1,0,-1)$ mod $3,4,5$ and noticed that would always work as long as $A,B,C$ were pairwise coprime and $C$ was odd.


text:
Q: Images aren't rendering on Git hub pages I've tried everything. Pushed all image files to Git hub repo. They're all lowercase .jpg and everything appears fine locally in the editor.  Still not showing up on Git hub pages.  Any ideas?

A: *

*Put the image in same repository, for example .\doc\image.jpg

*In *.md file (I assume you talking about readme.md or some other doc in md format) put link to the image like this:

![My Image](https://github.com/<github-user>/<repository>/blob/master/doc/image.jpg?raw=true)

The easy way to get the url - just navigate to uploaded image in web interface, right-click on the image and copy URL :-)


text:
Q: Prob. 13, Sec. 18, in Munkres' TOPOLOGY, 2nd ed: If $Y$ is Hausdorff,then there is a unique extension of every continuous function Here is Prob. 13, Sec. 18, in the book Topology by James R. Munkres, 2nd edition:

Let $A \subset X$; let $f \colon A \to Y$ be continuous; let $Y$ be Hausdorff. Show that if $f$ may be extended to a continuous function $g \colon \overline{A} \to Y$, then $g$ is uniquely determined by $f$.

My Attempt:

Suppose that there are continuous functions $g \colon \overline{A} \to Y$ and $h \colon \overline{A} \to Y$ such that $g(a) = h(a) = f(a)$ for all $a \in A$.
If there is some point $x \in \overline{A}$ for which $g(x) \neq h(x)$, then since $Y$ is Hausdorff, there are disjoint open sets $U$ and $V$ in $Y$ such that $g(x) \in U$ and $h(x) \in V$.
Now as $g$ and $h$ are continuous (by our supposition) and as $U$ and $V$ are open sets in $Y$, so $g^{-1}(U)$ and $h^{-1}(V)$ are open sets in $\overline{A}$ in the subspace topology. So there are open sets $U^\prime$ and $V^\prime$ in $X$ such that $g^{-1}(U) = \overline{A} \cap U^\prime$ and $h^{-1}(V) = \overline{A} \cap V^\prime$.
Moreover, as $x \in \overline{A}$ such that $g(x) \in U$ and $h(x) \in V$, so $x \in g^{-1}(U)$ and $x \in h^{-1}(V)$, which implies that  $x \in U^\prime \cap V^\prime$.
Now as $x \in \overline{A}$ and as $U^\prime \cap V^\prime$ is an open set containing $x$, so there is an element $a \in A$ such that $a \in U^\prime \cap V^\prime$. And, as this $a \in A$, so $g(a) = h(a) = f(a)$, and also $a \in \overline{A}$.
Thus $a \in \overline{A} \cap U^\prime =  g^{-1}(U)$ and $a \in \overline{A} \cap V^\prime   = h^{-1}(V)$. Therefore, $g(a) \in U$ and $h(a) \in V$.
But $g(a) = h(a) = f(a)$. So $f(a) \in U \cap V$, which contradicts our choice of $U$ and $V$ as disjoint open sets containing $g(x)$ and $h(x)$, respectively.
Thus there is no point $x \in \overline{A}$ for which $g(x) \neq h(x)$. That is, $g(x) = h(x)$ for all $x \in \overline{A}$. Hence $g = h$, as required.

Are there any issues with this proof?

A: This is actually simpler than this.
If $f$ and $g$ continuously extend function $f$ such that $g(x) \neq h(x)$ for some point $x \in \overline A-A$, then we can find two disjoint open sets $U, V$ such that $g(x) \in U$ and $h(x) \in V$.
In this case $g^{-1}(U)$ and $h^{-1}(V)$ are open and both contain $x$, and $g^{-1}(U) \cap h^{-1}(V)$ is open. Since $x \in \overline A$, $\exists a \in A \cap g^{-1}(U) \cap h^{-1}(V)$. But then $g(a)=h(a)$, which contradicts the disjunction of $U$ and $V$.


text:
Q: Meromorphic 1-form and Picard's theorem Let $D$ be the open unit disk in the complex plane and $U_1,U_2,\,\ldots\,,U_n$ be an open cover of the puntured disk $D^*= D\setminus\{0\}$. Suppose on each open set $U_j$ there is an injective holomorphic function $f_j$ such that $df_j=df_k$ on every intersection $U_j\cap U_k$.
Question: Is it true that the differentials $df_j$ glue together to a meromorphic 1-form on $D$?
Remark: If the residue is zero then it is true (with help of Picard's theorem).

A: Thanks for the answer! I apologize for answering with a delay (am on biking trip in Corsica).
Yes, Tom Goodwillie is right about the necessity of the connectiveness condition. Bill Thurston's answer, however, does not convince me. I will explain why:
Call $\omega$ the holomophic form defined on the punctured unit disk. There are two cases:

*

*The residue is zero. Then there is a holomorphic function on the unit disk such that $df=\omega.$ Thus $df=df_j$ for every j. Using the connectedness of $U_j$ one can add a constant to $f_j$ such that $f=f_j$ on $U_j$. Then one concludes easily with Picard that f is meromorphic on the unit disk.

*The residu $a$ is not zero.  Then integrating $\omega$ yields a cover of infinite order because each turn around the origin adds the number $2\pi a$. So here I do not agree with Bill Thurston who says the order is finite. What actually happens is that the primitive of $\omega$ is of the form:
holomorphic function on the punctured disk + $a\times$ logarithm.
Now here comes my explanation of Bill Thurston's mistake when he says that the covering space is of finite order. The best way to define the Riemann R(g) surface of an analytic germ g is to say that R(g) is the connected component of g in the total space $|\mathcal{O}|$ of the sheaf of holomorphic functions. There are two natural projections defined on R(g). The first  projection sends each germ to its centerpoint ("projection on the variable plane"). The second projection sends each germ to the value the germ takes in its centerpoint ("projection on the value plane"). It is the first projection that we are interested in. But when arguing that his covering space is finite above the punctured unit disk, Bill Thurston actually uses the functions $f_j$ as map, thus taking the second projection instead of the first.

A: If the $U_i$'s are assumed to be connected (as in Tom Goodwillie's comment) the answer is yes. There are counterexamples if the $U_i$ are not connected.
The hypothesis implies that the differentials $df_j$ patch together to define a differential form $\omega$ on $D \setminus 0$ that is never 0 (on $D \setminus 0$).  Integration of $\omega$ defines a covering space of $D \setminus 0$: that is, we can choose a basepoint,
say $* = 1/2$, elements of the covering space $Y$ consist of points $z \in D \setminus 0$ together with a value that can be obtained by integrating $\omega$ along some path in $D \setminus 0$
 from $*$ to $z$.
If $\omega$ is the differential of an injective function on each of finitely many
connected $U_j$'s (following Tom Goodwilli's comment), then each $U_j$ can be lifted to the covering space $Y$. This
implies that the branched cover has finitely many sheets. Since $\pi_1(D \setminus 0)$ is abelian, $Y$ an $n$-fold cyclic cover isomorphic to $z \mapsto z^n$. In these coordinates,
 pullback of $\omega$ to $Y$ can be integrated to give a function $g$ from $Y$ to the Riemann sphere such that satisfies $g(\zeta y) = g(\zeta) + C$ for some constant $C$, where $\zeta$ is a
primitive $n$th root of unity. But then $n*C = 0$, so $C = 0$, so $g$ comes from a function on $D \setminus 0$; since it is finite-to-one near 0,  by Picard's theorem this is a removable singularity (as a map to the Riemann sphere), it extends to a meromorphic function on $D$, and its differential is therefore meromorphic.
If the $U_j$'s are not assumed connected, the covering space $Y$ still exists, but it need not have
finitely many sheets.  In the infinite-sheeted case, the covering space is the universal cover of $D \setminus 0$ isomorphic to $z \mapsto \exp(z)$ from the right halfplane $Re(z) < 0$ to $D \setminus 0$.  The integral of the pullback of $\omega$ to the right halfplane
is a function that has the form $g(z) = a z + g_0(z)$, where $g_0(z)$ is the pullback of a function $f_0$ defined on $D \setminus 0$.  (The linear term takes care of the integral
of $\omega$ on a loop around the origin).  The function $f_0$ must be an immersion (locally univalent function) from $D \setminus 0$ to $\mathbb C$.  Such functions can be rather wild, for example, $f_0(z) = exp(1/z)$.  The integral of $\omega$ itself could then be expressed as the multi-function $f(z) = z^a f_0(z)$, where $a$ is any complex number.
Claim for any complex number $a$ and any locally univalent function $f_0: D \setminus 0 \to \mathbb C$ there is a finite cover $U_i$ of $D \setminus 0$ (where the $U_i$ are not connected) such that on each $U_i$ $\omega$ is the differential of a univalent function $f$.
Proof of Claim: Cover $D \setminus 0$ by countably many open sets such that the integral
of $\omega$ in each set is univalent.  Every cover of a 2-manifold has a refinement that is locally at most 3-to-1, so its nerve is a 2-complex. (This is one characterization of topological dimension). It has a further refinement $U$, corresponding to the barycentric subdivision, by a covering that can be partitioned into three parts $U = A \cup B \cup C$
 where the elements of $A$ are disjoint, the elemetns of $B$ are disjoint, and the elements of $C$ are disjoint.   We can integrate $\omega$ on each of the elements of $A$, $B$ and $C$, and then add suitable constants to make the images in each of $A$, $B$ and $C$ disjoint.
In summary: we've found three holomorphic functions $f_A$, $f_B$ and $f_C$ defined on
the union of $A$, the union of $B$ and the union of $C$ whose differentials all equal
$\omega$, but $\omega$ has an essential singularity at the origin.

A: Here is another conjecture that seems to me equivalent to my initial question. (It is a kind of "ugly" version above the value plane, the initial question above the variable plane, the disk, being the "nice" point of view.)
Let $f : E\to \mathbb{C}$ be a connected étale space and $t:E\to E$ an isomorphism ("translation") such that  $f\circ t=f+2i\pi a$ where $a$ is a non-zero complex number. Then $\mathbb{Z}$ acts on $E$ via the "translations" $t^n$. The 1-form $df$  clearly induces a 1-form on the quotient  space $E/\mathbb{Z}$ which we still denote by $df$. Conjecture: if the quotient space is biholomorphic to the punctured disk then the pullback of $df$
does not have an essential singularity at the center of the disk (and its residue at the center is exactly $a$).


text: Q: C# chrome selenium fake geolocation I'm writing automation for chrome selenium. After the browser is opened, I have to change location. enter link description here how can I make the structure in the link for c #?


text:
Q: Free API or similar to get Next Earnings Date for stocks I am looking for an API or similar where I can get the next (upcoming) earnings date for a stock. I have googled for it and haven't found anything usable. I know of both the Yahoo and Google finance APIs, but none of them provide the next earnings date. Many sites, i.e.  www.finviz.com (look for "Earnings" here http://finviz.com/quote.ashx?t=c) have the next earnings date information, but no API to get it.
Does anyone know where I can fetch the next earnings date?
Thank you :-)

A: I think this may have what you need, it's not free but it has a free trial which may be sufficient for your needs: http://www.zacksdata.com/zacks-data-api
(Disclosure: This API is managed by my company)

A: again not free, but here is another one :
http://www.pracplay.com/products/starter/starter_reference#TOC-EventScreen
and the api :
http://www.pracplay.com/products/starter/starter_reference#TOC-Calendars-and-Other
(Disclosure: This API is managed by my company)


text:
Q: Using realm for iOS app dev, is there a way to see your database as a GUI? It would help alot for development.

A: Yes, you can

*

*Install Realm-browser.

*Set breakpoint and use lldb console for find db file path

Objective-C
po [RLMRealmConfiguration defaultConfiguration]

Swift
po RLMRealmConfiguration.defaultConfiguration()

*Open terminal and type open [Pasted path here]

A: You can also set up the Realm Object Server (https://realm.io/products/realm-mobile-platform/) and open the Realms via that. Then you will be able to open the Realms remotely with the Realm Browser and inspect them live, even while the app is running on on the device.


text:
Q: Extract from array values having keys as values of another array Better show than tell.
$first = array(
    3=>"Banana",
    4=>"Apple",
    6=>"Lemon",
    7=>"Pineapple",
    8=>"Peach"
);

$second = array(4,7,8);

(Please note: the first one is associative array, it can have holes)
The result should be
$result = array(
    "Apple",
    "Pineapple",
    "Peach"
);

Any smart idea?
Thank you

A: Here we are using array_intersect_key, array_flip and array_values. This single liner will be enough.

1. array_values will return values of an array.
2. array_flip will flip array over keys and values.
3. array_intersect_key will return array on the basis of two input array's over intersecting keys.

Try this code snippet here
print_r(
     array_values(
         array_intersect_key(
                  $first, array_flip($second))));

A: Just a simple foreach loop will do it. And isset() checks that the index exists in the first array before trying to read it:
$first = array(
    3=>"Banana",
    4=>"Apple",
    6=>"Lemon",
    7=>"Pineapple",
    8=>"Peach"
);
$second = array(4,7,8);
$result = array();

foreach($second as $i)
{
    if (isset($first[$i])) $result[] = $first[$i];
}

var_dump($result);

A: You can use like this
$first = array(

    3 => "Banana",
    4 => "Apple",
    6 => "Lemon",
    7 => "Pineapple",
    8 => "Peach"
);

$second = array(4, 7, 8);

foreach ($first as $key => $val) {
    if (array_search($key, $second) === false) {
        unset($first[$key]);
    }
}

print_r($first);
exit;


text:
Q: Hibernate Criterion: wrap object Criterion in Exists Currently we have a difficult logic for generate Criterion object. And we need to wrap the finally generated criterion in "exists" operator. For example, the sql code generated of Citerion object:
Select tbl1.name from tbl1

and in result we want to have in generated Criterion object
exists (Select tbl1.name from tbl1)

Maybe, someone have any ideas. I wathced on DetachedCriteria, but it not applicable in current issue


text:
Q: Capistrano bringing deleted git files to release I am deploying with Capistrano and using git as my version control.
When I do cap deploy:update , it is bringing deleted files that are no longer in master to the /release/bla folder.
I do not wish to delete these files as I might need to check them in the future but also, I do not wish that Capistrano use them in my releases.
What are my options?
--
As per @LeeHambley's response below, I had a misunderstanding about how git commit -a works. git commit -a deletes the files from the current master but not their history. You can get their history as @LeeHambley details below.

A: Sounds like they should be added to your .gitignore so that Git won't touch them, you could then easily upload them once by hand, or symlink them each deploy.
Typically, this would be done by uploading them into shared:
shared $ tree
.
└── config
   └── database.yml
   └── system
      └── uploads

And then people write tasks to symlink them into the release:
after 'deploy:symlink' do
  %w{database system}.each do |path|
    run "ln -s #{shared_path + path} #{latest_release + path}"
  end
end

This way, one would also add the following lines to gitignore:
/config/database.yml
/system/uploads

This would mean that they wouldn't be managed by Git anymore, each developer on your team would have their own copy of those files, and they'd have to be created on the server once by hand, then Git, or Capistrano won't mess with them again.
Regarding "I might need to check them in in the future" - I'd suggest you could commit thefile.yaml.example to the repository, and document the procedure for new installations to make your developer's lives easier.
When you add the files to the .gitignore, they'll also need to be deleted from the repository, this won't remove the history of the file, but it will remove it from the current head. If it's important you could always get the history of the file by doing git log ./path/to/any/file/even/if/it/does/not/exist.anymore. A wiser course of action might be to use git mv to move the file from it's existing position to {oldname}.sample, so the history will be transferred to the .sample file.


text:
Q: Forwarding SMS messages to multiple phone #'s on Twilio I currently use SMS forwarding to one number for multiple applications -- it keeps my SMS inbox nice and tidy -- love it.
However, we're using multiple SMS alert services and I'd like to forward them off to my team so we all get the alert. My coding skills aren't very strong, so I'm struggling here to understand what I can do to make this work.  So long story short, an SMS message comes in and is forwarded off immediately to multiple numbers.
Here's the code I use for forwarding to one number. What can I do to forward to multiple numbers?
> [root@centos64 html]# more fwdsms.php
> <?php
> header('Content-Type: text/html');
> ?>
> <Response>
>    <Message to="<?=$_REQUEST['PhoneNumber']?>">
> <?=htmlspecialchars(substr($_REQUEST['From'] . ": " . $_REQUEST['Body'], 0, 1600))?>
> </Message>
> </Response>
> [root@centos64 html]#

A: If your list of numbers to forward to is not crazy big, easiest in this case would probably be to just add multiple <Message> verbs to your script.
<Message to="RECIPIENT1">
<?=htmlspecialchars(substr($_REQUEST['From'] . ": " . $_REQUEST['Body'], 0, 1600))?>
</Message>
<Message to="RECIPIENT2">
<?=htmlspecialchars(substr($_REQUEST['From'] . ": " . $_REQUEST['Body'], 0, 1600))?>
</Message>

To clean it up a bit you could store your $_REQUEST info in a $message variable and then do something like:
<Message to="RECIPIENT1"> <?php echo $message; ?></Message>
<Message to="RECIPIENT2"> <?php echo $message; ?></Message>

Let me know if this helps!


text:
Q: Flipping an image with python (pygame) I'm trying to learn python so I'm messing around with pygame. I'm a complete beginner.
so far I have made it so that I can control an image, moving it in 2d with the arrow keys.
However, I drew the image facing left and it is always facing left and I want to make it face the direction it's moving. I managed to make it rotate 180 degrees when I press right, but that was everytime I press right so I kept flipping the wrong way.
I need it to face right when moving right and left when moving left.
Image attached.
Thank you
import pygame
import time
pygame.init()
display_width = 1000
display_height = 800
black=(0,0,0)
white=(255,255,255)
gamedisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('metal gear python')
clock = pygame.time.Clock()

snakeimg= pygame.image.load('snake.png')

snake_width = 96
snake_height= 79
def snake(x,y):
    gamedisplay.blit(snakeimg, (x,y))

discovered = False
while not discovered:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            discovered = TRUE
        print (event)

    x = (display_width * 0.45)
    y = (display_height * 0.8)
    x_change=0
    y_change=0
    snake_speed=0

    gameExit= False
    while not gameExit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            print(event)
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -3
                elif event.key == pygame.K_RIGHT:
                    x_change = 3

                elif event.key == pygame.K_RIGHT:
                    x_change = 3

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    x_change = 0
                elif event.key == pygame.K_RIGHT:
                    x_change = 0
        x += x_change

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                    y_change = -3
            elif event.key == pygame.K_DOWN:
                    y_change = 3
        if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    y_change = 0

        y += y_change

        gamedisplay.fill(white)
        snake(x,y)

        if x > display_width-snake_width or x < 0:
            gameExit=True

        if y > display_height-snake_height or y < 0:
            True

        pygame.display.update()
        clock.tick(60)

pygame.quit()
quit()

A: Mainly i change the snake function, so that it computes the correct rotation and then rotates the image. Also I change a little bit of the logic, especially at event handling so it is easier to read
import pygame
import time

pygame.init()
display_width = 1000
display_height = 800
black = (0, 0, 0)
white = (255, 255, 255)
gamedisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('metal gear python')
clock = pygame.time.Clock()

snakeimg = pygame.image.load('snake.png')

snake_width = 96
snake_height = 79

def snake(x, y):
    if x_change == 0 and y_change == 0:
        rotation = -90
    elif x_change > 0 and y_change == 0:
        rotation = 180
    elif x_change < 0 and y_change == 0:
        rotation = 0
    elif x_change == 0 and y_change > 0:
        rotation = 90
    elif x_change == 0 and y_change < 0:
        rotation = -90
    elif x_change < 0 and y_change < 0:
        rotation = -45
    elif x_change < 0 and y_change > 0:
        rotation = 45
    elif x_change > 0 and y_change < 0:
        rotation = -135
    elif x_change > 0 and y_change > 0:
        rotation = 135
    gamedisplay.blit(pygame.transform.rotate(snakeimg, rotation), (x, y))

discovered = False
while not discovered:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            discovered = True
        print(event)

    x = (display_width * 0.45)
    y = (display_height * 0.8)
    x_change = 0
    y_change = 0
    snake_speed = 0

    gameExit = False
    while not gameExit:
        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                gameExit = True
                discovered = True # so you can actually quit the game
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -3
                elif event.key == pygame.K_RIGHT:
                    x_change = 3
                elif event.key == pygame.K_UP:
                    y_change = -3
                elif event.key == pygame.K_DOWN:
                    y_change = 3
            elif event.type == pygame.KEYUP:
                if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
                    x_change = 0
                elif event.key in (pygame.K_UP, pygame.K_DOWN):
                    y_change = 0

        x += x_change
        y += y_change

        gamedisplay.fill(white)
        snake(x, y)

        if x > display_width - snake_width or x < 0:
            gameExit = True

        if y > display_height - snake_height or y < 0:
            gameExit = True

        pygame.display.update()
        clock.tick(60)

pygame.quit()
quit()

And still i have the question: Why 2 game loops inside each other?


text:
Q: Add in openapi file helidon objects health and metrics I was write file openapi.yml wth openapi 3.0 description for services in my helidon project. But I use standart helidon handlers too (health and metrics):
return Routing.builder()
   .register(JsonSupport.create())
   .register("/api/files", health)
   .register("/api/files", metrics)
   .register("/api/files/storage", fileService)
   .register("/api/files", OpenAPISupport.create(config))
   .build();

How make section for health and metrics in my openapi.yml? I use:
<dependency>
   <groupId>io.helidon.openapi</groupId>
   <artifactId>helidon-openapi</artifactId>
   <version>1.3.1</version>
</dependency>

A: There are two ways you can do this:

*

*Simply add the /health and /metrics endpoint information to the openapi.yml file you already created.

*Add your own implementation of the MicroProfile OpenAPI OASModelReader interface to your application that adds the health and metrics information programmatically. You also set a configuration value to tell the system about your implementation. Please see https://helidon.io/docs/latest/index.html#/openapi/01_openapi for the details.

Unfortunately, there is not currently any automatic way to add OpenAPI information about health and metrics to your application's OpenAPI document.
Further information (I seem to have misinterpreted the original question):
The /metrics and /health endpoints are implemented by Helidon, but the MicroProfile Metrics and Health specifications dictate the paths for and the behavior of those endpoints.
Some relevant documents to get you started:
metrics:

*

*architecture: https://github.com/eclipse/microprofile-metrics/blob/2.3.2/spec/src/main/asciidoc/architecture.adoc

*REST endpoints: https://github.com/eclipse/microprofile-metrics/blob/2.3.2/spec/src/main/asciidoc/rest-endpoints.adoc
health:

*

*wire protocol: https://github.com/eclipse/microprofile-health/blob/2.2/spec/src/main/asciidoc/protocol-wireformat.adoc


text:
Q: How to set auto_increment_offset and auto_increment_increment for a single database Is it possible to set auto_increment_offset and auto_increment_increment variables only for a single database without affecting any other database?
The reason why I want this is I am implementing a master master replication on a database but I have a cloud VPS with 30 domains and its databases. So I need to set this variables for a single database without affecting the other databases.

A: No, it is a global variable. You can set it per session though, so the PHP software could be written to set it each time the database connection is opened.

If the local value is set, the new value affects AUTO_INCREMENT columns for all tables into which new rows are inserted by the current user for the duration of the session, unless the values are changed during that session.


text:
Q: Displaying Data on Table I have a question.I have an empty
 and when i click on an empty -Element, i can pass Data from an <input>-Element and save this String into my Database.Actually i want this String to be displayed on my -Element.(It means,there is a possibity, that every -Elements can display its own String.)
This is how i create my
 :

    <%for(int uzeit = 0; uzeit < uhrzeit.length ;uzeit++) { %>

            <%out.println(uhrzeit[uzeit]); %>
            <%for(int rest =0; rest<wochentag.length;rest++) { %>

            <%} %>

    <%} %>

This is how i save the <input> :
int result = 0;

if(request.getParameter("submit") != null) {
    String name = new String();

    if(request.getParameter("getdata") != null) {
        name = request.getParameter("getdata");
    }else {
        out.println("termin is null");
    }
    Termin t1 = new Termin();
    result = t1.setTermin(name);

setTermin(name) adds 'name' to my Database.

Hope someone can help me :)

A: I'm not entirely sure if I understand it correctly, but I think the idea is to have an input field and then, ehn you click on a td the data in the input field goes there. To do that, you can use plain JS or Jquery. I used jquery as the code is faster to write. Your change code should look like this:
$(document).ready(function(){
    $('td').click(function(){
        $(this).text($('#myIn').val());
        $('#myIn').val("");
    });
});

Check it working on: http://jsfiddle.net/lrojas94/sn0x6xat/
Basically, when you click a td element, you want it to take the value of the actual input. If what you want is to, also, submit that input, then you can feel free to do it using AJAX while showing the input to the user.
Sorry if I did not answer your question. If I didn't please try to be a little more clear.


text:
Q: Как отключить редирект для всех файлов, начинающихся на 1c_exch_.....? В htaccess у меня есть следующее:
<FilesMatch "1c_exch_blabla.php$">RewriteEngine off</FilesMatch>

То есть, отключаем редирект на https для конкретного данного файла.
Вопрос такой: а как отключить редирект для всех файлов, начинающихся на 1c_exch_..... ?

A: подсказал коллега
<FilesMatch "1c_exch_*$">


text:
Q: Yocto glibc-locale do_package installed but not shipped in any package I am trying to build a custom image on yocto. When I create an image, I get an error in glibc-locale (do_package step).
The error is
ERROR: glibc-locale-2.24-r0 do_package: QA Issue: glibc-locale: Files/directories were installed but not shipped in any package:
    {
        "a lot of file in /usr/lib/gconv, /usr/share/i18n paths"
    }
    Please set FILES such that these items are packaged. Alternatively if they are unneeded, avoid installing them or delete them within do_install.
    glibc-locale: 820 installed and not shipped files. [installed-vs-shipped]
    ERROR: glibc-locale-2.24-r0 do_package: Fatal QA errors found, failing task.
    ERROR: glibc-locale-2.24-r0 do_package: Function failed: do_package
    ERROR: Logfile of failure stored in: /home/test/rpi/build/tmp/work/cortexa7hf-neon-vfpv4-poky-linux-gnueabi/glibc-locale/2.24-r0/temp/log.do_package.30243
    ERROR: Task (/home/test/poky-morty/meta/recipes-core/glibc/glibc-locale_2.24.bb:do_package) failed with exit code '1'

I tried to solve it adding the following in the glibc-locale_2.24.bb file:

INSANE_SKIP_${PN} = "installed-vs-shipped "

When I do this, there is no error in glibc do_package step anymore but I have an error in the do_rootfs step:
 ERROR: ekt-image-1.0-r0 do_rootfs: Unable to install packages. Command '/home/test/rpi/build/tmp/sysroots/x86_64-linux/usr/bin/opkg --volatile-cache -f /home/test/rpi/build/tmp/work/raspberrypi3-poky-linux-gnueabi/ekt-image/1.0-r0/opkg.conf -t /home/test/rpi/build/tmp/work/raspberrypi3-poky-linux-gnueabi/ekt-image/1.0-r0/temp/ipktemp/ -o /home/test/rpi/build/tmp/work/raspberrypi3-poky-linux-gnueabi/ekt-image/1.0-r0/rootfs  --force_postinstall --prefer-arch-to-version   install locale-base-en-us' returned 255:
Collected errors:
 * opkg_prepare_url_for_install: Couldn't find anything to satisfy 'locale-base-en-us'.

ERROR: ekt-image-1.0-r0 do_rootfs: Function failed: do_rootfs
ERROR: Logfile of failure stored in: /home/test/rpi/build/tmp/work/raspberrypi3-poky-linux-gnueabi/ekt-image/1.0-r0/temp/log.do_rootfs.10085
ERROR: Task (/home/test/rpi/meta-rpi/images/ekt-image.bb:do_rootfs) failed with exit code '1'

I tried to cleanstate glibc, glibc-locale but it does not work.
Edit: I tried to add these lines in my glibc-locale.inc file:
FILES_kernel-base += "/usr/share/i18n/charmaps/*"
FILES_kernel-base += "/usr/share/i18n/locales/*"
FILES_kernel-base += "/usr/lib/gconv/*"
FILES_kernel-base += "/usr/share/i18n*"

And also these lines:
FILES_${PN} += "/usr/share/i18n/charmaps/*"
FILES_${PN} += "/usr/share/i18n/locales/*"
FILES_${PN} += "/usr/lib/gconv/*"
FILES_${PN} += "/usr/share/i18n*"

But it does not solve my problem.

A: I have had this issue, and it seems to be due to leaving out glibc options in the DISTRO_FEATURES for the build. If you're redefining DISTRO_FEATURES, make sure to include ${DISTRO_FEATURES_LIBC} in its definition.
See Re: [yocto] Problem building glibc-locale on the Yocto mailing list.
See also the comments about DISTRO_FEATURES_LIBC in openembedded-core/local.conf.sample.extended at master · openembedded/openembedded-core.

A: Instead of adding a distro feature like this:
DISTRO_FEATURES += "feature"

Try instead:
DISTRO_FEATURES_append = " feature"

The first sentence in my conf/local.conf was overwriting ?= definitions, such as DISTRO_FEATURES_LIBC.


text:
Q: Override validation messages from package in laravel 5 I have this input in a custom package:
<input name="price" type="text">

The request class has the following rule:
public function rules()
{
    return [
        'price' => ['required']
    ];
}

When the rule fails for price input, the message displayed is:

The price field is required

Instead I would like to display:

The super cool price is required

Editing resources/lang/en/validation.php is not an option, because the lang must be setted from the package itself. Do you have any idea on how to achieve this?
Edit: following the docs on how overriding package language files is not working having the following structure:
// resources/lang/packages/en/my-package/validation.php

return [
    'attributes' => [
        'price' => 'super cool price'
    ],
    'custom' => [
        'price' => [
            'required' => 'super cool price is required'
        ],
    ],
];

A: A good alternative is override the messages() function in the request class:
public function messages()
{
    return [
        'price.required' => 'super cool price is required'
    ];
}

public function rules()
{
    return [
        'price' => ['required']
    ];
}


text:
Q: Is a 15" laptop with full HD useable on a daily basis? Or would I have to probably work on a lower resolution? I have a 17" and it is too big to transport around. Not sure if this is the right place to ask but google search listed it as the first place for questions about laptops.

A: Speaking from personal experience, I wouldn't want anything less than full HD on my 15" laptop.
It is smaller and needs some getting used to the first few days, but Windows is resized to 125%, so that it feels more like what you're used to. So yes, I really recommend it.
Personally I've even changed this to 100%, but I'm still quite young. This preference might be different depending on your age, your eyes and personal choices.


text:
Q: Line drawing on dragging from one point to another in android I want to make an app in which when i touch at a point on the screen and drag to another position,a line get drawn on ACTION_UP and then another line from the ACTION_UP position to some other point and so on.But the line we have drawn before should not disappear on drawing a new line.

A: public class LineDrawerView extends View
{
    public LineDrawerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    ArrayList<Rect> lines= new ArrayList<Rect>();
    int x1, y1;
    int x2, y2;
    boolean drawing=false;

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);

        canvas.drawColor(Color.YELLOW);

        Paint p= new Paint();
        p.setColor(Color.BLACK);

        if (drawing)
            canvas.drawLine(x1, y1, x2, y2, p);
        else
            for (int i=0; i<lines.size(); i++)
            {
                Rect currline= lines.get(i);
                canvas.drawLine(currline.left, currline.top, currline.right, currline.bottom, p);
            }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        boolean result=false;
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                x1=x2= (int)event.getX();
                y1=y2= (int)event.getY();
                drawing=true;
                result=true;
                break;
            case MotionEvent.ACTION_MOVE:
                x2= (int)event.getX();
                y2= (int)event.getY();
                result=true;
                break;
            case MotionEvent.ACTION_UP:
                x2= (int)event.getX();
                y2= (int)event.getY();
                lines.add(new Rect(x1, y1, x2, y2));
                drawing=false;
                result=true;
                break;
        }

        if (result) invalidate();
        return result;
    }
}