text:
Q: Embed PowerBI With RLS I'm trying to embed a powerbi report in a .NET Core Project with RLS(row level security)
The issue is I'm unable to add the reference to the embedToken on the front end.
Here is the front end code:
<script type="text/javascript">

    // This code is for sample purposes only.

    // Configure IFrame for the Report after you have an Access Token.
    window.onload = function () {
        var reportData = @Html.Raw(Json.Serialize(Model));

        var accessToken = reportData.AccessToken;
        var embedUrl = reportData.EmbedUrl;
        var reportId = reportData.ReportId;

        //show panel for admins
        if (userIsAdmin == "true") {
            filterPaneEnabled = true;
        }
        else {
            filterPaneEnabled = true;
        }

        var config = {
            type: 'report',
            accessToken: accessToken,
            embedUrl: embedUrl,
            tokenType: models.TokenType.Embed,
            id: reportId,

            settings: {
                filterPaneEnabled: filterPaneEnabled,
                navContentPaneEnabled: true
            }
        };

        // Grab the reference to the div HTML element that will host the report.
        var reportContainer = document.getElementById('reportContainer');
        // Embed the report and display it within the div container.
        var report = powerbi.embed(reportContainer, config);
    };
</script>

Here is the backend token generation by providing effective identity/role for rls:
  var rls = new EffectiveIdentity(username: "someuser", new List<string> { "someid" });

                var rolesList = new List<string>();
                rolesList.Add("DYNAMIC_RLS");
                rls.Roles = rolesList;

                var embedToken = client.Reports.GenerateTokenInGroup(groupId, reportId,
                    new GenerateTokenRequest(accessLevel: "View", datasetId: "someid", rls));

                EmbedToken token = await GetEmbedToken(client, reportId, groupId, accessToken);

                Report powerBIReport;
                powerBIReport = await GetPowerBIReport(client, reportId, groupId);
                if (powerBIReport != null)
                {
                    model.ReportId = reportId;
                    model.ReportName = report.Name;
                    model.EmbedToken = token;
                    model.AccessToken = accessToken;
                    model.EmbedUrl = powerBIReport.EmbedUrl;
                    model.UserIsAdmin = "false";
                }

Here are the errors I'm getting: I noticed if I remove " tokenType: models.TokenType.Embed" from the front end config the report renders but no rls is shown.
Any tips? I have verified the embed token is generated correctly as I connected via powerbi sandbox environment!


text:
Q: how to add css file in mpdf I am trying to convert html into pdf using mpdf. Problem is that i am unable to apply css to pdf file..
Here is my code of php:
<?php

    $html = $divPrint;
    $mpdf=new mPDF();
    $stylesheet = file_get_contents('pdf.css');
    $mpdf->WriteHTML($stylesheet,1);
    $mpdf->WriteHTML($html,2);
    $mpdf->Output();
    exit;

?>

What it is doing is taking html through ajax on my this php page. But the output it gives doesn't come with css which i've written for it..
Please tell me that to do now?

A:  <?php

$html = $divPrint;

include('mpdf.php'); // including mpdf.php
$mpdf=new mPDF();
$stylesheet = file_get_contents('pdf.css'); // external css
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html,2);
$mpdf->Output();
exit;

?>

1st assign your html in $html then include  mpdf.php file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Combine ODE with constraints using a Lagrange multiplier Consider a constrained ODE system:
\begin{align}
\dot{\bf x} &= \bf f(t,\bf x), \\
st. 0 &= \bf g(t,\bf x).
\end{align}
I wish to combine these into a single equation using a Lagrange multiplier, however I am unsure how to do it. I talked with my supervisor the other day about it and he quickly scribbled the following down:
\begin{equation}
\dot{\bf x} + (\nabla_\bf x \bf g(\bf x))^\top \lambda = \bf f(t,\bf x).
\end{equation}
However, it was a last moment thing so it might not be entirely correct, and I don't really see how he would get that. But then again I don't exactly see how I can apply the Lagrange method in the first place since it requires a function you wish to maximize/minimize, whereas I have $\bf f(t,\bf x) - \dot{\bf x} = 0$.
Does anyone have any advice on how to approach this problem?
Based on the information Carlo Beenakker gave me I have attempted the following:
I tried following the method outlined in: https://ep.liu.se/ecp/084/010/ecp13084010.pdf section 6.
If I understand this correctly I want to turn my constrained ODE into an optimization under constraint problem, which leads to a lagrangian equation.
So I consider equation (63-64):
\begin{equation}
\mathcal{F}({\bf x}) = \int_{t_0}^{t_1} L(t,{\bf x}, {\bf \dot{x}}) dt
\end{equation}
subject to the constraints
\begin{equation}
\phi({\bf x}) = \int_{t_0}^{t_1} h(t,{\bf x}) dt = 0
\end{equation}
I can see that the first equation is similar to my original equation with ${\bf f}(t,{\bf x}) = L(t,{\bf x}, \bf \dot{x})$, and the constraints I guess are related as such:
\begin{equation}
h(t,{\bf x}) = \frac{d}{dt} g(t,{\bf x})
\end{equation}
This then leads me to equation 67:
\begin{equation}
\frac{\partial L}{\partial {\bf x}} - \frac{d}{dt} \left(\frac{\partial L}{\partial {\bf \dot{x}}} \right) = \nabla_{\bf x} h({\bf x}) \lambda
\label{eq:1}
\end{equation}
However, if I use ${\bf f}(t,{\bf x}) = L(t,{\bf x}, \bf \dot{x})$, and insert it, I get:
\begin{equation}
\frac{\partial f(t,{\bf x})}{\partial {\bf x}} - \frac{d}{dt} \left(\frac{\partial {\bf \dot{x}}}{\partial {\bf \dot{x}}} \right) = \frac{\partial f(t,{\bf x})}{\partial {\bf x}} = \nabla_{\bf x} h({\bf x}) \lambda
\end{equation}
Which doesn't look right. So I'm guessing I did something wrong or there is something I have forgotten. Anyone that can give me a hint as to what I'm doing wrong?


text:
Q: MongoDB indexed performance: ascending vs descending I'm trying to figure out if there is any performance issue when choosing ascending vs descending index:
I have the following index: <system_id, created>:
system_id: this is an ObjectId, ascending order.
created: this is a Date, ascending order.
My collection has more than 30 million documents.
I want to get the last documents which were created in the last week (created field) and belong to a certain system_id.
I'm limiting the results to 2000 documents and sorting them by created: -1.
The query takes a long time (more than a minute).
If I change the index to be system_id (asc), created (desc), will it be better in terms of performance?


text:
Q: In Ruby, how does one verify the identity of a Struct? I've been trying to make sense of the class of self in the present method that Ryan Bates used in his Presenters RailsCast (#287 Presenters from Scratch (pro) - RailsCasts). In the video, Ryan says, 'Self is the template object which has all the helper methods we want to access', but I wanted to know the class for this object. After reading a range of blog posts, SO threads, and Ruby docs, I'm starting to think that self is a kind of Struct, but I don't know how to confirm this notion.
My questions are: 1) In the present method below, is self a Struct?, and 2) How does one verify that something is a Struct?
module ApplicationHelper
  def present(object, klass = nil)
    klass ||= "#{object.class}Presenter".constantize
    presenter = klass.new(object, self)
    yield presenter if block_given?
    presenter
  end
end

I'm asking this because I don't have much experience working with  Struct classes and when I stick binding.pry in the middle of the method above and try to get the name of the class for self, I end up with more questions.

*

*When I enter self.class, I get, #<Class:0x007fb64f696268> I wondered if getting Class here might indicate that I have a Struct, but I couldn't find any documentation that confirmed this

*When I enter self.class.class, I get Class

*When I enter self, I get an extensive object that starts with the lines of code of code listed below
@ line 16 ApplicationHelper#present:

14: def present(object, klass = nil)
15:   klass ||= "#{object.class}Presenter".constantize
16:   binding.pry
17:   presenter = klass.new(object, self)
18:   yield presenter if block_given?
19: end

[1] pry(#<#<Class:0x007fb64f696268>>)> self
=> #<#<Class:0x007fb64f696268>:0x007fb64f6948f0
@_assigns={"marked_for_same_origin_verification"=>true},
@_config={},
@_controller=
  #<PostsController:0x007fb64f6762d8
   @_action_has_layout=true,
   @_action_name="show",
   @_config={},
   @_db_runtime=0,
   @_lookup_context=
    #<ActionView::LookupContext:0x007fb64f6760d0
      @cache=true,
      @details=
        {:locale=>[:en],
        :formats=>[:html],
        :variants=>[],
        :handlers=>[:raw, :erb, :html, :builder, :ruby]},
      @details_key=#<Concurrent::Map:0x007fb64f697938 entries=0 default_proc=nil>,
      @prefixes=["posts", "application"],
      @rendered_format=:html,
      @view_paths=
        #<ActionView::PathSet:0x007fb64f675fe0

This post was helpful in explaining how a Struct works, but doesn't explain how one can confirm that they have a Struct.
Initially, when I started dissecting the present method, I found this answer to be helpful. However, I was thrown off by the comment, saying that the "ModelPresenter is initialized by passing the model, and the ApplicationHelper class", since ApplicationHelper is a module.

A: Summary:
use is_a?(Struct)
explanation:
A struct is a constructor for an anonymous class:
struct_class = Struct.new(:foo)
# => #<Class:0x007fa7e006ea98>

You can check that an instance of the anonymous class is a struct like so:
inst = struct_class.new
inst.class.superclass
# => Struct

However Object#is_a? checks the parent class as well as superclasses:
inst.is_a?(Struct)
# => true

You can see the same behavior in the following arbitrary example:
# inherits from String
anon_class = Class.new(String)

inst = anon_class.new
# => ""

inst.class == String
# => false

inst.is_a?(String)
# => true


text:
Q: MySQL: Error when running a Windowing query I am trying to execute a WINDOW query which is given below:
SELECT
DATE(ts),
oi,
avg(oi) OVER(PARTITION BY DATE(ts) )
FROM bybit_oi_1d_BTCUSD

It gives the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(PARTITION BY DATE(ts) )
FROM bybit_oi_1d_BTCUSD LIMIT 0, 25' at line 4

A: No Window functions until MySQL 8+ or MariaDB 10.2


text:
Q: 3Sum using python3 and enumarate I want to solve the following task using 'enumerate' in python3
The way enumerate works is demonstrated below
nums=(2,7,1,15)               # a tuple

for num in enumerate(nums):
        print(num, 'hello')

#output
#(0, 2) hello        #enumarate(nums) = (0,2)
#(1, 7) hello
#(2, 1) hello
#(3, 15) hello

for count, num in enumerate(nums):
        print(num, 'hello')

# Output
#2 hello    here count=0 but not displayed
#7 hello    here count=1 but not displayed
#1 hello    here count=2 but not displayed
#15 hello   here count=3 but not displayed

Using the above principle, given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = target sum? Find all unique triplets in the array which gives the sum = target sum.
A solution set for target sum =10  is:
[
  [0,1,2]
]

where num at 0th index+num at 1st index+num at 2nd index(7+2+1=10).

A: Do you have an idea for an algorithm to solve the problem?
I would probably do something like build up two dicts listing all the ways to use the array indexes make a sum with 1 number and 2 numbers to be a certain key value.
E.g., if I had been given nums = [2, 7, 1, 2, 3], I would write code to build up a table like:
one_sum = {1: [2],
           2: [0, 3],
           3: [4],
           7: [1]}

I would use a defaultdict from collections module to efficiently write this code (initialized as one_sum = defaultdict(list) above, though a set would also be a valid data structure for the problem).
It would be straightforward to use enumerate for this part; e.g.,
for i, n in enumerate(nums):
    one_sum[n].append(i)

Then I would then build up a two_sum table this time showing all pairs of indexes that make a certain sum.  Continuing with the example above, I would want to generate:
two_sum = {3: [(0, 2), (2, 3)],
           4: [(2, 4)],
           5: [(0, 4), (3, 4)],
           8: [(1, 2)],
           9: [(0, 1), (1, 3)],
          10: [(1, 4)]}

(Note one way to efficiently do this is to loop through the built up one_sum, but be careful not to re-use an index e.g., don't add (2,2) or (4,4) to two_sum[4] because while nums[2] + nums[2] does add up to 4, it uses an index twice (so isn't unique).  Also be careful not to double add indexes that are out of order.)
Finally I would loop through the one_sum dict, looking at indices that sum to k and then look in two_sum to see if there are any pairs of indices that sum to target-k, and if so then join the pairs together (checking to sort indices and not repeat indices in a tuple) having found a solution.
For a target of 10 this would ideally build up
three_sum = [(0,1,2), (1,2,3)]

# Note both were added from combining one_sum[1] with two_sum[9]
# nothing from combining one_sum[2] with two_sum[8] as they reuse indexes
# nothing from combining one_sum[3] as two_sum[7]==[]
# nothing new from combining one_sum[7] with two_sum[3] as (0,1,2) and (1,2,3) already present.

A: Here's a brute force method. It's not as efficient as this algorithm can be, mind you.
def f(nums, target):
    sols = []
    for i1, n1 in enumerate(nums):
        for i2, n2 in enumerate(nums[i1+1:]):
            for i3, n3 in enumerate(nums[i2+1:]):
                if (n1 + n2 + n3 == target):
                    sols.append([i1, i2, i3])
    return sols


text:
Q: how to retrieve multiple records (with all fields) of second entity which has n:n relationship with first entity in plug in in ms crm? I have two custom entities with N:N relationship.
1) Membership , 2) Offer
I have used subgrid on form of Membership and Offer to shows related records.
I am writing one plugin function where I have one membership entity record id as input and I want to get all related records of Offer entity as output.
I have tried following code but I couldn't get related offer entity records.
entity1 = "new_membership" , entity2 = "new_offer" , relationshipEntityName = "new_new_membership_new_offer"
public List<new_offer> getAllOffersFromMembership(string entity1,string entity2, string relationshipEntityName, string Id)
{
  QueryExpression query = new QueryExpression(entity1);
  query.ColumnSet = new ColumnSet(true);

  LinkEntity linkEntity1 = new LinkEntity(entity1, relationshipEntityName, "new_membershipid","new_membershipid", JoinOperator.Inner);
  LinkEntity linkEntity2 = new LinkEntity(relationshipEntityName, entity2, "new_offerid","new_offerid", JoinOperator.Inner);
  linkEntity1.LinkEntities.Add(linkEntity2);
  query.LinkEntities.Add(linkEntity1);

  linkEntity2.LinkCriteria = new FilterExpression();
  linkEntity2.LinkCriteria.AddCondition(new ConditionExpression( "new_membershipid", ConditionOperator.Equal, Id));

  EntityCollection collRecords = service.RetrieveMultiple(query);

  //To Do : Get offer entity records
}

As I am new in MS CRM, may be I am doing some silly mistakes.
Thanks in advance.

A: Invert your query to fetch related records.
var query = new QueryExpression("new_offer"){ColumnSet = new ColumnSet(true)};
var offerLinkEntity = new LinkEntity("new_offer", "new_new_membership_new_offer","new_offerid", "new_offerid", JoinOperator.Inner);

var memebershipLinkEntity = new LinkEntity("new_new_membership_new_offer", "new_membership","new_membershipid","new_membershipid", JoinOperator.Inner) {LinkCriteria = new FilterExpression()};

memebershipLinkEntity.LinkCriteria.AddCondition(new ConditionExpression("new_membershipid",ConditionOperator.Equal, mem.Id));

offerLinkEntity.LinkEntities.Add(memebershipLinkEntity);
query.LinkEntities.Add(offerLinkEntity);

var response = service.RetrieveMultiple(query);
var offers = response.Entities ?? Enumerable.Empty<new_offer>();


text:
Q: How to add a method to a class where the method name is based on an existing, annotated method in AspectJ? Consider this code:
class DatabaseCommands {

    @Privilege(ADMIN)
    public void delete(Something thingToDelete, User currentUser) {
        /* ... */
    }
}

Currently an access check is weaved into this method, to check if currentUser has the necessary rights to execute the database command (and throws an exception if not).
What do I have to add to my AspectJ file so that a new method
public boolean deleteAllowed(Something thingToDelete, User currentUser)

is added to the class, with the same access checks, but without the execution of the command?
This use case seems to be similar to the one of adding getters/setters to fields, like
class Foo {
    @Getter @Setter
    String name = ""
}

A: to my knowledge, unfortunately, it's not possible add methods (called Inter Type Declarations in AspectJ) using dynamic signatures, so there is no way to create methods based on names or parameters of another method.
@Setter @Getter is not implemented using AspectJ, but using other techniques. Spring Roo will actually inspect source code, and generate source for aspects, which will then be compiled and applied to original classes. Project Lombok and others use directly ASM, BCEL or APT to instrument Java bytecode. ASM is the same toolkit used by AspectJ itself to modify (Weave in AspectJ terminology) .class files, but when used directly is much more flexible (and much more complicated) than AspectJ. APT is Sun's Annotation Processing Tool, which since Java 6 is "embedded" in the Java compiler. It can be used to "intercept" the moment Javac is compiling a method or class having certain annotations, and can be used to "inject" new code, there including a getter/setter pair, or another new method.


text:
Q: Cannot import s3 i am trying to import s3 so i can use the code `conn = S3.AWSAuthConnection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) as used  here
but i get this error
  import s3
  File "C:\Users\abcedfghijk\Envs\myblog\lib\site-packages\s3__init__.py", line 1, in
    from .s3 import *
  File "C:\Users\abcedfghijk\Envs\myblog\lib\site-packages\s3\s3.py", line 253
    except Exception, e:
                    ^
SyntaxError: invalid syntax

please help out.. thanks

A: except Exception, e: is python2 syntax, which means you have installed s3.
pip3 install s3 says: UserWarning: This backport is meant only for Python 2.
The package you're looking for is boto3. Try:
$ pip3 install boto3
$ python3
>>> import boto3
>>> s3_client = boto3.client('s3')

A: This is Python2 syntax. This library seems old (Last released: May 27, 2015) and the blog post is even older (Published Aug 06, 2009). Either try running this with python2 or use boto (e.g. boto3.resource('s3'))


text:
Q: Incompatibility backgrounds css in IOS Mobile i developer a web site and when i open in IOS (Chrome or Safari) the resolution the background imgs break... TKS
CSS
 #home {
background: url('../images/fundo3.jpg') 50% 0 no-repeat fixed;*
background-size: cover;
background-position: center;
color: #5C5C5C;
display: -webkit-box
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
  -ms-flex-align: center;
       align-items: center;
height: 100vh;
text-align: center;}

.parallax-section {
background-attachment: scroll !important;
background-size: cover !important;}

footer {
background: url('../images/footer-bg.jpg')  fixed;
-webkit-background-size: cover;
background-size: cover;
background-position: center;
color: #ffffff;
padding-top: 80px;
padding-bottom: 80px;}

[1]: https://i.stack.imgur.com/zZVoD.jpg desktop
  [2]: https://i.stack.imgur.com/X5HWP.jpg ios

A: The solution is to create some mobile or iOS specific media queries and tweak the background image pixel size until you get a satisfactory size. Remember, you need high resolution graphics in order to get a nice result on newer iOS devices.
Code to tweak the size:
Replace
background-size: cover !important;}

With
background-size: 1500px,contain;


text:
Q: Method Replace, execution error 13 when strings are big In a old script, I use the method Replace for translate the excel sheets to an another language.
But now, I would replace some string but sometimes I get an execution error 13 "Type mismatch".
I noticed when the String is big (length >~ 400 characters), the method replace return this error.
By example, here I haven't problem :
Sheets(sheet).Cells.Replace "toto", "tata", xlWhole

But here :
Sheets(sheet).Cells.Replace "WWWWWWWWWWWW", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", xlWhole

I get the error "Type mismatch (Error 13)"
I tried to force the type of the data
var temp as string
temp = "AAAAAAAA...."

But it doesn't work...
Can I fix it ? Are there another solution ?
Thanks =)

A: Look at this answer :  dividing the string into smaller chunks of 250 chars and then treat them as "normal" string seems to do the trick.


text:
Q: Getting sporadic EOF error when sending multiple requests in Go Let me start by saying I'm new to Go and welcome any pointers/corrections.
I'm trying to write a small Go application which will create a number of DNS queries and send them out in respective Go routines. I get the URLs from a file of 1000 URLs and create a slice, for each URL in the slice I make a query for the A record and push the URL and elapsed time to a result channel if successful and if there is an error to a respective error channel. I then listen on a select.
What I'm struggling with is I will receive (seemingly randomly) an EOF error for some of my queries when using TCP and will receive i/o timeout error when using UDP. I would like to use TCP and ensure a response, I'm lost as to why I would be getting an EOF error. This also happens if I make 1000 queries to the same URL vs 1000 different URLs
Working on OSX and Go version 1.6
This is what I have so far:
package main

import (
    "bufio"
    "fmt"
    "github.com/miekg/dns"
    "os"
    "time"
)

// CHECK AND PRINT ERRORS
func checkErr(e error) {
    if e != nil {
        fmt.Println("Error: %s", e)
    }
}

// MAKES A SLICE OF URLS FROM TXT FILE
func urlSlice() []string {
    result := []string{}
    file, err := os.Open("topsites.txt")
    checkErr(err)
    defer file.Close()
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        result = append(result, scanner.Text())
    }
    return result
}

func makeQuery(target string) (string, error) {
    server := "8.8.8.8"
    // WILL RECIEVE EOF ERROR IF TCP - I/O TIMEOUT IF UDP
    c := dns.Client{Net: "tcp", Timeout: time.Duration(100 * time.Second)}
    m := dns.Msg{}
    m.SetQuestion(dns.Fqdn(target+"."), dns.TypeA)

    _, t, err := c.Exchange(&m, server+":53")
    if err != nil {
        return "", err
    }
    return "Url: " + target + " - - Took: " + t.String(), nil
}

func main() {
    start := time.Now()
    targets := urlSlice()
    resch, errch := make(chan string), make(chan error)
    for _, url := range targets {
        go func(url string) {
            res, err := makeQuery(url)
            if err != nil {
                errch <- err
                return
            }
            resch <- res
        }(url)
    }

    for i := 0; i < len(targets); i++ {
        select {
        case res := <-resch:
            fmt.Println(res)
        case err := <-errch:
            fmt.Println(err)
        }
    }
    elapsed := time.Since(start)
    fmt.Println("\ntotal time elapsed: ", elapsed)
}

Output:
Url: facebook.com - - Took: 548.582107ms
Url: wordpress.com - - Took: 548.805505ms
Url: google.com.br - - Took: 541.491363ms
Url: onclickads.net - - Took: 548.16544ms
Url: bongacams.com - - Took: 543.28688ms
Url: tianya.cn - - Took: 543.41525ms
Url: blogger.com - - Took: 544.461005ms
Url: alibaba.com - - Took: 543.53541ms
Url: gmw.cn - - Took: 543.56093ms
Url: pornhub.com - - Took: 664.297282ms
Url: outbrain.com - - Took: 664.423217ms
Url: ask.com - - Took: 671.557037ms
EOF
EOF
EOF
EOF
EOF
EOF
EOF
Url: t.co - - Took: 1.166130918s
Url: youth.cn - - Took: 1.946658912s
Url: apple.com - - Took: 2.763568935s

...continued...

total time elapsed:  23.703546858s

Thoughts, suggestions, and help all appreciated. Thanks!

A: This may be of interest: https://idea.popcount.org/2013-11-28-how-to-resolve-a-million-domains/
According to the article, the naive approach is limited by how many UDP sockets can be opened at the same time - around 1000.  I would assume the same is true for TCP sockets - you are going to run out of file descriptors or some other resource.
The author provides a link to his parallel dns resolver at the end of the article: https://github.com/majek/goplayground/blob/master/resolve/resolve.go
He uses a configurable number of go-routines all communicating over the same UDP port.  I am guessing if you want to use TCP you would have to use 1 tcp connection per go-routine (with number of go-routines well below 1000)


text:
Q: org.apache.catalina.realm.LockOutRealm.filterLockedAccounts An attempt was made to authenticate the locked user org.apache.catalina.realm.LockOutRealm.filterLockedAccounts An attempt was made to authenticate the locked user
i m unable to open tomcat login , can anyone tell me how to clear this log


text:
Q: Change cell colours on a google sheet via script? I have a sheet which is constantly updated ( via a script), containing a large amount of numbers.
To make the data easier to read, I would like to forat the cell colours, depending on the value of the cell to the immediate left.
green if higher
red if lower
amber if the same
So for example, if my cells contains;
10,20,100,5,5
20 would be green
100 would be green
5 would be red
16 would be amber
I have an existing script in place which is on a loop handling multiple sheets, so I would like to apply the formatting at the point the data is pasted into the cell;
Below is the portion of code which populates cells, and where I would like it to query the value of the cell to the immediate left.
for (var sheet of sheets) {
        //sheet.getRange(targetcell)
        //    .setValue('=--SPLIT(REGEXEXTRACT(JOIN(",",IMPORTDATA(B1)),"LCPrice"":""(.*)"), CHAR(34))')

            sheet.getRange(targetcell).setValue('=--SPLIT(REGEXEXTRACT(JOIN(",",IMPORTDATA(B1)),"LCPrice"":""(.*)"), CHAR(34))');
    SpreadsheetApp.flush();
    var range = sheet.getDataRange();
    range.copyTo(range, { contentsOnly: true });

Does anyone know if this is possible?


text:
Q: Knex client undefined Was hoping to see if anyone knows why this error is occurring? I am trying to deploy an app to digital ocean and everything was going well until this.
emphasized text/home/user/koala/server/node_modules/knex/lib/knex.js:33
  if (arguments.length === 0 || !config.client && !config.dialect) {
                                        ^

TypeError: Cannot read property 'client' of undefined
    at Knex (/home/user/koala/server/node_modules/knex/lib/knex.js:33:41)
    at Object.<anonymous> (/home/user/koala/server/db/connection.js:5:20)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/user/koala/server/components/account/accountController.js:1:82)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
[nodemon] app crashed - waiting for file changes before starting...


text:
Q: foreach(var item => model.xxxx) Null Exceptions I have gone through lot of posts however unable to resolve this issue.

*

*I input some values on the View and click the Submit button

*My repo calculates the payment schedule based on the criteria and displays the list (that's what I am trying to achieve)

This is where I am having issues.
On the initial load my Model is null and I get the null reference exception.
I have just started coding with asp so please ignore the basics in this case.
Any suggestions would be helpful
@model FinanceApplication.ViewModels.LoanViewModel
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {

                    Enter Price
                    @Html.TextBoxFor(model => model.Amount)

                    Enter Deposit
                    @Html.TextBoxFor(model => model.Deposit)

                    Finance Option

                        @Html.DropDownListFor(model =>
                            model.Term, new SelectList(Enum.GetValues(typeof(Options))),
                          "Select Option",
                          new { @class = "form-control" })

                    Delivery Date

                        @Html.EditorFor(model => model.Deliverydate)

                    Arrangement Fee
                    @Html.TextBoxFor(model => model.ArrangementFee)

                    Completion Fee
                    @Html.TextBoxFor(model => model.CompletionFee)

                        <input type="submit" id="btnSubmit"
                               value="Submit" onclick="myFunction();" />

Payment Schedule

                Amount (£)
                @Html.DisplayFor(model => model.Amount)

                Loan Amount (£)
                @Html.DisplayFor(model => model.LoanAmount)

                Deposit (£)
                @Html.DisplayFor(model => model.Deposit)

                Term (years)
                @Html.DisplayFor(model => model.Term)

                Delivery Date
                @Html.DisplayFor(model => model.Deliverydate)

                                Payment Date
                                Payment Amount (£)
                                Total Paid (£)
                                Balance (£)

                            if(Model != null)
                            {
                                @foreach (var item in Model.PaymentSchedule)
                                {

                                     @Html.DisplayFor(modelItem =>
                                                  item.PaymentDate)
                                     @Html.DisplayFor(modelItem =>
                                                  item.PaymentAmount)
                                     @Html.DisplayFor(modelItem =>
                                                  item.TotalPaid)
                                     @Html.DisplayFor(modelItem =>
                                                  item.RemainingBalance)

                                }
                            }
                            else
                            {

                                No Items found

                            }

    }

 {
     private IPaymentScheduleRepository _paymentScheduleRepository;

     public HomeController(IPaymentScheduleRepository paymentScheduleRepository)
     {
     _paymentScheduleRepository = paymentScheduleRepository; }

     [HttpGet]
     public IActionResult Index()
     { return View(new LoanViewModel()); }

     [HttpPost]
     public async Task<IActionResult> Index(LoanViewModel requestParameters)
     { LoanViewModel output = await _paymentScheduleRepository.GetPaymentSchedule(requestParameters);
         return View("Index", output);}}

//ViewModel
public class LoanViewModel
{
    [Required(ErrorMessage = "Please enter the loan amount.")]
    [Range(1, 100000000,
      ErrorMessage = "Loan amount must be between 1,000 and 1000,000.")]
    public decimal Amount { get; set; }

    [Required(ErrorMessage = "Please enter the deposit amount.")]
    [Remote(action: "VerifyDeposit", controller:"Home")]
    public decimal Deposit { get; set; }

    [Required(ErrorMessage = "Please select the term of the loan.")]
    public string Term { get; set; }

    [Required(ErrorMessage = "Please select the delivery date.")]
    [DataType(DataType.Date)]
    [Display(Name = "Delivery Date")]
    [DisplayFormat(ApplyFormatInEditMode = true,
      DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime Deliverydate { get; set; }

    public decimal ArrangementFee { get; set; }

    public decimal CompletionFee { get; set; }

    public decimal LoanAmount
    {
        get { return (Amount - Deposit); }
    }

    [Display(Name = "Payment Schedule")]
    public List<SheduledPayments> PaymentSchedule { get; set; }
}

//PaymentSchedule
public class SheduledPayments
{
    public DateTime PaymentDate { get; set; }
    public decimal PaymentAmount { get; set; }
    public decimal RemainingBalance { get; set; }
    public decimal TotalPaid { get; set; }
}

A: On the initial load your view model returns null - hint.
You should have a method for loading the view i.e get and a method for posting the view i.e. post.
Depending on context you need to work with the model in both action methods.
Check this and post the action method on your initial load.

A: For the decimal values you can use the ?? operator, for the date you can use the ternary operator ?:
. . .
@Html.DisplayFor((modelItem => (item.PaymentDate == null ? new DateTime(1900,1,1):item.PaymentDate)))
@Html.DisplayFor(modelItem => item.PaymentAmount ?? 0)
. . .

see this for more informations.
Otherway If the problem is the first call, your model is not defined so you must initialize the parameters in the model constructor.


text:
Q: While Plotting x-y contour, it plot a single point I have tried many times to create an x and y plot.
Every time I get only a point, and not a contour which I want. It should be the arc of a circle or an ellipse.
My current Matlab code:
a = 8*pi/5;
u = 1;
z=0.15;

x = cosh(u)*sqrt(1 - (sin(a)*sin(a)*sinh(u)*sinh(u))/square((sqrt(1-z)*cosh(u) + cos(a))));

y= -1*((sinh(u)*sinh(u)*sin(a))/(sqrt(1-z)*cosh(u) + cos(a)));

plot(x,y,'o')

assume any value of u.

A: u is a scalar, so you are plotting single points.
Make u an array
a = 8*pi/5;
u = 1:0.02:2;    % Your u values as an array
z = 0.15;

And make your operations element-wise in the x and y calculations
x = cosh(u).*sqrt(1 - (sin(a).*sin(a).*sinh(u).*sinh(u))./square((sqrt(1-z).*cosh(u) + cos(a))));

y= -1.*((sinh(u).*sinh(u).*sin(a))./(sqrt(1-z).*cosh(u) + cos(a)));

Use a line style which isn't just a point (like 'o' is), for instance for a line with circles at each value you can use
plot(x,y,'-o')

Note: your x and y calculations give complex results for these values, and plot ignores imaginary parts of the inputs by default.

A: I forgot u should be an array to get the points in the plot
a = 8*pi/5;
% assigning an array from 1 to 2 with stepsize = 0.1
u = 1:0.02:2;
z = 0.15;

Since, u is an array the multiplication should be element-wise(.*)
x = cosh(u).*sqrt(1 - (sin(a).*sin(a).*sinh(u).*sinh(u))./square((sqrt(1-z).*cosh(u) + cos(a))));

y= -1.*((sinh(u).*sinh(u).*sin(a))./(sqrt(1-z).*cosh(u) + cos(a)));

% Ignoring the complex value since it only provide some phase
plot(abs(x),abs(y),'r');
hold on
plot(real(x),real(y),'g')
legend('abs values','real Values')


text:
Q: Problems with .SelectNodes not returning any nodes I have a problem with MSXML2.DOMDocument.SelectNodes function. My XML file looks like:
<?xml version="1.0" encoding="utf-8"?>
<Report xsi:schemaLocation="PCVManifestReport http://ritenetdb-prod.aodc.slb.com/ReportServer?%2FRITENETReports%2FPCVManifestReport&rs%3AFormat=XML&rc%3ASchema=True" Name="PCVManifestReport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="PCVManifestReport">
 <Tablix1>
   <Details_Collection>
     <Details Textbox24="CONTAINER" Serial_No="7345" Remarks="General transportation container.  Alternate codes are: Container, Container-Mini, Container-Modular, Container-Open, Container-Closed, Container-HalfHeight, Container-Food, Container-Box, Container-Skid, Basket, Pallet, Rack - Location to adjust Maintenance Events Certification Lifting, Cert-NDT etc as per Country/SLB standard applied." Item_Count="6" Transport_Index="234.60" Seal="" />
     <Details Textbox24="CONTAINER" Serial_No="28056-I" Remarks="General transportation container.  Alternate codes are: Container, Container-Mini, Container-Modular, Container-Open, Container-Closed, Container-HalfHeight, Container-Food, Container-Box, Container-Skid, Basket, Pallet, Rack - Location to adjust Maintenance Events Certification Lifting, Cert-NDT etc as per Country/SLB standard applied." Seal="" />
     <Details Textbox24="BUNKER" Serial_No="EXPS-SEW 14" Remarks="Explosive bunker used for wellsite storage and transport." Seal="" />
   </Details_Collection>
 </Tablix1>
 <Tablix2>
   <Details1_Collection>
     <Details1 Textbox60="">
       <Tablix3 Textbox40="CONTAINER,7345">
         <Details2_Collection>
           <Details2 Asset_Code="EQF-38" Serial_No1="38752" Remarks1="1-11/16 IN. DIA STEEL WEIGHT BAR, STD SERVICE. RATED TO 20000 PSI & 450 DEGF. LENGTH 48.4 IN., WEIGHT 30.4 LBS." Ship_Weight="0.00" Textbox47="No" />
           <Details2 Asset_Code="EQF-38" Serial_No1="GB3802" Remarks1="1-11/16 IN. DIA STEEL WEIGHT BAR, STD SERVICE. RATED TO 20000 PSI & 450 DEGF. LENGTH 48.4 IN., WEIGHT 30.4 LBS." Ship_Weight="0.00" Textbox47="No" />
           <Details2 Asset_Code="COL-TRX" Serial_No1="4702904" Remarks1="8 RING COLLECTOR, MADE BY TROLEX (third party) generally used in the North sea. Old FCC Part <NA>" Textbox47="No" />
           <Details2 Asset_Code="WPSA-BA" Serial_No1="153" Remarks1="1-11/16" Wireline Perforating Shock Absorber (WPSA-BA)" Textbox47="No" />
           <Details2 Asset_Code="PEH-EFA" Serial_No1="2528" Remarks1="PEH-EFA, HEAD, 1-3/8 FOR FLEX Weak Point" Ship_Weight="0.00" Textbox47="No" />
           <Details2 Asset_Code="PEH-EFA" Serial_No1="2535" Remarks1="PEH-EFA, HEAD, 1-3/8 FOR FLEX Weak Point" Ship_Weight="0.00" Textbox47="No" />
         </Details2_Collection>
       </Tablix3>
     </Details1>
   </Details1_Collection>
 </Tablix2>
</Report>

Header part of my file goes like this
Dim RITEmanifest As MSXML2.DOMDocument
Set RITEmanifest = New DOMDocument
RITEmanifest.async = False
RITEmanifest.Load("path to file")
RITEmanifest.setProperty "SelectionLanguage", "XPath"

So now I can browse through nodes the "hard-coded" way without any problems
For Each node In RITEmanifest.DocumentElement.ChildNodes(0).ChildNodes(0).ChildNodes
    Debug.Print node.Attributes.getNamedItem("Serial_No").value
Next

But using SelectNodes does not return any nodes
Debug.Print RITEmanifest.SelectNodes("Details").Length

Any idea why would that be?


text:
Q: Integral equation or what? Actually this is my own question.
Is there a way to solve:
$$\int_0^8x^r\,\mathbb{d}x=32$$
Even if, without compute the equation we already know from trial and error that the answer is $r=1$.
When i tried inputting that equation on wolfram alpha,
This is my input ->

∫[0,8]x^r dx=32

there are 2 answers: 2 real solutions (including about lambert W function form) and 1 real integer solution which is $1$.

A: You can simply solve the integral: $\displaystyle{\int_a^b x^r dx}=\left[\dfrac{1}{r+1}x^{r+1}\right]_a^b$.
This results in $4(r+1)=8^r$. Now if you plot the function $r\longmapsto 8^r$, e.g. on WolframAlpha, then you will see that its graph crosses the line $r\longmapsto 4(r+1)$ twice.

A: If $r=-1$ then the integral diverges, and if $r\neq-1$ we get
$$32=\int_0^8x^r\,{\rm d}x=\left[\frac{x^{r+1}}{r+1}\right]_0^8=\frac{8^{r+1}}{r+1}.$$
A bit of rearranging and setting $s:=-3\ln(2)(r+1)$ shows that this is equivalent to
$$se^s=-\frac{3\ln2}{32}.$$
By definition of the Lambert $W$ function(s) the solutions to this equation are precisely the values of
$$W_k\left(-\frac{3\ln2}{32}\right),$$
whenever this is defined, as $k$ ranges over the integers. Because the argument $-\tfrac{3\ln2}{32}$ is a negative real number (greater than $-e^{-1}$), these values are real numbers only for $k=0$ and $k=-1$. This yields the solutions
$$W_0\left(-\frac{3\ln2}{32}\right)\approx0.966495\ldots
\qquad\text{ and }\qquad
W_{-1}\left(-\frac{3\ln2}{32}\right)=1.$$


text:
Q: How to open a tab with jquery-ui I´m trying to open a tab using jquery, here is my code:
$("#ecContenedorFolders").tabs({
     tabTemplate: "
#{label}
"
});
$("#ecContenedorFolders").tabs("add","#ecApp05","Friends Discussions");

As everyone can see i´m using a template, so when i use the 1st 3 lines i get my new tab, but i can switch between prevoius tabs, if i only use the last line i get my new tab, i can switch between tabs, but i can add content. ¿Does anyone knows a way to improuve this code?
Thanks in advance.

A: What you need is to include panelTemplate along with your tabTemplate. Something like this:
$("#ecContenedorFolders").tabs({
  tabTemplate: "
#{label}
",
  panelTemplate: "
Panel Text here
"
});

$("#ecContenedorFolders").tabs("add", "#ecApp05", "Friends Discussions");

Hope this helps!


text:
Q: Android, Twitter, 'FOLLOW US' I am building an android application and I am stuck at one place. I have integrated Twitter in my app using twitter4j, signpost apis. I am successful in writing code for putting text in user profile but I also want the user to follow my app when they click 'follow us on twitter' button.
Can anybody give me reference or guidance of writing such code?

A: What you are probably looking for is createFriendship()
You can see how it is used here
2016 Edit: Google code svn is broken and twitter 4j has moved
http://twitter4j.org/en/api-support.html


text:
Q: Reading mass storage device : Mac failed, Windows succeed. NOT FORMAT ISSUES My question is different and is not an easy one. Please help me. Thank you so much.
Information on my storage device :
2TB, 1TB for exFAT, 1 TB for NTFS.
USB 3.0

Everything WAS working FINE until today when SUDDENLY my Mac OS X can't read my seagate mass storage device anymore. When I attached it to my Mac, it did mounted correctly. However, when I double clicked its icon to access the contents of its filesystem, the Finder of Mac went not responding. So I switched to access its contents through command line and type the following commands:
cd /Volumes/myDevice
ls # here I did get the informations of the items under the root directory
cd aFolder # here I tried to enter a sub-directory, but the shell went not responding, just like the Finder.

So I doubted if the filesystem on my mass storage device was corrupted. But when I attached it to a Windows 10 PC, everything works fine. I don't know why Mac failed.
I tried the safe mode of Mac, and it did not help. When I was about to give up and format that mass storage device on Mac through device utilities, it gave me the unexpected information that it can not open the device. I tried to work around this by accessing this device on the Windows 10 virtual machine on my Mac, but it failed and did not work like a Windows 10 PC.
Now I am totally lost. I haven't try the method to entirely format the device on another PC because I think this may be fixable. However, I did try to format one partition, and Mac can't access it either. So I try a entirely different USB device formatted in FAT32, and Mac can access it.
Now I am totally lost. I don't know why Finder went not responding. Any ideas? Thanks so much. I am using Mac OS X Yesomite 10.10.5.


text:
Q: Cannot move file because NoSuchFileException I use this code to list files into directory and move it based on a found value.
    @Override
    public void execute(JobExecutionContext context) {

        File directoryPath = new File("C:\\csv\\nov");
        // Create a new subfolder called "processed" into source directory
        try {
            Path processedFolderPath = Path.of(directoryPath.getAbsolutePath() + "/processed");
            if (!Files.exists(processedFolderPath) || !Files.isDirectory(processedFolderPath)) {
                Files.createDirectory(processedFolderPath);
            }

            Path invalidFilesFolderPath = Path.of(directoryPath.getAbsolutePath() + "/invalid_files");
            if (!Files.exists(invalidFilesFolderPath) || !Files.isDirectory(invalidFilesFolderPath)) {
                Files.createDirectory(invalidFilesFolderPath);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        FilenameFilter textFileFilter = (dir, name) -> {
            String lowercaseName = name.toLowerCase();
            if (lowercaseName.endsWith(".csv")) {
                return true;
            } else {
                return false;
            }
        };
        // List of all the csv files
        File filesList[] = directoryPath.listFiles(textFileFilter);
        System.out.println("List of the text files in the specified directory:");

        for(File file : filesList) {

            try {
                try (var br = new FileReader(file.getAbsolutePath(), StandardCharsets.UTF_16)){
                    List<CsvLine> beans = new CsvToBeanBuilder(br)
                            .withType(CsvLine.class)
                            .withSeparator('\t')
                            .withSkipLines(3)
                            .build()
                            .parse();

                    for (CsvLine item : beans)
                    {
                        Path originalPath = file.toPath();
                        if(item.getValue().equals(2)
                        || item.getValue().equals(43)
                        || item.getValue().equals(32))
                        {
                            // Move here file into new subdirectory when file is invalid
                            Path copied = Paths.get(file.getParent() + "/invalid_files");
                            try {
                                // Use resolve method to keep the "processed" as folder
                                br.close();
                                Files.move(originalPath, copied.resolve(originalPath.getFileName()), StandardCopyOption.REPLACE_EXISTING);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                    }}
            } catch (Exception e){
                e.printStackTrace();
            }
            Path originalPath = file.toPath();
            System.out.println(String.format("\nProcessed file : %s, moving the file to subfolder /processed\n",
                    originalPath));
        }

        // Move here file into new subdirectory when file processing is finished
                            Path copied = Paths.get(file.getParent() + "/processed");
                            try {
                                // Use resolve method to keep the "processed" as folder
                                br.close();
                                Files.move(originalPath, copied.resolve(originalPath.getFileName()), StandardCopyOption.REPLACE_EXISTING);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
    }

The problem is that I try to move a file. I get error:

java.lang.RuntimeException: java.nio.file.NoSuchFileException: C:\csv\nov\12_21_39.csv
      at com.wordscore.engine.processor.DataValidationCheckJob.execute(DataValidationCheckJob.java:94)
      at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
      at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
    Caused by: java.nio.file.NoSuchFileException: C:\csv\nov\12_21_39.csv

How I can edit the code in way that it can be moved properly?

A: It looks like you have omitted break; after both Files.move(originalPath, ...); calls.
Without a break to exit the for (CsvLine item : beans) loop, processing continues over the next iteration. The second iteration will attempt to perform Files.move(originalPath, ...) again - and fails because the file has already been moved.
Therefore you get the NoSuchFileException which you have re-thrown as RuntimeException in your try.. Files.move .. catch block.
The handling would be cleaner if you dealt with move in one place and such that it avoids the untidy br.close(), leaving file handling to the auto-close try() block. Something like this:
Path invalidDir = Paths.get(file.getParent() + "/invalid_files");
Path processedDir = Paths.get(file.getParent() + "/processed");
for(File file : filesList) {

    Path originalPath = file.toPath();
    Path moveTo = processedDir.resolve(originalPath.getFileName());

    try (var br = new FileReader(file.getAbsolutePath(), StandardCharsets.UTF_16)){
        List<CsvLine> beans = new CsvToBeanBuilder(br)
                .withType(CsvLine.class)
                .withSeparator('\t')
                .withSkipLines(3)
                .build()
                .parse();

        for (CsvLine item : beans) {
            if(item.getValue().equals(2)
            || item.getValue().equals(43)
            || item.getValue().equals(32)) {
                // file is invalid, skip it
                moveTo = invalidDir.resolve(originalPath.getFileName());
                // LOG MSG HERE
                break;
            }
        }
    }
    Files.move(originalPath, moveTo, StandardCopyOption.REPLACE_EXISTING);

    System.out.format("%nProcessed file : %s, moving the file to subfolder %s%n", originalPath, moveTo);
}


text:
Q: Sticky footer with the flexible box layout model? I am trying to implement a sticky footer with the flexible box layout model as implemented in recent versions of Chrome and Firefox.
Given this markup inside the body element:
<header>
    HEADER
</header>

<div>
    CONTENT
</div>

<footer>
    FOOTER
</footer>

my idea is to use the following CSS:
html,
body {
    height: 100%;
}

body {
    margin: 0;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-direction: column;
    flex-direction: column;
}

div {
    -webkit-flex: 1;
    flex: 1;
}

footer {
    background-color: yellow;
}

This works fine as long as the content is less than 100% of the viewport height. When the content becomes larger, however, Chrome 28 begins to paint the footer on top of the content. Is it buggy behaviour (and if: how can I workaround it) or is my CSS wrong?
You can test Chrome's behaviour here: http://jsfiddle.net/SYmJp/.
Firefox does display the thing as intended. As does Chrome/Chromium 25/26.
If this is a regression in recent Chrome versions, is the bug already reported?
ADDED
The apparent error persists in Chrome 29.

A: Change height to min-height: http://jsfiddle.net/n4rv8xws/
This fixed it for me in Chrome 39:
html,
body {
    min-height: 100%;
}

I agree with your assertion that this is a Chrome regression.


text:
Q: Perimeter decreases under intersection with half spaces The main thing i need to prove is the following assertion:
Let $E\subset R^N$ be a set of finite perimeter and $H=\{x\in R^N : x\cdot e < t  \}$ for $t\in R$ and $e\in S^{N-1}$.
Then prove that  $$ \text{Per}(E\cap H)\leq\text{Per}(E), $$
by using the following decomposition of the Gauss Green measure of $E\cap H$
$$ \mu_{E\cap H}= (\mu_{E})_{|_{H}} + e H^{N-1}_{|_{E\cap\partial H}}. $$
For the convenience of the reader i recall that  E  is of locally finite perimeter if there exists a vector-valued Radon measure $\mu_E$ such that  $\int_{E} \text{div}Tdx=\int_{R^N} T\cdot d\mu_E$ for every smooth compactly supported vector field $T$, in this case $\text{Per}(E;A)=|\mu_E|(A)$.
The hint of the book is the following: Use the recalled decomposition with the vector field $T(x)=e$ for each $x$ (clearly a truncation argument is required).
My attempt is like the following, i consider $T_M(x)= \phi(|x|)e$ ($M>0$) where $\phi\in C^{\infty}(R)$ is such that $\phi=1$ on $(-\infty, M]$ and $\phi=0$ on $[M+1,\infty)$. Using this vector field in the decomposition and passing to the limit for $M\to\infty$ i can get easily
$$H^{N-1}(E\cap \partial H)\leq \text{Per}(E;H). $$
I can't fine out how to prove the derired inequality


text:
Q: java EasyMock ignore calls to an object from TestedClass' methods I have a class where I have an object. I am testing a method that calls this object, but it the object has nothing to do with my test, so I'd like to ignore it.
Class TestedClass {
 ObjectX obj;

  method() {
   /* some processing */
   obj.someMethod().otherMethod(lotofparameters);  /* i want to ignore this line in my test */
  }
}

So I want to test the method() without calling those methods on obj with parameters.
Thank u

A: Mock it using the createMock method. Then use the anyTimes method to basically ignore any calls to it.
expect(objMock.someMethod())
        .andReturn(42).times(3)

I threw in a return in case you needed it for something. Check out their documentation for more.
EDIT (to address the first comment)
Make someMethod return another mock. Then mock otherObj.otherMethod. As for the parameters, consider using the matchers listed in the documentation I linked to. You can even make your own matcher, so maybe that can help solve your issue.


text:
Q: Measuring an enterprises reliance upon software In bidding a complex project for a client, I wanted a way to determine their reliance upon software. They have many people doing manual entry and Excel spreadsheets power many pieces as well as legacy code and some off the shlef solutions that do not interact in any way.
Its one thing to say "You need software to run your business" but how do you create a measure of this to be able to say something like "You are currently 68% reliant upon software" its time to take it seriously before the expanding complexity costs more to maintain than to re-write?

A: Reliance on software?  Surely you're kidding.  Unless you're working in mining, fishing, forestry or agriculture, it's usually 100%.
Turn the power off in the office and see how long they can work with flashlights and candles.  Also, turn off everything on the factory floor that's not a light or a manual power tool.
Simply walk around and watch people work.  If it involves electricity for anything more than power tools or lighting, there's a computer involved.
Take away their cell-phones, too, while you're at it.

A: Mike,
I think the issue that Scott has with your question is that without knowing at least the industry in question, the generic term "software" isn't sufficient.  If instead you mean, their reliance upon home grown software vs COTS (commercial off the shelf), or free solutions then you have a bit more of a platform for a good question.
What I would consider is that they're probably only interested in the bottom line.  Figure out which percentage of their business model functions without any computer interaction.  If 100% of their daily business is computer free, but they use a financial suite to track expenses, then try to estimate how much that task would cost if they couldn't use the software.  Add that amount to their yearly income, and recalculate it's percentage.  It's going to be a swag no matter which way you shake it.
Anyways, best of luck on this one... I don't envy you :)
Adam Carstensen
www.mobiusbay.com


text:
Q: Copy previous line to current line from text file I have a file with lines, just like this:
A
B
C

I want to create a duplicate file in bash that contains each line merged with the copy of next line, like:
A;B
B;C
C;

A: $ sed 'x;G;s_\n_;_;1d;${p;x;s_$_;_;}' file
A;B
B;C
C;

What that sed expression is doing:

*

*x: save the incoming line in hold space, and retrieve the previous one

*G: append the new line (from hold space) to the old one

*s_\n_;_: replace line-break with a ;.

*1d: if this is the first line, delete it (don't print it) and advance to next

*${...;}: if this is the last line...

*p: first print the joined pair

*x: retrieve the final line

*s_$_;_: append final ;

A: Somewhat simpler sed solution without hold space:
sed '$!N;y/\n/;/;p;y/;/\n/;D' file

*

*$!N to join next line (if any; the $! is not needed with GNU sed when not in POSIX mode)

*y/\n/;/ replace the newline with ;

*print the resulting line

*y/;/\n/ to change back to newline, so with

*D you can get rid of the first line and continue with the next one

A: Same basic idea as the awk solution given by Torin:
$ perl -lne 'print "$last;$_" if defined $last; $last=$_;END{print "$last;" if $.}' file
A;B
B;C
C;

Or, if you're into the whole brevity thing:
$ perl -lne'$.>1?print"$l;$_":1;$l=$_}{print"$l;"if$.' file
A;B
B;C
C;

A: A Vim Solution
One can issue this command (credit to Conspicuous Compiler for suggesting this):
vim "+%s/\n\(.\+\)*/;\1\n\1" sample.txt

Alternatively and probably more customarily, start Vim and open the file and issue the ex command:
:%s/\n\(.\+\)*/;\1\n\1

Explanation:
Substitute the pattern:

*

*the new line character,\n

*a character group,\(.+\), which composes the entire next line. The quantifier which follows, *, just indicates that there can be zero or more matches

with the following:

*

*a semicolon

*followed by a reference to the character group, \1

*followed by the new line character, \n

*followed by a second reference to the character group, \1.

Before:

After:

A: $ perl -lp -0777e 's/\n(?=(.*\n?))/;$1/g'  input.txt

A: Using awk:
awk 'prev{ print prev ";" $0 }
     { prev = $0 }
     END { if (NR) print prev ";" }'

which with your input, gives
A;B
B;C
C;

A: Quick'n'dirty way (involves reading the file twice):
$ tail -n+2 file | paste -d';' file -
A;B
B;C
C;


text:
Q: MVC: How to make multiple requests share a List of Images I created a controller for retrieving images from my database, and sucessfully retrieved images with this:
public class ImageController : Controller
{
    [Route("user/{userId:int}/profile", Name = "GetUserProfileImage")]
    public ActionResult UserProfileImage(int userId)
    {
        using (var imgRepo = new ImageRepository())
        {
            UserProfileImage img = imgRepo.GetUserImage(userId);
            return File(img.Image, "image/jpg");
        }
    }
}

The ImageRepository instantiates a DBContext when it's created, and disposes the DBContext when it's disposed.
Therefore I have a view displaying a list of users, and for each user I show their picture like this:
@model IEnumerable<UserRankingViewModel>

            #

            @Html.DisplayNameFor(modelItem => modelItem.First().Name)

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.RankingPosition)

                    @Html.DisplayFor(modelItem => item.Name)

    }

Where @item.ImageUrl is an Url to GetUserProfileImage route. If I was to list 50 users, then 50 requests would be made to that route, and I guess 50 times the DBContext would be queried for an User Image.
For this particular case, is it possible to store a List of UserProfileImage in memory to avoid querying database everytime? Is this a bad practice? If Yes, why?
In my situation, there is no other application/webservice which could change database data other than this, so if a user updates their picture, I could check if is there any in memory picture in that List and update it, besides updating database.

A: Try to load all images into your model as byte64, and show directly in view.
In your code, what is UserProfileImage? what king for UserProfileImage.Image?
You can try;
class UserRankingViewModel
{
    ... ...
    public string ImageBase64 {get;set;}
}

class yourController: Controller
{
    public IActionResult YourMethodForLoadUserRunk()
    {
        .... ....
        //here you can load image from dbcontext (memorystream for ex)
        //and convert to array
        var user = new UserRankingViewModel();
        var string64 = Convert.ToBase64String(yourimage.ToArray());
        user.ImageBase64 = String.Format("data:image/gif;base64,{0}", string64);
        ....
        ....
    }
}

So in your View:
@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.RankingPosition)

                @Html.DisplayFor(modelItem => item.Name)

}


text:
Q: Kohana event system in Erlang? I want to implant a framework in Erlang that is similar to Kohana event system. Anyone know how to do that or have any idea? I really like how Kohana is structured.
EDIT
The Kohana event system have been documented here : http://docs.kohanaphp.com/general/events . If I understand it correctly, I can replicate Kohana in Erlang like this:
kohana.erl
event.erl
router.erl
profiler.erl
[system (a directory)]
ready.erl
routing.erl
execute.erl
post_routing.erl
404.erl
pre_controller.erl
post_controller_constructor.erl
post_controller.erl
send_headers.erl
display.erl
shutdown.erl
log.erl
redirect.erl
I'm not sure whether this is better than Python wsgi like Django middleware and there is already ewgi for Erlang. I just want to make a framework for fun. I'm more familiar with Kohana 2 but interested in implanting HMVC or Kohana 3 for erlang.

A: Basically the event system in kohana is just a collection of functions/methods to run at a future point in time. I don't know anything about Erlang, but if you can write a collection class, and put function/method callbacks into it, it should be trivial to port the event system over.


text:
Q: SQL: How to check if foreign key was really changed I had FK with wrong constraints and I have to change it:
ALTER TABLE user_login_logout_fact DROP CONSTRAINT user_fk;

ALTER TABLE user_login_logout_fact
  ADD CONSTRAINT user_fk FOREIGN KEY (user_id)
      REFERENCES uuser (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED;

There's no problem with it, but I have to apply this using patch file with checking if it was applied already. So I have to create function like this:
CREATE FUNCTION tryUpgrade(patch varchar) RETURNS integer AS $$
    DECLARE testRecord RECORD;
    BEGIN
        RAISE NOTICE 'checking %', patch;
        SELECT INTO testRecord * FROM patchlog where basename = patch;
        IF FOUND THEN
            RAISE NOTICE 'patch % has already been applied', patch;
            RETURN 0;
        END IF;

    //check if constraints are ok
    IF ok THEN
        RAISE NOTICE 'upgraded but not noted';
        INSERT INTO patchlog VALUES (patch, now());
        RETURN 0;
    END IF;

    SELECT INTO testRecord upgrade(); //this function will alter table
    INSERT INTO patchlog VALUES (patch, now());
    RAISE NOTICE 'upgraded';
    RETURN 1;
END;
$$ LANGUAGE plpgsql;

So, the question is - how to check if FK will use ON DELETE CASCADE but not old NO ACTION?

A:
How to check if FK will use ON DELETE CASCADE but not old NO ACTION?

You can check the confdeltype in the system catalog table pg_constraint. The manual:

Foreign key deletion action code: a = no action, r = restrict, c = cascade, n = set null, d = set default

In PL/pgSQL code use it like:
IF EXISTS (
   SELECT FROM pg_constraint
   WHERE  conname = 'user_fk'
   AND    conrelid = 'user_login_logout_fact'::regclass
   AND    confdeltype = 'c'
  ) THEN
  -- all done
ELSE
  -- run ALTER TABLE ...
END IF;

Table name can optionally be schema-qualified. See:

*

*How do I speed up counting rows in a PostgreSQL table?
Information schema versus system catalog
As you answered yourself, the same can be achieved by querying the information schema, which adheres to an SQL standard.
However:

*

*Not all major RDBMS implement it. Oracle doesn't, for one.

*The information schema is implemented with (sometimes hugely complex) views (not tables), which make look-ups a lot slower than accessing tables in pg_catalog directly. A quick test in a real live db showed factor 10 for the example at hand. I have seem factor 1000 and more.

*The aim of using the information schema is often to keep your implementation "portable". But this hardly ever works to begin with. The various RDBMS are just too far from the SQL standard in too many ways.
There is another benefit, though: Postgres does not assert anything concerning the structure of tables in pg_catalog across major versions. By using the information schema, one would be on the safe side across major versions of Postgres.
However, basic structures hardly change. While possible, it is rather unlikely, that a query like this would break in a future version.
See:

*

*How to check if a table exists in a given schema

*Related answer on dba.SE discussing "Information schema vs. system catalogs"

A: Also, second solution whitch is seems to be less postgresql-specific.
Info about foreign keys stores in referential_constraints table:
SELECT * FROM information_schema.referential_constraints
WHERE CAST(constraint_name AS TEXT) LIKE 'user_fk'
    AND delete_rule LIKE 'CASCADE'
    AND update_rule LIKE 'CASCADE';


text:
Q: k3s without HA: how to switch master node? Rancher documentation on k3s is quite nice and its HA support (both with external DB or embedded etcd) look nice, but I don't want/need an HA setup.
In case my master node fails, I don't mind having downtime while I re-create it or make a master out of another one, but I cannot find documentation how to switch master node.
Which files should I backup regularly (or host in NFS mount which is what I want to do) so I can easily re-setup the cluster with another server node but with the exact same state?
For the initial setup, we do:

*

*master: curl -sfL https://get.k3s.io | sh

*worker: curl -sfL https://get.k3s.io | K3S_URL=\"https://${MASTER_IP}:6443\" K3S_TOKEN=\"${TOKEN}\" sh -s
If I just re-run the scripts choosing another master, I'll have all the state lost. Is there a single directory I can copy/preserve (and an argument to pass to script to re-use it)?


text:
Q: Super fish hover on page load Hi I am using jquery superfish and I need active(hover) first menu item on page load but on hover another menu item cancel that hover on first item. Any suggestion?
This is html code for menu

venkovní plochy

                    120m2

venkovní plochy

                    120m2

my website sis here http://www.manko-design.cz/demo/ its not working how I need. I need this. When I move cursor on another image in that row script remove class from first image. If I move out cursor from image to out from image but not on another image in row last hover image stay hover.

A: You can make the last hovered li>ul element always visible by attaching a class .current to it and forcing its opacity and display properties as follows:
Javascript:
$(document).ready(function(){
    $('ul.sf-menu').superfish();
    var last_hover = $('.sf-menu>li:first');
    $('ul.sf-menu>li').hover(function () {
        last_hover.removeClass('current');
        last_hover = $(this);
        last_hover.addClass('current');
    }, function(){
    });
});

CSS:
.current > ul {
    display:block !important;
    opacity:1 !important;
}

fiddle


text:
Q: WPF DocumentViewer is slower than Microsoft XPS viewer I'm dealing with problem to show dwfx (auto cad) files in our WPF application. I'm using XpsDocument to show such a files.
Problem is lack of performance in case of more complex files. Sometime containing thousands of shapes, despite the fact we advise customers to export it as simple as they can.
By lack of performance I mean scroll and zoom when compared to Microsoft XPS viewer which opens this kind of files by default.
Have anybody experience with this? Can I achieve same scroll and zoom experience in WPF document viewer as I can see in Windows XPS viewer?
Sample file: https://1drv.ms/u/s!AhKm-nEB-Yrths4rY7b0V2rAWE4y1g (444 kB)
And this is how to show it in wpf app. xaml:
<Window x:Class="WpfApplication10.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Width="525"
        Height="350">
    <Grid>
        <DocumentViewer x:Name="dv" />
    </Grid>
</Window>

Code behind:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var file = @".\Plan-04.dwfx";
        using (XpsDocument xpsDocument = new XpsDocument(file, FileAccess.Read))
            dv.Document = xpsDocument.GetFixedDocumentSequence();
    }
}


text:
Q: Issue with OnCollisionEnter2D - No error messages but no result first time posting here so apologies if I get anything wrong. I've written a chunk of code meant to check if the attached object is touching another object with the tag "hazard". If it is then the value of the float "hp" will be reduced by 1. No error messages are present when I run my game but when I run my game and touch an object tagged "hazard" with my player character hp isn't effected - I know this because I successfully implemented a health bar which doesn't change at all when I touch an object with the tag.
Below is the code I have written to detect the collision and reduce the value of hp.
void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag =="hazard")
        {
          hp = hp - 1;
        }
    }

Both the player character object and hazard objects have 2D Collider components attached.
Upon request the code for the health has been added below:
This code sets the initial value of "hp" and declares the game objects that I later use to represent the remaining health of the player.
float hp = 10;
   public GameObject phealth1;
   public GameObject phealth2;
   public GameObject phealth3;
   public GameObject phealth4;
   public GameObject phealth5;
   public GameObject phealth6;
   public GameObject phealth7;
   public GameObject phealth8;
   public GameObject phealth9;
   public GameObject phealth10;

This code prevents "hp" from going above or below the maximum and minimum values as well as updating the health bar based on the value of "hp".
 void Update()
{

    if (hp > 10)
        hp = 10;

    if (hp < 0)
        hp = 0;

    switch (hp) {
        case 10:
            phealth1.gameObject.SetActive(true);
            phealth2.gameObject.SetActive(true);
            phealth3.gameObject.SetActive(true);
            phealth4.gameObject.SetActive(true);
            phealth5.gameObject.SetActive(true);
            phealth6.gameObject.SetActive(true);
            phealth7.gameObject.SetActive(true);
            phealth8.gameObject.SetActive(true);
            phealth9.gameObject.SetActive(true);
            phealth10.gameObject.SetActive(true);
            break;
        case 9:
            phealth1.gameObject.SetActive(true);
            phealth2.gameObject.SetActive(true);
            phealth3.gameObject.SetActive(true);
            phealth4.gameObject.SetActive(true);
            phealth5.gameObject.SetActive(true);
            phealth6.gameObject.SetActive(true);
            phealth7.gameObject.SetActive(true);
            phealth8.gameObject.SetActive(true);
            phealth9.gameObject.SetActive(true);
            phealth10.gameObject.SetActive(false);
            break;
        case 8:
            phealth1.gameObject.SetActive(true);
            phealth2.gameObject.SetActive(true);
            phealth3.gameObject.SetActive(true);
            phealth4.gameObject.SetActive(true);
            phealth5.gameObject.SetActive(true);
            phealth6.gameObject.SetActive(true);
            phealth7.gameObject.SetActive(true);
            phealth8.gameObject.SetActive(true);
            phealth9.gameObject.SetActive(false);
            phealth10.gameObject.SetActive(false);
            break;
        case 7:
            phealth1.gameObject.SetActive(true);
            phealth2.gameObject.SetActive(true);
            phealth3.gameObject.SetActive(true);
            phealth4.gameObject.SetActive(true);
            phealth5.gameObject.SetActive(true);
            phealth6.gameObject.SetActive(true);
            phealth7.gameObject.SetActive(true);
            phealth8.gameObject.SetActive(false);
            phealth9.gameObject.SetActive(false);
            phealth10.gameObject.SetActive(false);
            break;
        case 6:
            phealth1.gameObject.SetActive(true);
            phealth2.gameObject.SetActive(true);
            phealth3.gameObject.SetActive(true);
            phealth4.gameObject.SetActive(true);
            phealth5.gameObject.SetActive(true);
            phealth6.gameObject.SetActive(true);
            phealth7.gameObject.SetActive(false);
            phealth8.gameObject.SetActive(false);
            phealth9.gameObject.SetActive(false);
            phealth10.gameObject.SetActive(false);
            break;
        case 5:
            phealth1.gameObject.SetActive(true);
            phealth2.gameObject.SetActive(true);
            phealth3.gameObject.SetActive(true);
            phealth4.gameObject.SetActive(true);
            phealth5.gameObject.SetActive(true);
            phealth6.gameObject.SetActive(false);
            phealth7.gameObject.SetActive(false);
            phealth8.gameObject.SetActive(false);
            phealth9.gameObject.SetActive(false);
            phealth10.gameObject.SetActive(false);
            break;
        case 4:
            phealth1.gameObject.SetActive(true);
            phealth2.gameObject.SetActive(true);
            phealth3.gameObject.SetActive(true);
            phealth4.gameObject.SetActive(true);
            phealth5.gameObject.SetActive(false);
            phealth6.gameObject.SetActive(false);
            phealth7.gameObject.SetActive(false);
            phealth8.gameObject.SetActive(false);
            phealth9.gameObject.SetActive(false);
            phealth10.gameObject.SetActive(false);
            break;
        case 3:
            phealth1.gameObject.SetActive(true);
            phealth2.gameObject.SetActive(true);
            phealth3.gameObject.SetActive(true);
            phealth4.gameObject.SetActive(false);
            phealth5.gameObject.SetActive(false);
            phealth6.gameObject.SetActive(false);
            phealth7.gameObject.SetActive(false);
            phealth8.gameObject.SetActive(false);
            phealth9.gameObject.SetActive(false);
            phealth10.gameObject.SetActive(false);
            break;
        case 2:
            phealth1.gameObject.SetActive(true);
            phealth2.gameObject.SetActive(true);
            phealth3.gameObject.SetActive(false);
            phealth4.gameObject.SetActive(false);
            phealth5.gameObject.SetActive(false);
            phealth6.gameObject.SetActive(false);
            phealth7.gameObject.SetActive(false);
            phealth8.gameObject.SetActive(false);
            phealth9.gameObject.SetActive(false);
            phealth10.gameObject.SetActive(false);
            break;
        case 1:
            phealth1.gameObject.SetActive(true);
            phealth2.gameObject.SetActive(false);
            phealth3.gameObject.SetActive(false);
            phealth4.gameObject.SetActive(false);
            phealth5.gameObject.SetActive(false);
            phealth6.gameObject.SetActive(false);
            phealth7.gameObject.SetActive(false);
            phealth8.gameObject.SetActive(false);
            phealth9.gameObject.SetActive(false);
            phealth10.gameObject.SetActive(false);
            break;
        case 0:
            phealth1.gameObject.SetActive(false);
            phealth2.gameObject.SetActive(false);
            phealth3.gameObject.SetActive(false);
            phealth4.gameObject.SetActive(false);
            phealth5.gameObject.SetActive(false);
            phealth6.gameObject.SetActive(false);
            phealth7.gameObject.SetActive(false);
            phealth8.gameObject.SetActive(false);
            phealth9.gameObject.SetActive(false);
            phealth10.gameObject.SetActive(false);
            break;
    }

}

Below is the entire script.
    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Health : MonoBehaviour
{
   float hp = 10;
   public GameObject phealth1;
   public GameObject phealth2;
   public GameObject phealth3;
   public GameObject phealth4;
   public GameObject phealth5;
   public GameObject phealth6;
   public GameObject phealth7;
   public GameObject phealth8;
   public GameObject phealth9;
   public GameObject phealth10;

    // Start is called before the first frame update
    void Start()
    {

    }

    void dmg(int x)
    {
        hp = hp - x;
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "hazard")
            dmg(1);
            Debug.Log("Contact made");
            Debug.Log(hp);
    }

    // Update is called once per frame
    void Update()
    {

        if (hp > 10)
            hp = 10;

        if (hp < 0)
            hp = 0;

        switch (hp) {
            case 10:
                phealth1.gameObject.SetActive(true);
                phealth2.gameObject.SetActive(true);
                phealth3.gameObject.SetActive(true);
                phealth4.gameObject.SetActive(true);
                phealth5.gameObject.SetActive(true);
                phealth6.gameObject.SetActive(true);
                phealth7.gameObject.SetActive(true);
                phealth8.gameObject.SetActive(true);
                phealth9.gameObject.SetActive(true);
                phealth10.gameObject.SetActive(true);
                break;
            case 9:
                phealth1.gameObject.SetActive(true);
                phealth2.gameObject.SetActive(true);
                phealth3.gameObject.SetActive(true);
                phealth4.gameObject.SetActive(true);
                phealth5.gameObject.SetActive(true);
                phealth6.gameObject.SetActive(true);
                phealth7.gameObject.SetActive(true);
                phealth8.gameObject.SetActive(true);
                phealth9.gameObject.SetActive(true);
                phealth10.gameObject.SetActive(false);
                break;
            case 8:
                phealth1.gameObject.SetActive(true);
                phealth2.gameObject.SetActive(true);
                phealth3.gameObject.SetActive(true);
                phealth4.gameObject.SetActive(true);
                phealth5.gameObject.SetActive(true);
                phealth6.gameObject.SetActive(true);
                phealth7.gameObject.SetActive(true);
                phealth8.gameObject.SetActive(true);
                phealth9.gameObject.SetActive(false);
                phealth10.gameObject.SetActive(false);
                break;
            case 7:
                phealth1.gameObject.SetActive(true);
                phealth2.gameObject.SetActive(true);
                phealth3.gameObject.SetActive(true);
                phealth4.gameObject.SetActive(true);
                phealth5.gameObject.SetActive(true);
                phealth6.gameObject.SetActive(true);
                phealth7.gameObject.SetActive(true);
                phealth8.gameObject.SetActive(false);
                phealth9.gameObject.SetActive(false);
                phealth10.gameObject.SetActive(false);
                break;
            case 6:
                phealth1.gameObject.SetActive(true);
                phealth2.gameObject.SetActive(true);
                phealth3.gameObject.SetActive(true);
                phealth4.gameObject.SetActive(true);
                phealth5.gameObject.SetActive(true);
                phealth6.gameObject.SetActive(true);
                phealth7.gameObject.SetActive(false);
                phealth8.gameObject.SetActive(false);
                phealth9.gameObject.SetActive(false);
                phealth10.gameObject.SetActive(false);
                break;
            case 5:
                phealth1.gameObject.SetActive(true);
                phealth2.gameObject.SetActive(true);
                phealth3.gameObject.SetActive(true);
                phealth4.gameObject.SetActive(true);
                phealth5.gameObject.SetActive(true);
                phealth6.gameObject.SetActive(false);
                phealth7.gameObject.SetActive(false);
                phealth8.gameObject.SetActive(false);
                phealth9.gameObject.SetActive(false);
                phealth10.gameObject.SetActive(false);
                break;
            case 4:
                phealth1.gameObject.SetActive(true);
                phealth2.gameObject.SetActive(true);
                phealth3.gameObject.SetActive(true);
                phealth4.gameObject.SetActive(true);
                phealth5.gameObject.SetActive(false);
                phealth6.gameObject.SetActive(false);
                phealth7.gameObject.SetActive(false);
                phealth8.gameObject.SetActive(false);
                phealth9.gameObject.SetActive(false);
                phealth10.gameObject.SetActive(false);
                break;
            case 3:
                phealth1.gameObject.SetActive(true);
                phealth2.gameObject.SetActive(true);
                phealth3.gameObject.SetActive(true);
                phealth4.gameObject.SetActive(false);
                phealth5.gameObject.SetActive(false);
                phealth6.gameObject.SetActive(false);
                phealth7.gameObject.SetActive(false);
                phealth8.gameObject.SetActive(false);
                phealth9.gameObject.SetActive(false);
                phealth10.gameObject.SetActive(false);
                break;
            case 2:
                phealth1.gameObject.SetActive(true);
                phealth2.gameObject.SetActive(true);
                phealth3.gameObject.SetActive(false);
                phealth4.gameObject.SetActive(false);
                phealth5.gameObject.SetActive(false);
                phealth6.gameObject.SetActive(false);
                phealth7.gameObject.SetActive(false);
                phealth8.gameObject.SetActive(false);
                phealth9.gameObject.SetActive(false);
                phealth10.gameObject.SetActive(false);
                break;
            case 1:
                phealth1.gameObject.SetActive(true);
                phealth2.gameObject.SetActive(false);
                phealth3.gameObject.SetActive(false);
                phealth4.gameObject.SetActive(false);
                phealth5.gameObject.SetActive(false);
                phealth6.gameObject.SetActive(false);
                phealth7.gameObject.SetActive(false);
                phealth8.gameObject.SetActive(false);
                phealth9.gameObject.SetActive(false);
                phealth10.gameObject.SetActive(false);
                break;
            case 0:
                phealth1.gameObject.SetActive(false);
                phealth2.gameObject.SetActive(false);
                phealth3.gameObject.SetActive(false);
                phealth4.gameObject.SetActive(false);
                phealth5.gameObject.SetActive(false);
                phealth6.gameObject.SetActive(false);
                phealth7.gameObject.SetActive(false);
                phealth8.gameObject.SetActive(false);
                phealth9.gameObject.SetActive(false);
                phealth10.gameObject.SetActive(false);
                break;
        }

    }

}

A: I suspect something is wrong in the scene.

*

*Check that there is only one of this script in the scene.

In the Hierarchy Tab type in the search bar t:MyComponentName.  Multiple copies using the same phealth objects could cause the issue you are experiencing.

*Double check your phealth{n} gameObjects that are assigned in the inspector.

Here is a cleaned up version of your code.  Tested and confirmed working.
using UnityEngine;

public class Health : MonoBehaviour
{
    public int health;
    public int maxHealth;
    public GameObject[] healthObjs;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("hazard"))
        {
            AddHealth(-1);
        }
    }

    private void AddHealth(int amount)
    {
        health = Mathf.Max(0, Mathf.Min(maxHealth, health + amount));

        UpdateDisplayedHealth();
    }
    private void UpdateDisplayedHealth()
    {
        for (int i = 0; i < healthObjs.Length; i++)
        {
            healthObjs[i].SetActive(i + 1 <= health);
        }
    }
}

*

*Removed the switch case replacing it with a for loop which makes the code much more compact.

*Updated the damage function to handle the min/max health value and to update the displayed health.

*Removed Update completely.


text:
Q: android application can run in emulator but it can't run in devices using apk My app can run in emulator. Then I install my app in devices (Hp) but when I opened my app, my app is force close and say "application is not installed in your phone"
Can you help me how to fix my problem?

A: Try to use hardware android debug


text:
Q: Babel not working on OS X? I'm using a MacBook Air, with OS X, and I have great difficulties in using Latex in my native language (serbian).
If I use the standard babel package in TexShop:
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english, serbian]{babel}

And set keyboard input language to Serbian-latin, when i type letters like
ž, š, ć, etc.
I get question marks on the output pdf when I typeset it (PdfTex). As far I understand, OS X uses UTF-8 encoding, so this shouldn't happen, yet it does. Any solutions? :)
P.S. Of course, I can use \v s for š and \' c for ć, but its very tedious to write like that.

A: What encoding is used by the operating system is not relevant; the editor you use for typing LaTeX documents might use another.
This is indeed the case for TeXShop, that initially is set up to use MacOSRoman, that is, Latin-1 (or ISO 8859-1).
Check in the Preferences panel, "Source" tab: under "Encoding" you find a drop-down menu, choose Unicode (UTF-8).
Take also the habit of putting at the start of your LaTeX file the line
% !TEX encoding = UTF-8 Unicode

that will prevent encoding problems.
Here's an example document (the text is from http://sr.wikipedia.org/sr-el/Београд)
% !TEX encoding = UTF-8 Unicode
\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[serbian]{babel}

\begin{document}

Beograd je glavni i najveći grad Srbije. Jedan je od
najstarijih gradova u Evropi. Prva naselja na teritoriji
Beograda datiraju iz praistorijske Vinče, 4.800 godina pre
nove ere. Sam Beograd su osnovali Kelti u 3. veku pre n. e,
pre nego što je postao rimsko naselje Singidunum. Slovensko
ime "Beligrad" (slov.~Bjelgrad) prvi put je zabeleženo
878. godine, u čemu je sadržan utisak izgleda tadašnje
tvrđave. Beograd je glavni grad Srbije od 1405. godine i bio
je prestonica raznih južnoslovenskih država od 1918. pa
do 2003, kao i Srbije i Crne Gore od 2003. do 2006.

\end{document}


text:
Q: Not able to Reindex Indexes when install magento by downloading code from magento connect I have installed magento 2 by downloading code from magento connect. I have not used composer for it.
Now, I am not able to reindex indexes from CLI.
Please let me know how to reindex indexes in magento 2.

A: to reindex in magento 2, go to the CLI and then the root folder of your magento installation and run the below command :
php bin/magento indexer:reindex


text:
Q: Text-overflow: ellipsis not working, despite using all necessary css prerequisites I can't figure out why is the text overflow ellipsis property not working here...
HTML:
<div class='overflowTest'>
   Long long long long long long text
</div>

And CSS:
.overflowTest {
   overflow: hidden;
   white-space: no-wrap;
   text-overflow: ellipsis;
   background-color: red;
   -webkit-border-radius: 12px;
   -moz-border-radius: 12px;
   border-radius: 12px;
   margin:4px;
   padding:4px;
   width: 46%;
   height:30px;
   font-size: 12px;
   padding-top:7px;
   font-style: normal;
   float: left;
}

It has overflow set to hidden, white-space to no-wrap, and text-overflow to ellipsis, it also has a given width(tried changing that from percentage to fixed number, still doesn't work), what am I missing?
Here's also a fiddle:
https://jsfiddle.net/9xhrs2nj/

A: There is no hyphen in nowrap.
Updated Example
It should be:
white-space: nowrap;

rather than:
white-space: no-wrap;


text:
Q: Extract Data points of a contourplot in Maple17 I am working with Maple (17). I am quite new at it and I need to learn or get to know how extract the raw data or data points from a contourplot (2d plot) to a text file or whatever, but just get the data and later plot in other software.

A: Maple's 2D plotting commands construct function calls in Maple's own language, which can be examined using stock commands (eg. nops, op, lprint, select, etc).
Of course the layout and nature of the contents of these PLOT function calls (which server as data structure) vary according to which particular plotting command produces them.
Here is some basic poking at the contents of the PLOT function call returned by the plots:-contourplot command.
restart;

P := plots:-contourplot( sin(x)*y^2,
                         x=-Pi..Pi, y=-1..1,
                         contours=[-1/2,-1/7,1/7,1/2],
                         grid=[39,39] ):

# The GUI prints the PLOT structure by rendering it graphically.
P;

# Data for 2D curves are stored within substructures that are
# function calls to the name `CURVES`.
Pdata := select( type, [op(P)], specfunc(anything,CURVES) ):

# There are four CURVES within this particular structure
# assigned to P, corresponding to the 4 named contour values.
nops(Pdata);
                    4

# Select only the numeric data, in a list.
C1 := select( type, [op(Pdata[1])], list(list(numeric)) ):

# There happen to be 78 entries of data.
nops( C1 );
                   78

# Print the first five entries in list C1.
# Each one is a list of two lists. In each such pair
# the two lists each contain two floats, representing
# x and y coordinates of a point.
# Each list of two points represents a line segment.
# This first CURVE is stored as 78 individual line segments
# (but here is the end-point data for 5 of those).

map(print, C1[1..5]):

[[0.524804672715281, -1.], [0.560425257062589, -0.967862584000641]]
[[0.593087222168692, -0.947368421052632], [0.560425257062589, -0.967862584000641]]
[[0.593087222168692, -0.947368421052632], [0.611600658135984, -0.931520641144355]]
[[0.661387927071535, -0.902063357909845], [0.611600658135984, -0.931520641144355]]
[[0.661387927071535, 0.902063357909845], [0.593087222168693, 0.947368421052631]]

You could look at the commands Export, writedata, fprintf, or ExportMatrix for choices about exporting such data to files. But of course first you'd need to decide on your target format.


text:
Q: How can group by or merge my json object based on common property in angular4 project I have this json object in my angular4 project. I want to group by or merge this object based on common property.
How can merge these object based on fixture_desc? I want to display as fixture_desc= "Pepsi Cooler" and under it all items.
 "items": [
              {
                "barcode": "052000324815",
                "price": 2,
                "taxable": false,
                "description": "Gatorade Cool Blue",
                "tax_rate": 0,
                "inventory": 8,
                "fixture_desc": "Pepsi Cooler"

              },
              {
                "barcode": "052000328660",
                "price": 2,
                "taxable": false,
                "description": "Gatorade Fruit Punch ",
                "tax_rate": 0,
                "inventory": 8,
                "fixture_desc": "Pepsi Cooler",
                "min": 2,
                "max": 8,
                "_id": "58feb29a3a5c560011b1b96c"
              },
              {
                "barcode": "052000328684",
                "price": 2,
                "taxable": false,
                "description": "Gatorade Lemon Lime ",
                "tax_rate": 0,
                "inventory": 4,
                "fixture_desc": "Pepsi Cooler",
                "min": 1,
                "max": 4,

              }
        ]

I want to make organise to display my data. My expected  result is like this :
"items": [
{
    "name": "Pepsi Cooler",
    "items": [
    {
          "barcode": "052000324815",
          "price": 2,
          "taxable": false,
          "description": "Gatorade Cool Blue",
          "tax_rate": 0,
          "inventory": 8,
          "fixture_desc": "Pepsi Cooler"
        },
        {
          "barcode": "052000328660",
          "price": 2,
          "taxable": false,
          "description": "Gatorade Fruit Punch ",
          "tax_rate": 0,
          "inventory": 8,
          "fixture_desc": "Pepsi Cooler"

        }
    ]
}
{
    "name": "Cook Cooler",
    "items": [
    {
          "barcode": "052000324815",
          "price": 2,
          "taxable": false,
          "description": "Gatorade Cool Blue",
          "tax_rate": 0,
          "inventory": 8,
          "fixture_desc": "Cook Cooler
        },
        {
          "barcode": "052000328660",
          "price": 2,
          "taxable": false,
          "description": "Gatorade Fruit Punch ",
          "tax_rate": 0,
          "inventory": 8,
          "fixture_desc": "Cook Cooler
        }
    ]
}
]

A: I solved my problem. I am posting it if its help anyone.
Here my Array:
    var myobj={"items": [
                      {
                        "barcode": "052000324815",
                        "description": "Gatorade Cool Blue",
                        "fixture_desc": "Pepsi Cooler"
                      },
                      {
                        "barcode": "052000328660",
                        "description": "Gatorade Fruit Punch ",
                        "fixture_desc": "Pepsi Cooler",
                      },
                      {
                        "barcode": "052000328684",
                        "description": "Gatorade Lemon Lime ",
                        "fixture_desc": "Pepsi Cooler",
                      }
                ]
    }
    and this is my solution:
     result:any[] = [];
     finalResult(myObj:any){
                var Obj = myObj;
                var groups:any[]=[];
    for (let a of Obj) {
        groups[a.fixture_desc] = groups[a.fixture_desc] || {
                        name:a.fixture_desc,
                        items:[],
                        isfixtureExpanded:false
                    };
                    groups[a.fixture_desc].items.push({

                            barcode: a.barcode,
                            description: a.description,
                            fixture_desc:a.fixture_desc,

                    });
                }

         for (var key in groups){

            this.result.push(groups[key]);
        }
                }

console.log(this.result);
    }

A: Instead of asking the code you can show us whatever you have done to achieve it, SO is not code generator. But anyway here's the code that can do the same you wanted.
function group(array, prop) {
var result = [];
    array.forEach(function(val) {
        var found = false;
        for(var i=0;i<result.length;i++) {
            if(result[i].name === val[prop]) {
                result[i].items.push(val);
                found = true;
            }
        }
    });
}

Call it as
var finalResult = group(items,'fixture_desc');


text:
Q: How to edit .conf files from a script On a new VPS I might want to ensure that certain config values are set, or amended if they already exist. For example in /etc/systemd/journald.conf I want to set SystemMaxUse=100M if it's not already set, or in /etc/ssh/sshd_config I want PasswordAuthentication no.
I could write regex/replaces but I'm lazy. Is there a nice/general way to ensure values like this are set, without simply appending to the end of the conf file? Appending seems hacky and would potentially end up with duplicate lines.

A: A friend has just recommended Augeas which is the perfect solution:
Edit a file via bash script