text:
Q: What does "speaks to the mindset" mean? I don't understand the following sentence.
"It speaks to the mindset that a lot of these channels have"
I'm really lost right now, i've tried googling it to no avail, if anyone could help out i would really appreciate it.

A: It means it addresses the way people are already thinking. Fits in with their style. So, hopefully it should be easy for the audience to relate to, understand, and appreciate it.
Their 'mindset' is their cultural, social, environmental, community way of currently perceiving things.
For example,

*

*'in Victorian times, the mindset of teachers and educationalists was draconian and cruel towards children.'

*'The current mindset in the medical industry favours non-invasive treatment'
'Speaks to' is an Americanism that I have mostly heard in business, and it means 'responds to'.
To give an example of the whole thing:

*

*'our newly invented stick-on prosthetic ears speak to the mindset of today's doctors, who favour non-invasive treatments.'

*'rap music speaks to the mindset of today's youth... and so we are going to use it in our advertising campaign'

*'TV shows about animals and pets speak to the mindset of the mostly young and very old viewers of these channels - so we aim to air our 'cats and dogs' show there.'


text:
Q: dd command without verbose mode I don't need dd command verbose, my idea is to write it to a file, like this:
sed -n 1,200000p fileinfo | while read line
do
    # $path is the directory path
    dd  if=file1 of="$path/file2"  bs=1000000  &>trash-file
done

But it takes a time. Is there any way to do this faster?

redpajama_set_name: RedPajamaStackExchange


text:
Q: System Idle is at 99%, Physical memory at 40%: why so slow? I have a Win 7 32-bit Pro machine joined to a domain on a 10/100 ethernet connection.   At times this machine runs all sorts of slow.  For example, it took it 20 seconds for a command prompt to pull up, not to mention the other 15 seconds for the start bar to recognize that I clicked on it.  There are a few times where it took almost 10 minutes for the machine to even prompt for a password after powering it on.  There are various other situations in which the computer exhibits it's "slowness".
Inspecting task manager does not reveal anything obvious.  All other processes combined consumes < 1% in an idle state, and physical memory sits around 30%-40% consumed.  On the other hand, the System Event View reveals that several process are reporting X service entered the stopped state and X service entered the start state at various times.  Some other errors in the event viewer that reveals symptoms of the
Event ID: 7011

A timeout (30000 milliseconds) was reached while waiting for a transaction response from the X service.

There were several of these errors where the X serice was SmcService, IAStorDataMgrSvc, Microsoft .Net Framework NGEN v4.0.30319_X86, a few others.  I don't think that these services are causing the problem.  Rather there's something thats causing this services to time out.  What on earth is going on?

A: The two things have nothing to do with each other. Idle is talking about CPU usage, not memory. It seems that you have identified the issue though, there is something wrong with these services (or a common dependency).
I would try to disable them one by one, and see if that changes anything. Additionally, I would try leaving the domain, booting in safe mode, and booting without network access.

A: Turns out that Symantec Endpoint Protection is the culprit. Unintsalling the program and rebooting made it seem like a new computer again (as it should being only 6 months old).
Still, I am unable to find the cause for it to slow down.  There are no other virus scans on the computer, not even Microsft's Security Essentials.  This is all I have for now.


text:
Q: button not clickable c# winforms Is it possible to make a button not clickable and just make it clickable when a textbox was filled out, radio button was ticked, checkbox and combo box item was selected?(it needs to be all done before making the button clickable) I already made the button unclickable but I need to make it clickable after filling out informations. Please help, thank you

A: One easy solution might be

*

*Disable your button on start up button1.Enabled=false

*Add events to your textbox etc. like TextChanged and with the following code.
     if (!textBox1.Text.Equals(string.Empty) && checkBox1.Checked && comboBox1.SelectedItem != null)
     {
         button1.Enabled = true;
     }
     else
     {
         button1.Enabled = true;
     }

That might work for your case here

A: Since your question at this time does not contain code, I will refrain from adding code to the answer and offer you pseudocode to provide one of many possible solutions to this problem.
private void Ev_DoCheckEnableButton(object sender, EventArgs e)
{
//check here if textbox is filled, if radio button is ticked, if checkboed is checked and if combobox is selected
//if checks passed set the button to enabled
//if not passed then set it to disabled
}

Now for each control you want to check add a listener for the appropriate Event to Ev_DoCheckEnableButton and voila.

A: First put btnClickable to enable = false, then
basically you need to check if everything is as you need it to be, if it is as you wish, button is being enabled back.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
                if(cb1.Checked==true && tbText.Text!=null && rb1.Checked==true)
                {
                    btnClickable.Enabled = true;
                }
            }

Note: This is an example where we use ComboBox - SelectionChanged method, because you wrote it last in the ln the question, so i assumed it goes last.
If, for example you want to put checkbox as the last item, just activate Click event on it, and change terms in if(). (ComboBox1.SelectedItem==null instead of cb1.Checked==true))


text:
Q: Why object can see implementation of method after upcast? Why i can call Method? It can't see the implementation of the Method, only declaration, isn't it? Is it upcast and boxing at the same time.. or not?
interface IB
{
    void Method();
}

struct A : IB
{
    public void Method() { Console.WriteLine("1"); }
}

class Program
{
    static void Main()
    {
        A a;
        a.Method();
        IB i = a;   // boxing.. and upcast?
        i.Method(); // why it works? It looks like call of declaration
    }
}

Result of work:

1
1

A: When you assign your object to the instance of your interface i you are simply hiding anything else in the a object that doesnt match the interface definition.
Instead lets assume your struct was
struct A : IB
{
    public void Method() { Console.WriteLine("1"); }   // Method defined in interface IB.

    public void Method2() { Console.WriteLine("2"); }  // Method only in A
}

class Program
{
    static void Main()
    {
        A a;
        a.Method();
        a.Method2();  // This works.
        IB i = a;
        i.Method();
        i.Method2();// This fails to compile because Method2 isnt defined in the interface.
    }
}

A: It looks like you are creating an instance of A, then calling the method in A, and then declaring IB(i) to be the instance of A and again calling its method

A: The instance of class A implements interface IB, that is to say, any instance of class A is also type of interface IB, so it is perfectly legitimate to assign object of A to IB. No casting. No boxing. And yes, as @CathalMF said, you will only be able to call what is there in IB interface from this object.


text:
Q: What are the conditions on $G$ such that $D^T G D$ is positive semidefinite? Problem Statement:
Suppose that the matrix $M \in \mathbb{R}^{N \times N}$ has the following decomposition:
$M=D^TGD$,
where $D \in \mathbb{R}^{N \times N}$ and $G \in \mathbb{R}^{N \times N}$.

What are the conditions on $G$ such that $M$ is positive semidefinite?

Solution attempt:
It seems that $M$ is positive semidefinite if $G$ is a diagonal matrix with nonnegative entries along the diagonal. Is there a more general statement that can be made regarding the form of $G$?
Is it useful to decompose $G$ as $G=X\Lambda X^{-1}$, where $\Lambda$ is a diagonal matrix containing the eigenvalues of $G$ and $X$ is a matrix whose columns are the eigenvectors of $G$?
Based on this question: Show that $A$ is positive semidefinite given $(B^TAB)$ is positive semidefinite and $B$ is invertible, is it sufficient that $G$ be positive semidefinite? Note here that I am interested in the case where $D$ is not invertible.

A: It is indeed sufficient that $G$ is positive semidefinite.
First, If $G$ is positive semidefinite, then it is by definition symmetric. Thus
$$M^T = (D^TGD)^T = D^TG^T(D^T)^T = D^TG^D = M \tag 1$$
thus $M$ also is symmetric.
Second, for any vector $v$ define $w=Dv$. Then we have
$$v^TMv = v^TD^TGDv = (Dv)^TG(Dv) = w^TGw \ge 0 \tag 2$$
since $G$ is positive semidefinite. Note that if $D$ is not invertible, $w$ may be the zero vector; however this is not a problem because $0^TM0 = 0$, which is explicitly allowed (OTOH for this reason $G$ being positive definite would not be sufficient for $M$ being positive definite).
(1) and (2) together mean that $M$ is positive semidefinite.
Note however that this is in general not a necessary condition. For example, consider
$$G = \pmatrix{1&0\\0&-1}, D=\pmatrix{1&0\\0&0}$$
Clearly $G$ is not positive semidefinite in this case, but $M = D^TGD = D$ is positive semidefinite. As the answer you linked to shows, it is however necessary in the case that $D$ is invertible.


text:
Q: What is the average length of an idealised ball of yarn? This is a question about statistical geometry.
The image https://commons.wikimedia.org/wiki/File:Ball_of_yarn_10.jpg shows a typical ball of yarn. Such a spherical ball of radius $$ has a volume $V=4π^3/3$. The radius of the yarn is $$. The idealized yarn of the question is assumed to be unstretchable and infinitely flexible.
Is there some method, maybe using random walks, to estimate an expectation value for the yarn length, given the radius R of the ball and the radius r of the yarn? (This is not homework; the question is about the ensemble average over all possible balls of radius .)
The length will depend on the way the ball is formed. There will be air-filled space inside the ball. Therefore yarn length $$ is surely smaller than $/(π^2)$. But what is its average length $L$ for an average ball? How can one determine this average length? Equivalently: how much air is contained in an average ball of yarn?

A: I suggest to replace the divisor $\pi r^2$ in your tentative formula for $L$ by the area $2\sqrt{3}\,r^2$ of the  circumscribed hexagon. In this way neighboring strands of the yarn are most densely packed. This would lead to
$$L\approx{4\pi R^3/ 3\over2\sqrt{3}r^2}={2\pi R^3\over3\sqrt{3}\,r^2}\ .$$


text:
Q: Rails - how to query has_many from model I have a scheduleevent model. The model uses ice_cube to create recurrence rules. A scheduleevent has_many schedtimeranges. A schedtimnerange has a start_time, end_time and booleans for the days of the week Sunday - Saturday. Whatever days are checked are true.
What I need to do is get those days in an array to pass them into ice_cube. How would I join scheduleevent to schedtimeranges, and get Sunday - Saturday where the value is true in a rails model? Do I query the records in the controller, then loop them in the model, or if I need to loop in the model, query them from the model?
Trying to do something like this, but getting a no method schedtimeranges error:
  def self.timeranges
    Schedtimeranges.where(scheduleevent_id: self.id).columns.select{ |c| c.type == :boolean }.map(&:name)
  end
  weekdays = self.timeranges

Scheduleevent Model:
  has_many :schedtimeranges, inverse_of: :scheduleevent
  accepts_nested_attributes_for :schedtimeranges, allow_destroy: true

EDIT:
weekdays = schedtimeranges.where(scheduleevent_id: id).columns.select{ |c| c.type == :boolean }.map(&:name).to_a

This works, but I just need to only get them where the value is true. How do I add that to this? So if a scheduleevent has say 3 schedtimeranges, I want to get the days of week, and start_time/end_time where they are true.
Expected output would be 07:00 AM, 14:00 PM, Monday, Thursday, Friday. (If those are the 3 days that are true.
  create_table "schedtimeranges", force: :cascade do |t|
    t.bigint "scheduleevent_id", null: false
    t.string "start_time"
    t.string "end_time"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.boolean "monday"
    t.boolean "tuesday"
    t.boolean "wednesday"
    t.boolean "thursday"
    t.boolean "friday"
    t.boolean "saturday"
    t.boolean "sunday"
    t.index ["scheduleevent_id"], name: "index_schedtimeranges_on_scheduleevent_id"
  end

EDIT 2:
This is how I am trying to create the recurrence rules. How would I loop the to_ice_cube and pass the scheduleevent_id through?
schedule = IceCube::Schedule.new(start)
case orule
when 'daily'
  schedule.add_recurrence_rule IceCube::Rule.daily(1).until(end_date.to_time)
when 'weekly'
  self.map(&:to_ice_cube).where(scheduleevent_id: self.id).each do |days|
    schedule.add_recurrence_rule IceCube::Rule.weekly(1).day(days.map{|s| s.to_sym}).until(end_date.to_time)
  end
end

The idea being that if it is a daily repeat type I just have a start time and end time between all days froms tart date to end date. If it is a weekly recurrence I want to create the rules for the times on those particular days.
I am getting an undefined method map the scheduleevent record.

A: I think you made it sound way more complicated than it is. Expected output helped a lot. I've added a couple of methods to Schedtimerange to make it simpler:
# why not ScheduleTimeRange and ScheduleEvent

class Schedtimerange < ApplicationRecord
  # sometimes you just have to type all the attributes that you need
  def days
    {
      monday:    monday,
      tuesday:   tuesday,
      wednesday: wednesday,
      thursday:  thursday,
      friday:    friday,
      saturday:  saturday,
      sunday:    sunday
    }
  end

  # # or like this
  # DAYS = %w[monday tuesday wednesday thursday friday saturday sunday].freeze
  # def days
  #   attributes.slice(*DAYS)
  # end

  # desired format goes here
  def to_ice_cube
    [start_time, end_time, *days.compact_blank.keys]
  end
end

https://api.rubyonrails.org/classes/Hash.html#method-i-compact_blank-21
>> Schedtimerange.first.to_ice_cube
=> ["07:00 AM", "08:00 AM", :monday, :friday]

>> Schedtimerange.where(scheduleevent_id: 1).map(&:to_ice_cube)
=> [["07:00 AM", "08:00 AM", :monday, :friday], ["11:00 AM", "04:00 PM", :monday, :tuesday]]

Do the same for Scheduleevent if you want:
class Scheduleevent < ApplicationRecord
  has_many :schedtimeranges

  def to_ice_cube
    [id, schedtimeranges.map(&:to_ice_cube)]
  end
end

>> Scheduleevent.limit(2).map(&:to_ice_cube)
=> [[1, [["07:00 AM", "08:00 AM", :monday, :friday], ["11:00 AM", "04:00 PM", :monday, :tuesday]]],
    [2, [[nil, nil, :monday, :tuesday], [nil, nil, :tuesday, :wednesday]]]]

If you're calling it from Scheduleevent, just use association to get relevant ranges:
schedtimeranges.map(&:to_ice_cube).each do |days|
  schedule.add_recurrence_rule IceCube::Rule.weekly(1).day(days).until(end_date.to_time)
end


text:
Q: opencv gpu cannot load feature type haar I am trying to use opencv gpu based cascade classifier. Here is a snapshot where I try to load the cascade
gpu::CascadeClassifier_GPU cascade_gpu;
if(!cascade_gpu.load(HAARCASCADE_FRONTALFACE3))
return 0;

I am getting the following error when I try to load
Unspecified error (The node does not represent a user object (unknown type?)) in cvRead, file /Users/ashok/ivsvn/3rdparty/trunk/opencv-2.4.8/modules/core/src/persistence.cpp, line 4991
Here is the header of the cascade file.
<?xml version="1.0"?>
<opencv_storage>
<cascade>
  <stageType>BOOST</stageType>
  <featureType>HAAR</featureType>
  <height>20</height>
  <width>20</width>
  <stageParams>
    <boostType>GAB</boostType>
    <minHitRate>9.9949997663497925e-01</minHitRate>
    <maxFalseAlarm>3.4999999403953552e-01</maxFalseAlarm>
    <weightTrimRate>9.4999999999999996e-01</weightTrimRate>
    <maxDepth>1</maxDepth>
    <maxWeakCount>1000</maxWeakCount></stageParams>
  <featureParams>
    <maxCatCount>0</maxCatCount>
    <featSize>1</featSize>
    <mode>ALL</mode></featureParams>
  <stageNum>18</stageNum>
  <stages> ...

I have a similar cascade file that is trained with
LBP that works with the gpu load.
Any clue on this issue?


text:
Q: OCaml random image I have written these few lines to make a random image with given size & n is number of black pixel I want.
I see that when I run with 512 in size and 511 * 511 for pixel number, image should be black but it's only partial. I think it's because he can pick two times the same x or y ?
How can I modify this to add verification if j.(x).(y) is used or not ?
let rdm_img2 size n =
let img = Array.make_matrix size size Blanc in (
snd(forloop((0, img),
    n,
    (function(i, j) ->
        let x, y = pickRdmxy(size) in
        match x,y with
        j.(x).(y) = Noir -> pickRdmxy size;
        j.(x).(y) = Blanc -> j.(x).(y) <- Noir;
        (i,j)
    )
)))

;;
and forloop is this lines :
let rec forloop(r, n, next : 'a * int* ('a -> 'a)) : 'a =
    if n = 0 then r
    else forloop (next(r), n-1, next)
;;

and pickRdmxy just return a random int between 0 and size.

A: Your code is not valid and cannot compile since
  match x,y with
  j.(x).(y) = Noir -> pickRdmxy size;
  j.(x).(y) = Blanc ->

is a syntax error.
I imagine that you meant
  match j.(x).(y) with
  | Noir -> pickRdmxy size
  | Blanc -> ...

Moreover, you are not using the arguments of your function, thus a normal for loop is clearer:
let img = Array.make_matrix size size Blanc in (
for _ = 1 to n do
  let x, y = pickRdmxy(size) in
  match j.(x).(y) with
  | Noir -> ()
  | Blanc -> j.(x).(y) <- Noir
done

Going back to your question, you are sampling with repetition, thus with a high probability, you will get collisions and will not sample all pixels after sampling exactly the number of pixels in your image.
If you want to sample without repetition, you need to change algorithms.
One way to do it is to compute a permutation of all indices, with a Knuth's shuffle for instance
let shuffle a =
  let a = Array.copy a in
  for i = Array.length a - 1 downto 0  do
    let r = Random.int (i+1) in
    let tmp = a.(r) in
    a.(r) <- a.(i);
    a.(i) <- tmp
  done;
  a

let sample_without_repetition n f sample_set =
  let permuted_sample_set = shuffle sample_set in
  for i = 0 to n-1 do f permuted_sample_set.(i) done


text:
Q: SQL: Sort by Nearest comma-separated dates I have a table with dates stored in comma separated like below
9/30/2013,9/17/2013,10/16/2013,
5/27/2013, 9/30/2013,
09/24/2013,09/27/2013,
09/13/2013,11/18/2013,
09/11/2013,09/13/2013,
12/27/2013,12/20/2013,
12/27/2013,12/20/2013,12/13/2013,12/6/2013,11/29/2013,
10/3/2013,10/10/2013,10/17/2013,10/24/2013,10/31/2013,
10/31/2013,10/24/2013,10/17/2013,10/10/2013,10/3/2013,

Now my task is sort the records with nearest first, past dates can be ignored. Need to compare all dates in a row with current date, please suggest how can I achieve this
Thanks in advance.
Edited
I'm excepting:
9/30/2013,9/17/2013,10/16/2013, as 10/16/2013 is nearest of all
10/3/2013,10/10/2013,10/17/2013,10/24/2013,10/31/2013, as 10/17/2013 next nearest
10/31/2013,10/24/2013,10/17/2013,10/10/2013,10/3/2013,
12/27/2013,12/20/2013,12/13/2013,12/6/2013,11/29/2013,
12/27/2013,12/20/2013,

A: Here is a udf to convert your string to a table of dates:
CREATE FUNCTION [dbo].[udf_ConvertCSVStringToDateTable]
(
    @CSVString varchar(max)
)
RETURNS
@DateTable TABLE
(
    [Date] DATETIME
)
AS
BEGIN
    DECLARE @ListSize BIGINT
    DECLARE @FoundIndex BIGINT
    DECLARE @Date INT
    DECLARE @DateString VARCHAR(10)

    SET @ListSize = LEN(@CSVString)

    WHILE(@ListSize > 0)
    BEGIN
        SET @FoundIndex = CHARINDEX(',', @CSVString)

        IF(@FoundIndex = 0)
        BEGIN
            SET @DateString = @CSVString
            SET @CSVString = ''
        END
        ELSE
        BEGIN
            SET @DateString = SUBSTRING(@CSVString, 1, @FoundIndex - 1)
            SET @CSVString = SUBSTRING(@CSVString, @FoundIndex + 1, @ListSize)
        END

        IF(ISDATE(@DateString) = 1)
        BEGIN
            INSERT @DateTable([Date]) VALUES (CONVERT(DATETIME, @DateString))
        END

        SET @ListSize = LEN(@CSVString)
    END
    RETURN
END

From that you should be able to do a select and filter using a WHERE clause or order using an ORDER BY clause


text:
Q: Ruby Equivalent of ASP.NETs Application_Start? I'd like to kick off a thread that wakes up every so many seconds to do some processing within a Ruby-on-Rails web app.  In .NET, the logical place would have been to create a thread in the global.asax file and start it in Application_Start.
Is there a similar paradigm for doing such things in RoR?  Would this be done in the ApplicationController?
As an aside: am I entering the wrong search strings or are search engines really bad at finding information for building RoR apps?

A: Rails doesn't really have an equivalent. The Whenever RubyGem is a nice abstraction of Cron that lets you use syntax like the example below from within your Rails application:
every 30.seconds do
  # Do something interesting...
end

Some resources you may find useful:

*

*Cron in Ruby Railscast (covers the Whenever gem)

*What's the best background job management library for Rails? (Stack Overflow)

*What is the best way to run asynchronous jobs in a Rails application? (Stack Overflow)

A: Search engines are not only bad, but almost the ONLY place you'll find information for RoR. :(
I think the paradigm you're looking for is a cron job, though that presumes you're running under Linux. What I've seen most often is essentially a "scheduled task" that pulls down a page every X y's and the processing is done within that request. You can even do this remotely by having your scheduled task point to the remote box's cron "hit point".
You could put the code in ApplicationController and have it check to see if the job was accomplished in the last X y's, but the problem is that you could be starved for requests for longer than the intended interval.
Good luck!

A: There isn't a pat answer to this question because it depends heavily on your specific requirements. Certainly, however, there isn't a direct equivalent to the concept you describe in ASP.NET However, you'll want to take a look at Background Processing on Rails as a great starting point.

A: A couple of years ago I tried daemon_generator but for some reason now forgotten I never ended up using it.


text:
Q: Input Radio estilizado não passa Post Opa,
Tenho uns radio buttos que via css são trocados por cores.

    <input type="radio" name="cor" value="1" />

    <input type="radio" name="cor" value="2" />

    <input type="radio" name="cor" value="3" />

    <input type="radio" name="cor" value="4" />

O CSs
    .radio-cores input[type="radio"] {
        display: none;
    }

    .radio-cores label {
        display: inline-block;
        color:#fff;
        padding: 4px 11px;
        font-family: Arial;
        font-size: 16px;
        cursor: pointer;
        margin:3px;
        border:1px solid #cecece
    }

Só que ao enviar o post, o radio button selecionado não vem, se remover a classe radio-cores da div, eles vem no post normalmente.

.radio-cores input[type="radio"] {
        display: none;
    }

    .radio-cores label {
        display: inline-block;
        color:#fff;
        padding: 4px 11px;
        font-family: Arial;
        font-size: 16px;
        cursor: pointer;
        margin:3px;
        border:1px solid #cecece
    }

.product-color-blue {
  background-color: blue;
}

.product-color-grey {
  background-color: grey;
}

.product-color-red {
  background-color: red;
}

.product-color-green {
  background-color: green;
}
<form method="post" action="salva.php" enctype="multipart/form-data">

      <input type="radio" name="cor" value="1" />

      <input type="radio" name="cor" value="2" />

      <input type="radio" name="cor" value="3" />

      <input type="radio" name="cor" value="4" />

</form>

A: Não use display:none e sim visibility: hidden;

.radio-cores input[type="radio"] {
        visibility: hidden;
    }

    .radio-cores label {
        display: inline-block;
        color:#fff;
        padding: 4px 11px;
        font-family: Arial;
        font-size: 16px;
        cursor: pointer;
        margin:3px;
        border:1px solid #cecece
    }

.product-color-blue {
  background-color: blue;
}

.product-color-grey {
  background-color: grey;
}

.product-color-red {
  background-color: red;
}

.product-color-green {
  background-color: green;
}
<form method="post" action="salva.php" enctype="multipart/form-data">

      <input type="radio" name="cor" value="1" />

      <input type="radio" name="cor" value="2" />

      <input type="radio" name="cor" value="3" />

      <input type="radio" name="cor" value="4" />

</form>

Fonte

A: A solução exata que encontrei, verifiquei que o uso do visibility: hidden; não exibe o radio, mas, seu espaço continua oculpado, não sendo o ideal em relação a layout.
Usando:
    .radio-cores input[type="radio"] {
        -moz-appearance: none;
        -webkit-appearance: none;
        appearance: none;
        opacity: 0;
    }

Está perfeito


text:
Q: How do I check if a range of SpecialCells contains cells? I ran into an edge case in one of my spreadsheets recently. I have a loop going over all visible cells in a table:
For Each c In ws.ListObjects(1).ListColumns(1).DataBodyRange.SpecialCells(xlCellTypeVisible)
    ...
Next c

Normally there will always be a few items visible, but in an edge case none were, which generated an error in my code:

Run-time error '1004': No cells were found

I tried wrapping the for-loop in an if-statement
If ws.ListObjects(1).ListColumns(1).DataBodyRange.SpecialCells(xlCellTypeVisible).Count > 0 Then

But this generates the same error. Similarly if I check if the range is nothing.
How do I go about checking if there are visible cells in the filtered table?

A: As a temporary solution, I used the solution shown below, where On Error Resume Next causes the error to be skipped, allowing me to check if a range has been assigned to the variable rng afterwards.
Dim rng As Range
Dim c As Range
On Error Resume Next
Set rng = ws.ListObjects(1).ListColumns(1).DataBodyRange.SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not rng Is Nothing Then
    For Each c In rng
        ...
    Next c
End If

I suppose a better solution might be creating a proper error handler for the function, as the current implementation is kinda ugly...

A: I would use a helper function to which you pass the listobject
Private Function hasVisibleRows(lo As ListObject) As Boolean

If lo.DataBodyRange Is Nothing Then Exit Function

On Error Resume Next
hasVisibleRows = lo.DataBodyRange.SpecialCells(xlCellTypeVisible).Count > 0
On Error GoTo 0

End Function

This is one of the rare cases where on error resume next is valid, as there is no other way to check for visible rows.
But I would always put the check in a separate function.


text:
Q: Removing Duplicate Numbers from an Array and Adding them to the end at c++ i have an array in data.txt file like 9 3 9 4 5 4 3 7 1 9 6
i need to find duplicate numbers and remove them from the array.
After that i need to collect them at the end of the array.
i wrote a code and the output is 9 3 4 5 7 1 6 9 3 4 9, but i need to put the duplicated numbers in array, in the sequence they appear in the original array.
So i need to get { 9, 3, 4, 5, 7, 1, 6, 9, 4, 3, 9 } as output.
What can i do with  the code to reach my goal ?
#include <iostream>
#include <fstream>
using namespace std;
#define SZ 11
int main(){
    ifstream fs("data.txt");
    if (!fs)
        return 0;
    int a[SZ];
    for (int i = 0; i < SZ; ++i)
        fs >> a[i];
    for (int k=0; k<SZ; k++) {
        for (int j=k+1; j< SZ ; j++) {
            if (a[j]==a[k]) {
                for (int l=j; l<SZ-1; l++) {
                    a[l]=a[l+1];
                }
                a[10]=a[k];
            }
        }
    }
    for (int i = 0; i < SZ; ++i)
        cout << a[i];
    return 1;}

A: If you want to keep the order, you have to compare each number to the previous ones instead of comparing it to the next ones. Your program becomes :
#include <iostream>
#include <iostream>
#include <fstream>
using namespace std;
#define SZ 11
int main(){
ifstream fs("data.txt");
    if (!fs)
        return 0;
    int a[SZ];
    for (int i = 0; i < SZ; ++i)
        fs >> a[i];
    // kk limits the number of iteration, k points to the number to test
    for (int k=0, kk=0; kk<SZ; kk++, k++) {
        for (int j=0; j< k ; j++) {
            if (a[j]==a[k]) {
                for (int l=k; l<SZ-1; l++) {
                    a[l]=a[l+1];
                }
                a[SZ - 1]=a[j];
                // a[k] is a new number and must be controlled at next iteration
                k -= 1;
                break;
            }
        }
    }
    for (int i = 0; i < SZ; ++i)
        cout << a[i];
    return 1;}

A: Here's one strategy.
Keep the notion of whether an entry is duplicate or not in a parallel array.
Print the numbers that are not duplicates first.
Then print the numbers that are duplicates.
#include <iostream>
#include <fstream>
using namespace std;
#define SZ 11
int main()
{
   ifstream fs("data.txt");
   if (!fs)
      return 0;
   int a[SZ];
   int isDuplicate[SZ];
   for (int i = 0; i < SZ; ++i)
   {
      fs >> a[i];
      isDuplicate[i] = false;
   }

   for (int k=0; k<SZ; k++) {
      for (int j=k+1; j< SZ ; j++) {
         if (a[j]==a[k])
         {
            isDuplicate[j] = true;
         }
      }
   }

   // Print the non-duplicates
   for (int i = 0; i < SZ; ++i)
   {
      if ( !isDuplicate[i] )
         cout << a[i] << " ";
   }

   // Print the duplicates
   for (int i = 0; i < SZ; ++i)
   {
      if ( isDuplicate[i] )
         cout << a[i] << " ";
   }
   cout << endl;

   // Not sure why you have 1 as the return value.
   // It should be 0 for successful completion.
   return 0;
}

A: The OP's (@kuvvetkolu) original example has O(SZ^3) complexity, which is brutal. @RSahu's solution is O(SZ^2), an improvement (and correct), but this should not require O(N^2)...
Here's a version that incurs only space overhead (assuming O(1) hash table lookup). You can use a unordered_set (a hash table) to track whether you've already seen a particular number, put it in the appropriate vector and then merge the vectors at the end.
#include <iostream>
#include <fstream>
#include <unordered_set>
#include <vector>

int main() {
    std::ifstream fs("data.txt");
    if (!fs)
        throw std::runtime_error("File not found!");

    std::vector<int> a;
    std::vector<int> dups;
    std::unordered_set<int> seen;

    int d;
    while (fs) {
        fs >> d;
        if (seen.find(d) == seen.end())
        {
            a.push_back(d);
            seen.insert(d);
        }
        else
        {
            dups.push_back(d);
        }
    }

    a.insert(a.end(), dups.begin(), dups.end());

    for (auto n : a)
        std::cout << n << " ";

    return 0;
}

A: I'm inclined to try out a solution that uses std::remove_if and has a deduping unary predicate. That should retain the order of your duplicate elements.


text:
Q: Angular App makes duplicate http requests after idling a couple of hours stack: Angular 7, nodejs backend, postgresql database, firebase auth
Problem: if I make an http request on my angular app and then let it idle in the background for a couple of hours, it makes duplicate http requests.  It always makes the same amount of duplicate requests, which is an additional 2.  It does this on the ENTIRE app.  The duplicate requests occur with zero user input after the initial request and typically occur a couple of hours later.
Could this happen when a user comes back and firebase does some sort of re-authentication request? At this point, I'm at a loss for what the issue could be


text:
Q: Open Popup using Python after conditional statement I want to use a conditional statement ex:
if(a>b)
generate a popup saying a is the greater one.
Is it possible using python?

A: Seems that I found a solution:
import ctypes  # An included library with Python install.

if(a>b):
    ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)


text:
Q: What does this error mean "A slave with the same server_uuid/server_id as this slave has connected to the master;"? Upon searching for this, the main cause of this error is usually when using snapshots or cloning the machine. But I did not do this. I perform mysqldump --master-data=2 on the master then restore the dump on my slave server. Then start the slave on the position indicated on the outfile.
Any idea on what caused this? I am running a multi-source replica and this error is from just 1 source.
here is the complete error:

Got fatal error 1236 FROM MASTER WHEN reading DATA FROM BINARY LOG: 'A slave with the same server_uuid/server_id as this slave has connected to the master; the first event 'VM1-bin.000006' at 641809774, the last event read from '/binlogdata/VM1-bin.000009' at 146836375, the last byte read from '/binlogdata/VM1-bin.000009' at 146836375.';

A: Even if you server_id is different you may need to change the server_uuid which you can do manually in my.cnf or by deleting $datadir/auto.cnf, this file is created by MySQL when it stats and includes the server uuid.
So stop MySQL, remove the file, and start MySQL again.

A: The purpose of server_uuid and server_id are for a MySQL source (a.k.a. master) server to close a zombie replica (a.k.a. slave) connection after a network error. (Also the server_uuid in MySQL or server_id in MariaDB go into the GTID to allow a replica to know which source each transaction came from.) When a replica connects, the source presumes that any old connection is a "zombie" that can be closed (rpl_source.cc).
According to the server_uuid documentation, server_uuid is automatically generated the first time that MySQL starts and saved to data_dir/auto.cnf (e.g. /var/lib/mysql/auto.cnf). So some causes of duplicate auto.cnf might be:

*

*Did you restore the datadir from a backup?

*Did you create a Debian or Ubuntu image with mysql-server preinstalled, and then run multiple instances of it as replicas? Both the postinst script and the mysql.service ExecStartPre script run mysqld --initialize-insecure which puts the server-uuid in /var/lib/mysql/auto.cnf.

To fix the latter issue, for my mysql read replicas, I created a debian image with mysqld installed but without the datadir /var/lib/mysql/ initialized using this snippet:
# https://dev.mysql.com/doc/mysql-apt-repo-quick-guide/en/
curl --fail --location https://dev.mysql.com/get/mysql-apt-config_0.8.24-1_all.deb --output /tmp/mysql-apt-config_0.8.24-1_all.deb
DEBIAN_FRONTEND=noninteractive dpkg -i /tmp/mysql-apt-config_0.8.24-1_all.deb
apt-get update

# disable starting mysql.service at install time
echo disable mysql.service | sudo tee /usr/lib/systemd/system-preset/01-disable-mysql-while-installing.preset
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server
sudo rm /usr/lib/systemd/system-preset/01-disable-mysql-while-installing.preset
# re-enable mysql service; it will start at the next boot
sudo systemctl enable mysql.service
# delete the datadir created by mysql-server postinst;
# mysql.service's ExecStartPre will recreate it
rm -r /var/lib/mysql

Looking at the MySQL 8.0.31 source, this error may also be sent after a group replication error or when rejoining group replication, but I have not tested that (tracing duplicate_slave_id in the source rpl_binlog_sender.cc.

A: You must have a different value in the my.cnf on each server in a replication setup.  server_id must be different on each machine, else replication will be trying to go in a loop.


text:
Q: nested For loop doesnt seem to be working properly My forloops here are not incrementing properly. any list that I go through using the variable p, doesn't seem to want to increment. It keeps using and outputing the same value even though it should be going through the list and I dont know how to go about fixing it.
for p in range(0,len(C13Masses)):
        for l in range(0,len(sortedMass)):
            newError = ((float(C13Masses[p])-float(sortedMass[l]))/float(C13Masses[p]))
            exp_ratio = float(AbuList[l])/float(Abu)
            #print newError

            if -error <= newError <= error and Tratio[p]*(0.01) <= exp_ratio <= Tratio[p]*(2.9):
                Hits.append(sortedMass[l])
                print newError, Tratio[p]*(0.01), exp_ratio, Tratio[p]*(2.9), ' ', C13Masses[p]

Here is a section of the output:
these are the 13C Masses:  [247.22498116056002, 248.22833599836002,
249.23169083616, 250.23504567396003, 251.23840051176]
0.00189079878665 0.000168240943605 9.35616976571e-06 1.99758297649e-38
0.198593689562 0.00189079878665 0.377861498675 0.548331648129   247.224981161
0.133748786249 0.00189079878665 0.537307237955 0.548331648129   247.224981161
0.121834092247 0.00189079878665 0.358098400434 0.548331648129   247.224981161
0.121601834165 0.00189079878665 0.32636250439 0.548331648129   247.224981161
0.0893994654456 0.00189079878665 0.497940678778 0.548331648129   247.224981161
0.0893985351189 0.00189079878665 0.413524472399 0.548331648129   247.224981161
0.0893824364222 0.00189079878665 0.324574566585 0.548331648129   247.224981161
0.0893816274425 0.00189079878665 0.435714057661 0.548331648129   247.224981161
0.0893376189448 0.00189079878665 0.32438300182 0.548331648129   247.224981161
0.0892978171418 0.00189079878665 0.368315187893 0.548331648129   247.224981161
0.0892961991823 0.00189079878665 0.326617924076 0.548331648129   247.224981161
0.0892508154191 0.00189079878665 0.424667156221 0.548331648129   247.224981161
0.089003024926 0.00189079878665 0.439130295968 0.548331648129   247.224981161
0.0851244929285 0.00189079878665 0.532198844226 0.548331648129   247.224981161
0.0693502375046 0.00189079878665 0.335078701191 0.548331648129   247.224981161
0.0529637866655 0.00189079878665 0.378723540117 0.548331648129   247.224981161
0.0286653522119 0.00189079878665 0.327320328214 0.548331648129   247.224981161
0.0122736430045 0.00189079878665 0.433670700169 0.548331648129   247.224981161
-0.00372801662321 0.00189079878665 0.451805497909 0.548331648129   247.224981161

as you can see the last second third and last columns all dont change but they should
so it works: it's just printing out the values that held true in the if statement. Im just dumb


text:
Q: How to iterate over this generic List with wildcards? I have a List of objects that extend another class:
List<? extends Fruit> arguments;

Now, I want to invoke a method on these objects. The invoking class has a method wash for each of the classes that extend Fruit, but NOT for the Fruit abstract class:
void wash( Apple a);
void wash( Peach p);

How can I apply the method wash to all the elements in arguments? This DOESN'T work, as my wash methods don't accept Fruit arguments:
for( Fruit f: arguments)
    this.wash( f); // the wash() method is not a member of Fruit

Is there any way to solve this without having to make an umbrella method wash( Fruit)? Because there are dozens of wash( ? extends Fruit) methods...
.
EDIT: The "invoking class" I am talking about is a visitor. And I can't alter any of the Fruit classes/subclasses. I can only program the visitor. This means it isn't possible to add the wash() method (or any other methods, for that matter) to the abstract class Fruit.

A: Welcome to the world of Double Dynamic Dispatch.
AFAIK, you can't do it easily on Java. You can do it two ways : The quick'n'dirty, and the Visitor way:
Quick'n'dirty
You need to ask the type of the object, so you'll need a wash method on Fruit which will redirect the call to the right function according to its type:
public void wash(Fruit f)
{
   if(f instanceof Apple)
   {
      wash((Apple) f) ;
   }
   else if(f instanceof Peach)
   {
      wash((Peach) f) ;
   }
   else
   {
      // handle the error, usually through an exception
   }
}

The problem with the quick'n'dirty is that the compiler won't tell you there is a new valid Fruit (e.g. Orange) that is not currently handled by the wash method.
Visitor
You could use the Visitor pattern to Fruit:
public abstract class Fruit
{
   // etc.
   public abstract void accept(FruitVisitor v) ;
}

public class Apple extends Fruit
{
   // etc.
   public void accept(FruitVisitor v)
   {
      v.visit(this) ;
   }
}

public class Peach extends Fruit
{
   // etc.
   public void accept(FruitVisitor v)
   {
      v.visit(this) ;
   }
}

And define the Visitor as :
public interface class FruitVisitor
{
   // etc.

   // Note that there are no visit method for Fruit
   // this is not an error

   public void visit(Apple a) ;
   public void visit(Peach p) ;
}

And then, the Visitor for your wash case:
public class FruitVisitorWasher : implements FruitVisitor
{
   // etc.

   // Note that there are no visit method for Fruit
   // this is not an error

   // Note, too, that you must provide a wash method in
   // FruitVisitorWasher (or use an anonymous class, as
   // in the example of the second edit to access the
   // wash method of the outer class)

   public void visit(Apple a)
   {
      wash(a) ;
   }

   public void visit(Peach p)
   {
      wash(p) ;
   }
}

In the end, you code could be
FruitVisitorWasher fvw = new FruitVisitorWasher() ;

for( Fruit f: arguments)
{
   f.accept(fvw) ;
}

Et voilà...
The Visitor pattern has the advantage the compiler will tell you if you added another Fruit (e.g. Orange) in which you coded an accept method and if you forgot to update the FruitVisitor pattern to support it.
And then, the Visitor pattern is extensible: You can have a FruitVisitorWasher, a FruitVisitorEater, a FruitVisitorWhatever, adding them without needing to modify Fruit nor Apple, Peach, etc..
One trap, though, you must manually write in each Fruit class the accept method (which is a copy/paste action) because it is this method which does all the work of "knowing" the right Fruit type.
Edit
If you go for the Quick'n'dirty solution, the Samuel Parsonage's solution could be even better than mine:
How to iterate over this generic List with wildcards?
which makes use of Java's reflection (I'm a C++ coder, so reflection doesn't come as a natural solution... My bad on this...). I find his solution quite elegant, even if it smells somehow (all the checks will be done in the runtime, so you'd better make sure everything's ok... Again, by C++ background: If something can be done, or an error can be detected at compile time, moving it at runtime should be avoided as much as possible)
Edit 2
John Assymptoth commented:

The Visitor pattern as you write it isn't an option, since I can't add the method wash to Fruit.

So I'll offer the inline code to prove wash() is not expected to be inside Fruit to work.
(I changed FruitVisitor from an abstract class into an interface, which is better)
Let's imagine the for loop is inside the bar method of the Foo class, which has its own wash method:
public class Foo
{
   public wash(Apple a) { /* etc. */ }
   public wash(Peach p) { /* etc. */ }
   public bar(List<? extends Fruit> arguments)
   {
      for( Fruit f: arguments)
      {
         wash(f) ; // we wand the right wash method called.
      }
   }
}

You want the right wash method called, so the code above won't work correctly.
Let's reuse the FruitVisitor pattern to correct this code. We will use an anonymous class inside the bar method:
public class Foo
{
   public void wash(Apple a) { System.out.println("Apple") ; }
   public void wash(Peach p) { System.out.println("Peach") ; }

   public void bar(List<? extends Fruit> arguments)
   {
      FruitVisitor fv = new FruitVisitor()
      {
         public void visit(Apple a)
         {
            wash(a) ; // will call the wash method
                      // of the outer class (Foo)
         }

         public void visit(Peach p)
         {
            wash(p) ; // will call the wash method
                      // of the outer class (Foo)
         }
      } ;

      for(Fruit f: arguments)
      {
         f.accept(fv) ;
      }
   }
}

Now, it works, and there are no wash method in Fruits.
Note that this code was tested against a 1.6 JVM, so I can provide the complete code if necessary.

A: This is possible using reflection
Try this
Method m=this.getClass().getMethod("wash", f.getClass());
m.invoke(this, f.getClass().cast(f));

A: Try modifying
void wash( Apple a);

to
void wash(List<? extends Fruit> list);

And then use the first element in wash method.
You still need to have the wash() method in Fruit class.
wash method in Fruit class will be abstract and should be defined in subclasses.


text:
Q: How to use scipy.optimize.minimize I have a objective function, say obj(x, arg_1, arg_2)
within f(), I have variable_3 = f(x, arg_1, arg_2)
obj() will return abs(x-variable_3)
I need to minimize the returned value of obj() using scipy.optimize.minimize
I guess I need to do it like this:
def obj(x, arg_1, arg_2)
    v_3 = f(x, arg_1, arg_2)
    return abs(x-v_3)
x0 = 1
result = minimize(obj, x0, args = (arg_1, arg_2))

Is this correct? Why I alwasy get errors?
Alternatively, actually I can do it in this way:
def obj(x, v_3)
    return abs(x-v_3)
def myfun(arg_1, arg_2)
    x0 = 1
    v_3 = f(x0, arg_1, arg_2)
    result = minimize(obj, x0, args = v_3)
    return result

But obviously, this is what I want.
So could somebody tell me how to do this minimization? Thanks

A: for scipy.optimize.minimize, multiple arguments should be packed into a tuple, which will then be unpacked by the objective function during numerical optimization.
it should look something like this:
def obj(arguments)
    """objective function, to be solved."""
    x, arg_1, arg_2 = arguments[0], arguments[1], arguments[2]
    v_3 = f(x, arg_1, arg_2)
    return abs(x-v_3)

x0 = 1
initial_guess = [1,1,1]  # initial guess can be anything
result = minimize(obj, initial_guess)
print result.x

A: Hope it will not cause some IP problem, quoted the essential part of the answer here:
from @lmjohns3, at Structure of inputs to scipy minimize function
"By default, scipy.optimize.minimize takes a function fun(x) that accepts one argument x (which might be an array or the like) and returns a scalar. scipy.optimize.minimize then finds an argument value xp such that fun(xp) is less than fun(x) for other values of x. The optimizer is responsible for creating values of x and passing them to fun for evaluation.
But what if you happen to have a function fun(x, y) that has some additional parameter y that needs to be passed in separately (but is considered a constant for the purposes of the optimization)? This is what the args tuple is for. The documentation tries to explain how the args tuple is used
Effectively, scipy.optimize.minimize will pass whatever is in args as the remainder of the arguments to fun, using the asterisk arguments notation: the function is then called as fun(x, *args) during optimization. The x portion is passed in by the optimizer, and the args tuple is given as the remaining arguments."


text:
Q: In Project Reactor, what is a "target" Mono/Flux? eg, the Mono#transform method docs say the following:

Transform this Mono in order to generate a target Mono

What does "target Mono" mean?

A: It's not always consistent, but in the reactor documentation, the use of "target" generally signals that the type of the publisher potentially changes. In the case of transform() I'm pretty sure it's actually meant to say "target type", as the docs for both transformDeferred() and transformDeferredContextual() do - there's no reason why it would be any different from the standard transform() operator.
Don't overthink it though - it's simply the Mono that's been transformed by the method. "Target" doesn't have any special meaning in a reactive context that you need to be aware of.


text:
Q: Crash when trying to connect to react-native-debugger or Chrome After upgrading our react-native project to react-native 0.59.10 I am experiencing a crash when running the Android version. The app builds, installs and runs fine, but it crashes when trying to connect to a remote debugger (react-native-debugger or Chrome). This affects Android only, iOS works fine.
Here is what adb logcat '*:E' reports when the crash occurs:
7-09 18:01:10.822  9024  9115 E AndroidRuntime: Process: com.acme.ifa.debug, PID: 9024
07-09 18:01:10.822  9024  9115 E AndroidRuntime: java.lang.NoClassDefFoundError: Failed resolution of: Lio/branch/referral/util/BRANCH_STANDARD_EVENT;
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at io.branch.rnbranch.RNBranchModule.getConstants(RNBranchModule.java:262)
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at com.facebook.react.bridge.JavaModuleWrapper.getConstants(JavaModuleWrapper.java:136)
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at android.os.Handler.handleCallback(Handler.java:873)
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:99)
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:193)
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:232)
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at java.lang.Thread.run(Thread.java:764)
07-09 18:01:10.822  9024  9115 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "io.branch.referral.util.BRANCH_STANDARD_EVENT" on path: DexPathList[[zip file "/data/app/com.acme.ifa.debug-lIhzIdDgqfx74SieP8wwnw==/base.apk"],nativeLibraryDirectories=[/data/app/com.acme.ifa.debug-lIhzIdDgqfx74SieP8wwnw==/lib/x86, /data/app/com.acme.ifa.debug-lIhzIdDgqfx74SieP8wwnw==/base.apk!/lib/x86, /system/lib]]
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
07-09 18:01:10.822  9024  9115 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)

Here is some relevant info about the environment from package.json
"dependencies": {
...
"react-native-branch": "3.0.1",
...

From android/app/build.gradle
defaultConfig {
        applicationId "com.acme.ifa"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 176
        versionName "2.6.5"
        resValue "string", "build_config_package", "com.acme.ifa"
    }
    ...

buildTypes {
        debug {
            applicationIdSuffix "debug"
            multiDexEnabled false
            signingConfig signingConfigs.debug
            resValue "string", "deployment_key", ""
        }
        ...

From android/build.gradle:
buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 21
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = '28.0.0'
    }
    repositories {
        jcenter()
        mavenCentral()
        google()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:3.4.0')
        classpath('com.google.gms:google-services:3.1.1')
    }
}

From gradle-wrapper.properties:
...
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
...

react-native info:
  React Native Environment Info:
    System:
      OS: macOS 10.14.5
      CPU: (8) x64 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
      Memory: 601.60 MB / 16.00 GB
      Shell: 5.3 - /bin/zsh
    Binaries:
      Node: 12.4.0 - /usr/local/bin/node
      Yarn: 1.16.0 - /usr/local/bin/yarn
      npm: 6.9.0 - /usr/local/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.1, macOS 10.14, tvOS 12.1, watchOS 5.1
      Android SDK:
        API Levels: 23, 24, 25, 26, 27, 28
        Build Tools: 23.0.1, 25.0.2, 25.0.3, 26.0.1, 26.0.2, 26.0.3, 27.0.3, 28.0.0, 28.0.0, 28.0.1, 28.0.2, 28.0.3
        System Images: android-25 | Google APIs Intel x86 Atom, android-25 | Google Play Intel x86 Atom, android-26 | Google APIs Intel x86 Atom, android-27 | Google APIs Intel x86 Atom, android-28 | Google APIs Intel x86 Atom
    IDEs:
      Android Studio: 3.4 AI-183.6156.11.34.5692245
      Xcode: 10.1/10B61 - /usr/bin/xcodebuild
    npmPackages:
      react: 16.8.3 => 16.8.3
      react-native: 0.59.10 => 0.59.10
    npmGlobalPackages:
      create-react-native-app: 1.0.0
      react-native-cli: 2.0.1
      react-native-git-upgrade: 0.2.7
      react-native-rename: 2.2.2

NOTES:

*

*before the upgrade (react-native 0.57.8 and react-native-branch ^2.3.3), this crash was not present.

*the crash happens both when running in the emulator and running on USB connected device

UPDATE: dependencies from android/app/build.gradle:
dependencies {
    implementation project(path:':@react-native-community_netinfo', configuration:'default')
    implementation project(path:':react-native-webview', configuration:'default')
    implementation project(path:':mobile-orientation-lock', configuration:'default')
    implementation project(path:':react-native-detect-navbar-android', configuration:'default')
    implementation project(path:':mobile-custom-webview', configuration:'default')
    implementation project(path:':react-native-fs', configuration:'default')
    implementation project(path:':react-native-reanimated', configuration:'default')
    implementation project(path:':react-native-branch', configuration:'default')
    implementation project(path:':react-native-vector-icons', configuration:'default')
    implementation project(path:':react-native-splash-screen', configuration:'default')
    implementation project(path:':react-native-gesture-handler', configuration:'default')
    implementation project(path:':react-native-config', configuration:'default')
    implementation project(path:':react-native-linear-gradient', configuration:'default')
    implementation project(path:':react-native-immersive', configuration:'default')
    implementation project(path:':react-native-i18n', configuration:'default')
    implementation project(path:':react-native-device-info', configuration:'default')
    implementation project(path:':react-native-code-push', configuration:'default')
    implementation project(path:':react-native-camera', configuration:'default')
    implementation('com.google.zxing:core:3.3.2')
    implementation('org.jetbrains.kotlin:kotlin-stdlib:1.2.71')
    implementation('com.google.code.gson:gson:2.8.5')
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation('androidx.appcompat:appcompat:${rootProject.ext.supportLibVersion}')
    implementation('com.facebook.fresco:fresco:1.10.0')
    implementation('com.facebook.fresco:animated-gif:1.10.0')
    implementation('com.facebook.react:react-native:+')  // From node_modules
    implementation('com.crashlytics.sdk.android:crashlytics:2.9.1@aar') {
        transitive = true
    }
    implementation('com.google.android.gms:play-services-analytics:12.0.1')
    implementation('androidx.multidex:multidex:2.0.0')
}

A: I "fixed" this by removing react-native-branch from the project. It turns out we are not using it anymore, so lucky coincidence :)

A: react-native reanimated do this with your app, chrome does not support the reanimated and crash your app on debug mode


text:
Q: Dynamics AX 2012 C# Compilation Warning We receive the following error when compiling our C# Visual Studio project at some client sites.  The C# project is embedded in the AOT.
MSB3270: There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "Microsoft.Dynamics.AX.ManagedInterop", "x86". This mismatch may cause runtime failures.
Opening the project in Visual Studio, the target processor is set for "Any"   I know it is only a warning, but I'd like to resolve it if possible.
Any suggestions?
Thanks,

*

*Brad

A: This was fixed by restarting the AOS.
No idea what was going on.


text:
Q: Identity function continuous function between usual and discrete metric space Let $X = (\mathbb R, d)$ be the usual real line and $Y =(\mathbb R, d')$ be the set R with discrete metric.
Show that identity map from $X$ to $Y$ is not continuous but open as well as closed.
On the other hand, the identity map from $Y$ to $X$  is continuous which is neither open nor closed.
My attempt :
we know that for continuity we want to show that inverse image of the open set is open.
Any singleton set   $\{x\}$  is open in discrete metric space and hence its inverse image under identity map is also $\{x\}$, which is not an open set in usual metric.
Hence, identity map is not continuous.
Again if identity map have domain with discrete metric then it is always continuous.
Am I correct??
Now for open map (closed), we want to show that image of open (closed) set is open (closed).
How to use this definition to prove open and closed.
Please help. Thank you.

A: What you did is correct.
Now, you have to keep in mind that, with respect to the discrete metric every set is open and every set is closed. In fact, given a set $S$, $S=\bigcup_{x\in S}\{x\}$ and, since each singleton is open, $S$ is open. And since every set is open, every set is closed too. Therefore, every map from an arbitrary metric space into a discrete one is both open and closed.
In order to prove the the identity from $Y$ to $X$ is neither open nor closed, you can take, for instance, the set $A=[0,1)$. It is neither open nor closed in $X$ but it is both open and closed in $Y$. Since $\operatorname{id}(A)$, $\operatorname{id}$ is neither open nor closed.


text:
Q: How to get Wordpress TwentyTwelve comments.php to work on another theme? Currently, I'm using a Wordpress theme that is built on Foundation. However, the theme doesn't have its own comment.php file and it's currently using the soon to be deprecated comments.php from wordpress\wp-includes\theme-compat folder.
So what I did is to copy/paste the latest comments.php file from the TwentyTwelve theme folder into my current theme folder. However, this results in an error:
Warning: call_user_func() expects parameter 1 to be a valid callback, function 'twentytwelve_comment' not found or invalid function name in C:\xampp\htdocs\wordpress\wp-includes\comment-template.php on line 1334

...since it's not properly wired up. What should I do to get the comments.php to work properly?

A: TwentyTwelve uses a function of its own to format comments-- twentytwelve_comment. In the file you copied-- comments.php-- you should see this line:
<?php wp_list_comments( array( 'callback' => 'twentytwelve_comment', 'style' => 'ol' ) ); ?>

That callback is to a function that doesn't exist in your theme, since it is defined in TwentyTwelve's functions.php and not yours. You can...

*

*Remove the callback-- this part 'callback' => 'twentytwelve_comment',. It is optional.  WordPress will use a default formatting function-- actually a method of the Walker_comment class. Its a bit hard to find. :)

*Copy TwentyTwelve's callback function to your theme; don't do anything to disguise where you got it

*Create your own callback


text:
Q: Why 'TEFL" is pronounced with Schwa /tef.əl/ although it's an abbreviation? Why 'TEFL" is pronounced with Schwa /tef.əl/ although it's an abbreviation?
What is the logic behind this of insertion a schwa sound?

A: 'TEFL' has two possible pronunciations:

*

*[ˈtef.əl]: with a schwa

*[ˈtef.l̩]: with a syllabic1 L

The reason Anglophones insert a schwa is because the tautosyllabic coda cluster2 */-fl/ is not found in English (Phonotactic Constraints) and native speakers are unfamiliar with that cluster so they insert a schwa there or make the L syllabic. If it were */tefl/ (single syllable), it would violate the phonotactics of English.

NOTES:

*

*Syllabic consonants are consonants that are capable of making a syllable on their own. In English, /l m n r/ can be syllabic when they come right after an obstruent (/p t k s g f/ etc) in an unstressed syllable for instance the second syllable of button is usually pronounced as a syllabic n (not every individual pronounces it with a syllabic n though)

*'Tautosyllabic' means being the same syllable, for example, the n and t in ant are in the same syllable so they're tautosyllabic. 'Coda' refers to the consonants after the nucleus (usually vowel) of the syllable (e.g. nt in ant). According to English Phonotactic Constraints, English doesn't have OBSTRUENT + SONORANT in the same syllable in the coda. (Obstruents: p, t, k, s, k, f etc. Sonorants: l, m, n etc.) Note that this is entirely different from OBSTRUENT + SYLLABIC consonant sequence.


text:
Q: Using the result of an outer query as part of a subquery I have a query in postgres that looks like this
SELECT events.startDate, managers.id, manager.name, manager.goneDate
FROM mentions, managers, events, categories
WHERE
managers.id = mentions.manager_id AND
events.id = mentions.event_id AND
categories.id = events.category_id

I also have a query that does some division that I need to join to it using the result of the events.startDate for each row, that query looks like this...
SELECT round((cast count(manager.id)
FROM mentions, managers, events
WHERE
managers.id = mentions.manager_id AND
events.id = mentions.event_id AND
events.eventdate >= (to_date('2012-08-18', 'YYYY-MM-DD') - INTERVAL '90 days') AND
events.eventdate <= '2012-08-18'
AND mentions.manager_id = 1
group by managers.id) as decimal)
/
(SELECT count(managers.id)
 FROM mentions, managers, events
 WHERE
managers.id = mentions.manager_id AND
events.id = mentions.event_id AND
events.eventdate >= (to_date('2012-08-18', 'YYYY-MM-DD') - INTERVAL '90 days') AND
events.eventdate <= '2012-08-18'
AND mentions.manager_id = 1
group by managers.id)
* 100), 2) as "result"

So essentially I need to join the result on to the "results" of my first query and instead of the hard coded date (2012-08-18) on the 2nd query I need to use the events.startDate for each row of the 1st query.


text:
Q: Почему не влезает последний блок на iPhone / iPad?

.overlay {
    width: 100%;
    height: 100vh;
    position: fixed;
    overflow: auto;
    left: 0;
    top: 0;
    background: rgba(0, 0, 0, 0.6);
    z-index: 1000;
}

.popup {
  width: 375px;
  margin: 0 auto;
  position: relative;
  height: 100vh;
}

.content {
  background: #fff;
  font-size: 40px;
  text-align: center;
}

a {
  background: red;
  text-decoration: none;
  color: #fff;
  margin: 0 auto;
}

text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text

      RED BUTTON</>

Есть попап http://prntscr.com/lc6ipv , в самом низу есть большая красная кнопка до которой невозможно доскроллить.
Его оверлэй и сам попап имеют такие стили:
.overlay {
  display: block;
  width: 100%;
  height: 100vh;
  position: fixed;
  overflow: auto;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 1000;
}

.popup {
    width: 100%;
    position: relative;
    height: 100vh;
}

Почему я не могу доскроллить до этого блока? На десктопах все ок

A: Проблема в height: 100vh; можете использовать top:0; bottom:0 если вам необходимо сделать overlay на всю страницу.
Так же можете установить высоту overlay при помощи JavaScript. Тут описано как получить правильный viewport и дальше просто применить полученное значение для overlay.
    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    document.querySelector('.overlay').style.height = h;

P.S Этот баг хорошо описан тут, статья на английском но благодаря картинкам все будет более чем понятно :)


text:
Q: Detect dismissal of UIActivityViewController I need to present a view, after UIActivityViewController will move to parent VC
...
UIActivityViewController *avvc = [[UIActivityViewController alloc] initWithActivityItems:shareItems applicationActivities:nil];
[self presentViewController:avvc animated:YES completion:nil];

A: I just want to clarify that the boolean value completed represents the completion state of the individual UIActivity. If the UIActivityViewController is dismissed without any action, the value for activityType will be nil and the value of completed will be false.
[avvc setCompletionWithItemsHandler:^(UIActivityType _Nullable activityType, BOOL completed,
                                      NSArray * _Nullable returnedItems,
                                      NSError * _Nullable activityError) {

    if (activityType == nil)    {
        NSLog(@"UIActivityViewController dismissed without any action.");
    } else {
        NSLog(@"completionWithItemsHandler, activityType: %@, completed: %d, returnedItems: %@, activityError: %@",
         activityType, completed, returnedItems, activityError);
    }
}];

A: Xamarin / C#
avvc.CompletionWithItemsHandler = MyCompletionWithItemsHandler;

// ...

void MyCompletionWithItemsHandler(NSString activityType, bool completed, NSExtensionItem[] returnedItems, NSError error)
{
    if (completed)
    {
        // Did not tap Cancel
    }
    else
    {
        // Cancel was tapped
    }
}

A: Swift 3 Version
avvc.completionWithItemsHandler = { (activityType, completed:Bool, returnedItems:[Any]?, error: Error?) in
   if completed {
      // Do something
   }
}

A: [avvc setCompletionHandler:^(NSString *activityType, BOOL completed) {
    NSLog(@"after dismiss");
    //Present another VC
}];

Hope this help you.


text:
Q: A comparison between the verbs "figure out" and "grasp" Please imagine there is a new designed tuna can with a particular cap opening design which requires a little thinking about the way you have to open it. Your friend gives you the can and asks you to open it. After a couple of minutes he returns to you and wants to ask you if you could open it. Which one of the following verbs works in my self-made sentence below?
For me, they both mean the same:

*

*Can you figure out how to open this?

*Can you grasp how to open this?

Based on dictionary definitions, figure out works here, but in my opinion "grasp" should not sound weird to a native ear.

A: When we figure out something, we are actively trying to understand or solve a problem.

It takes most people some time to figure out how to use new software.
I couldn't figure out the solution to the last maths problem.

When we grasp something, the information or solution is already there, and the question becomes one of comprehension - can we understand this concept that already exists. For example:

The student shows a weak grasp of physics.
She felt the solution was within her grasp.

In your examples, 'Can you figure out how to open this?' seems far more fitting, because the people involved currently can't open the container, but they are trying to solve the problem of how to do so.


text:
Q: Cannot resize launcher icons in Unity I am using Oneiric. I have Unity 4.28 installed. I have also installed CCSM, Ubuntu Tweak, Dconf tools and MyUnity. I have tried resizing the launcher icons using these tools, but none of them are having the desired effect.
It would help if any one could provide suggestions on how to resolve this issue.

A: Probably because you're in a unity-2d session. Open a terminal, copy & paste this command in, press enter. Unity (3d) will return ubuntu, unity-2d will mean just that
echo $DESKTOP_SESSION

unity-2d doesn't support launcher resize yet, it's possible but that's another question.

A: Open CompizConfig Settings Manager. Go to Ubuntu Unity Plugin and go to tab Experimental.
Launcher icon size is the option you need.

A: Well this worked for me in 12.04. I have to use Unity-2D on my old laptop.
http://www.dedoimedo.com/computers/ubuntu-unity-2d-resize-launcher.html


text:
Q: Round off dict values to 2 decimals I'm having a hard time rounding off values in dicts. What I have is a list of dicts like this:
y = [{'a': 80.0, 'b': 0.0786235, 'c': 10.0, 'd': 10.6742903}, {'a': 80.73246, 'b': 0.0, 'c':
10.780323, 'd': 10.0}, {'a': 80.7239, 'b': 0.7823640, 'c': 10.0, 'd': 10.0}, {'a':
80.7802313217234, 'b': 0.0, 'c': 10.0, 'd': 10.9762304}]

I need to round off the values to just 2 decimal places.
When I try the following:
def roundingVals_toTwoDeci(y):

    for d in y:
        for k, v in d.items():
            v = ceil(v*100)/100.0
            print v
            d[k] = v
    return
roundingVals_toTwoDeci(y)
s = json.dumps(y)
print s

I get:
0.0
0.0
18.2
0.0
27.3
54.5
0.0
0.0
0.0
[{"a": 0.0, "b": 0.0, "c": 27.300000000000001, "d": 0.0, "e": 54.5, "f": 0.0, "g": 18.199999999999999, "h": 0.0, "i": 0.0}]

I need to make this work with versions 2.4+ and so am not using dict comprehensions.
First, I am having a hard time looping through all the key, values in all the dicts in the original.
Second, this result has just 1 decimal point instead of 2 when it prints inside the function?
Third, why is the 'json.dumps' and then 'print' not showing the values from inside the function?
EDIT:
Working with @Mark Ransom's answer below, I get the desired o/p. However, I have to urlencode the json.dumps value and send it to a URL. At the URL, it decodes the values into all the decimal places. So, for example, if, josn.dumps gives {"a": 9.1}, the URL shows it (after urlencode) as 9.10034254344365. The modified code is as below:
class LessPrecise(float):
    def __repr__(self):
        return str(self)

def roundingVals_toTwoDeci(y):
    for d in y:
        for k, v in d.items():
            v = LessPrecise(round(v, 2))
            print v
            d[k] = v

roundingVals_toTwoDeci(y)
j = json.dumps(y)
print j

params = urllib.urlencode({'thekey': j})

print json.dumps gives {"a": 9.1}
At the URL after urlencode, it gives 9.1078667322034 instead of 9.1as in the following:
Output:::
100.0
0.0
0.0
0.0
100.0
0.0
0.0
0.0
81.8
0.0
18.2
0.0
90.0
0.0
0.0
10.0
[{"a": 100.0, "b": 0.0, "c": 0.0, "d": 0.0}, {"a": 100.0, "b": 0.0, "c": 0.0, "d": 0.0}, {"a":
81.8,  "b": 0.0, "c": 18.2, "d": 0.0}, {"a": 90.0, "b": 0.0, "c": 0.0, "d": 10.0}]

At the URL:
9.100000381469727

The JSON string after json.dumps()
[{"a": 80.0, "b": 0.0, "c": 10.0, "d": 10.0}, {"a": 100.0, "b": 0.0, "c": 0.0, "d": 0.0}, {"a":
80.0, "b": 0.0, "c": 10.0, "d": 10.0}, {"a": 90.0, "b": 0.0, "c": 0.0, "d": 10.0}]

The urlencode string - after decoding at http://meyerweb.com/eric/tools/dencoder/
thekey=[{"a": 80.0, "b": 0.0, "c": 10.0, "d": 10.0}, {"a": 100.0, "b": 0.0, "c": 0.0, "d":
0.0}, {"a": 80.0, "b": 0.0, "c": 10.0, "d": 10.0}, {"a": 90.0, "b": 0.0, "c": 0.0, "d": 10.0}]

At the URL, I get values like 18.200000762939453(this value is from a later script run)

A: Taking the best bits from a couple of other answers:
class LessPrecise(float):
    def __repr__(self):
        return str(self)

def roundingVals_toTwoDeci(y):
    for d in y:
        for k, v in d.items():
            v = LessPrecise(round(v, 2))
            print v
            d[k] = v

>>> roundingVals_toTwoDeci(y)
80.0
10.0
0.08
10.67
80.73
10.78
0.0
10.0
80.72
10.0
0.78
10.0
80.78
10.0
0.0
10.98
>>> s=json.dumps(y)
>>> s
'[{"a": 80.0, "c": 10.0, "b": 0.08, "d": 10.67}, {"a": 80.73, "c": 10.78, "b": 0.0, "d": 10.0}, {"a": 80.72, "c": 10.0, "b": 0.78, "d": 10.0}, {"a": 80.78, "c": 10.0, "b": 0.0, "d": 10.98}]'

A: import json

y = [{'a': 80.0, 'b': 0.0786235, 'c': 10.0, 'd': 10.6742903}, {'a': 80.73246, 'b': 0.0, 'c':
10.780323, 'd': 10.0}, {'a': 80.7239, 'b': 0.7823640, 'c': 10.0, 'd': 10.0}, {'a':
80.7802313217234, 'b': 0.0, 'c': 10.0, 'd': 10.9762304}]

def roundingVals_toTwoDeci(y):

    for d in y:
        for k, v in d.items():
            v = round(v,2) # <--- round() does exact that.
            d[k] = v # <--- You need to put the rounded v back in d
            print v
    return

roundingVals_toTwoDeci(y)
s = json.dumps(y)
print s

A: JSONEncoder uses repr, and repr prints floats with all their available precision. The only possible solutions are to inherit from JSONEncoder and round while actually converting the values to a string (which implies to copy and adapt some code from the json.encoder module), or else wrap the floats into your own type RoundedFloat and register a serializer for that. Also note that repr's behaviour depends on the Python version used.
As often with non-obvious behaviour, the observation during debugging can trick you: print uses str(), and str() rounds at a certain point, unlike repr() which shows the naked ugliness of floating point maths.
The proof is in the code:
>>> class F(float):
...     def __str__(self): return "str"
...     def __repr__(self): return "repr"
...
...
>>> print F(1)
str
>>> F(1)
repr
>>> repr(1-1e-15)
'0.999999999999999'
>>> str(1-1e-15)
'1.0'

A: Answering the second part of your question
Try replacing line 5 of your code with:
 v = round(v, 2)

This will round the number to two decimal places. Using round, I get
[{'a': 80.0, 'c': 10.0, 'b': 0.08, 'd': 10.67}, {'a': 80.73, 'c': 10.78, 'b': 0.0, 'd': 10.0}, {'a': 80.72, 'c': 10.0, 'b': 0.78, 'd': 10.0}, {'a': 80.78, 'c': 10.0, 'b': 0.0, 'd': 10.98}]

I am using Python 2.7.2. Here's all the code:
from math import ceil
import json

y = [{'a': 80.0, 'b': 0.0786235, 'c': 10.0, 'd': 10.6742903},
     {'a': 80.73246, 'b': 0.0, 'c': 10.780323, 'd': 10.0},
     {'a': 80.7239, 'b': 0.7823640, 'c': 10.0, 'd': 10.0},
     {'a': 80.7802313217234, 'b': 0.0, 'c': 10.0, 'd': 10.9762304}]

def roundingVals_toTwoDeci(y):
    for d in y:
        for k, v in d.items():
            v = round(v, 2)
            #print v
            d[k] = v
    return

roundingVals_toTwoDeci(y)
s = json.dumps(y)
print s

A: I don't understand what relates to json, but I can propose:
from math import ceil

y = [{'a': 80.0, 'b': 0.0786235, 'c': 10.0, 'd': 10.6742903},
     {'a': 80.73246, 'b': 0.0, 'c': 10.780323, 'd': 10.0},
     {'a': 80.7239, 'b': 0.7823640, 'c': 10.0, 'd': 10.0},
     {'a': 80.7802313217234, 'b': 0.0, 'c': 10.0, 'd': 10.9762304}]

class TwoDec(float):
    def __repr__(self):
        return "%.2f" % self

def roundingVals_to_TwoDeci(y,ceil=ceil,TwoDec=TwoDec):
    for d in y:
        for k, v in d.iteritems():
            d[k] = TwoDec(ceil(v*100)/100)

roundingVals_to_TwoDeci(y)
for el in y:
    print el

result
{'a': 80.00, 'c': 10.00, 'b': 0.08, 'd': 10.68}
{'a': 80.74, 'c': 10.79, 'b': 0.00, 'd': 10.00}
{'a': 80.73, 'c': 10.00, 'b': 0.79, 'd': 10.00}
{'a': 80.79, 'c': 10.00, 'b': 0.00, 'd': 10.98}

A: I know this question is old, but here is a quick one-liner solution that works at least here in Linux Python 2.7.6 and might be interesting to someone else:
y = [{ x : round(z, 2) for x,z in yi.items()} for yi in y ]

However, this might be inefficient for larger data sets, as it re-generates the list/dict structure.

A: [[round(d[key],2) for key in d] for d in y]

[{key:round(d[key], 2) for key in d} for d in y]

A: Round dictionary values one-liner
with d as the dict and here to 2 decimal places
d = {k: round(v, 2) for k, v in d.items()}
Given the subject line Round off dict values to 2 decimals, this is what most will be coming here to find.
dictionary comprehension might be used in a search


text:
Q: Not able to update specifc DataTable in DataSet private void Form1_Load(object sender, EventArgs e)
{
      da = new SqlDataAdapter("select * from record",@"database=student;server=arun-pc\mypc;integrated security=true");
      da.Fill(ds,"record");
}

private void button1_Click(object sender, EventArgs e)
{
      da.SelectCommand.CommandText = "select * from emp";
      da.Fill(ds,"emp");
      dataGrid1.DataSource = ds;
}

private void button2_Click(object sender, EventArgs e)
{
      cb = new SqlCommandBuilder(da);
      da.Update(ds.Tables[0]);
      MessageBox.Show("updated")
}

I'm not able to update table[0] but I can update in table[1] and I'm not able to find why it is so?

A: It would be a lot easier for you if you follow these tutorials here when doing your data access (be sure to choose your .net version if you're not on 2.0):
http://msdn.microsoft.com/en-us/library/fxsa23t6(v=vs.80).aspx
Start with the "Creating a Simple Data App" one
As to what is actually going wrong, if all you're finding is that no rows are being updated (update returns 0) then you should first check that the table you're sending for update actually contains modified rows..
Follow the tutorial, and do your data access that away and it will either all work out, or you'll get an error message that tells you where things went wrong :)


text:
Q: Why does adding a background image to an input (button) change it's default browser user agent styling? Here is an example:  http://jsfiddle.net/eJSGn/
input{
    padding-left: 20px;
}

input:last-of-type{
    background: url(http://skiorboard.com/wp-content/uploads/2014/03/search.png) no-repeat;
    background-size:15px 15px;
}

<input type="button" value=" Search " />
<input type="button" value=" Search " />
<input type="button" value=" Search " />

So if I have three input buttons and style the last of the three to have a background image (magnifying glass) why does the adding of this image to the third button also result in drastic changes to the button?  In chrome, for example, the third button's background turns white and the border style changes.
I want to use the browser's default styles for these buttons, but would like to be able to add a background image to the button without it making that button look totally different than the other buttons which I will not be adding icons to.

A: Your overriding the background property which browsers use to set their defaults (browser set styles have the very lowest CSS priority). It would be the same as doing.
/* This will override browser styles. */
button
{
  background: grey;
}

/* This will override the above style */
button
{
  background: black;
}

/* This will override the above style */
button
{
  background: blue!important;
}

Each one has more priority over the other therefore overriding it.


text:
Q: Method org.postgresql.jdbc4.Jdbc4Connection.unwrap is not yet implemented stack-trace:
Exception in thread "main" org.pivot4j.PivotException: java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc4.Jdbc4Connection.unwrap(Class<T>) is not yet implemented.
    at org.pivot4j.impl.PivotModelImpl.initialize(PivotModelImpl.java:202)
    at cn.sdut.pivot4j.App.main(App.java:25)
Caused by: java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc4.Jdbc4Connection.unwrap(Class<T>) is not yet implemented.
    at org.postgresql.Driver.notImplemented(Driver.java:710)
    at org.postgresql.jdbc4.AbstractJdbc4Connection.unwrap(AbstractJdbc4Connection.java:218)
    at org.postgresql.jdbc4.Jdbc4Connection.unwrap(Jdbc4Connection.java:21)
    at org.pivot4j.datasource.SimpleOlapDataSource.createConnection(SimpleOlapDataSource.java:77)
    at org.pivot4j.datasource.AbstractOlapDataSource.getConnection(AbstractOlapDataSource.java:105)
    at org.pivot4j.datasource.AbstractOlapDataSource.getConnection(AbstractOlapDataSource.java:95)
    at org.pivot4j.impl.PivotModelImpl.createConnection(PivotModelImpl.java:242)
    at org.pivot4j.impl.PivotModelImpl.initialize(PivotModelImpl.java:200)
    ... 1 more

I'm writing a simple program using Mondrain and Pivot4j. Following is the code I've written:
public class App {
    public static void main(String[] args) throws Exception {

        SimpleOlapDataSource dataSource = new SimpleOlapDataSource();
        dataSource.setConnectionString("jdbc:postgresql://localhost:5432/food_mart?user=postgres&password=111111");

        String initialMdx = "SELECT {[Measures].[Unit Sales], [Measures].[Store Cost], "
                + "[Measures].[Store Sales]} ON COLUMNS, {([Promotion Media].[All Media], "
                + "[Product].[All Products])} ON ROWS FROM [Sales]";

        PivotModel model = new PivotModelImpl(dataSource);
        model.setMdx(initialMdx);
        model.initialize(); // throws Exception
    }
}

I have no idea about why I got this Exception.

A: I'm the developer of Pivot4J and I suppose your problem to be the same with what this post describes :

*

*https://groups.google.com/d/msg/pivot4j-list/2SBlByTMNjg/434C0iw3vcEJ
You need to specify Olap4J's connections string, not that of underlying RDBMS for the data source.
For reference about connection string syntax, you can refer to API documentation for appropriate Olap4J driver implementations, that is either MondrianOlap4JDriver or XmlaOlap4JDriver.
Also, please feel free to visit our mailing list, it you have further questions about Pivot4J.
Hope this helps.
Xavier


text:
Q: Caclulate Standard Error when subtracting two effects I am working on this issue that compares two regions with the McCrary Test (Regression Discontinuity Design). It basically measures how the density of a variable of interest develops accross a pre set cut off point. In my case, we talk about density of businesses (y) and how this develops accros a geographic border [distance in m] (x). The result of the test is the log difference at the pre set cut off point. This value we call theta.
Now I have measured theta for two instances. Now I want to subtract these effect from each other (to illimate possible placebo effect). However, the question is how do I subtract these from each other and especially how do I calculate the new Standard Error and p-value (significance)
These are the results: (Standard Error in parentheses)
Test 1: 0.6298 (0.1614)
Test 2: -0.4667 (0.1048)
Net effect = Test 1 - Test 2 = 0.6298 + 0.4667 = 1.0965
Theta = 1.0965
SE = ?????


text:
Q: Как указать путь к файлу, который находится в папке пользователя, а я не знаю имя пользователя Всем привет, у меня проблема. Мне надо работать с файлами в appdata, а appdata находиться в папке пользователя, а имя пользователя соответсвенно у меня нет. Если что я работаю с библиотекой fstream, как получить имя пользователя и сделать так?:
fstream pr;
pr.open("C:\Users" + username "\AppData\LocalLow\Innersloth\Among Us"); //username это имя пользователя

A: Используйте функцию std::getenv("USERNAME") или std::getenv("USER")

A: А кто вам гарантирует, что папка профиля расположена на диске С:\users? Кто вам гарантирует, что имя папки профиля совпадает с логином?
Нужно использовать переменную окружения USERPROFILE, а не хордкодить C:\users\%USERNAME%


text:
Q: How to change the format into simple date/time format-jquery/js I want to convert : 2015-09-13T08:09:09.0Ztime format into: Sept13, 2015 08:08:09 AMwhere,
08: hours
08: mins
09: secs
and AM/PM depending on what time it is. Any idea how can i achieve this?
Thanks!!!

A: Have a look at the toLocaleString() method, it does that, except it will return the date as 9/13/2015, and convert the time to the person's local time. Implementation would be:
var date = new Date("2015-09-13T08:09:09.0Z");
date.toLocaleString();
// returns "9/13/2015, 4:09:09 AM" in the Eastern Time Zone.

You could use other methods on the date object of course, to get the exact desired effect, but it would be quite a bit of logic to write out. Alternatively, you can have a look at an excellent library called moment.js which does the heavy lifting for you. First example on their homepage does what you described.


text:
Q: snippet jQuery plugin issue This is probably fairly straightforward but I can't find a solution anywhere.
When using:
http://www.steamdev.com/snippet/
$("pre.htmlCode").snippet("html",{style:"greenlcd"});

Snippet style selector

Choose your style below.

Preview your style here.

This seems to work, except the tags are being processed like this:

How do I prevent this from happening? I hope this is clear enough!

A: Used < rather than Snippet style selector</h1>
    <div class="instructions">
        <p>Choose your style below.</p>
        <p>Preview your style here.</p>
    </div>
    <!-- 39 styles to choose from! -->

Or in case of XHTML, use <[CDATA[ ... ]]>


text:
Q: Protractor Angular 4 E2E Unexpected Token Import After several days and countless threads here and elsewhere, I cannot seem to get my e2e tests running. It seems like either there are compiling issues from TS to JS or the protractor library isn't loading. When I run the code below, I get the following message:

[13:18:39] E/launcher - Error:
  /Users/shawncasey/doctor_web_portal/e2e/e2e.spec.ts:23 import {
  E2eTest } from './e2e.page'; ^^^^^^
SyntaxError: Unexpected token import
      at createScript (vm.js:80:10)
      at Object.runInThisContext (vm.js:139:10)
      at Module._compile (module.js:616:28)
      at Object.Module._extensions..js (module.js:663:10)
      at Module.load (module.js:565:32)
      at tryModuleLoad (module.js:505:12)
      at Function.Module._load (module.js:497:3)
      at Module.require (module.js:596:17)
      at require (internal/module.js:11:18)
      at /Users/shawncasey/doctor_web_portal/node_modules/protractor/node_modules/jasmine/lib/jasmine.js:93:5
      at Array.forEach ()
      at Jasmine.loadSpecs (/Users/shawncasey/doctor_web_portal/node_modules/protractor/node_modules/jasmine/lib/jasmine.js:92:18)
      at Jasmine.execute (/Users/shawncasey/doctor_web_portal/node_modules/protractor/node_modules/jasmine/lib/jasmine.js:197:8)
      at /Users/shawncasey/doctor_web_portal/node_modules/protractor/built/frameworks/jasmine.js:132:15
      at Function.promise (/Users/shawncasey/doctor_web_portal/node_modules/protractor/node_modules/q/q.js:682:9)
      at /Users/shawncasey/doctor_web_portal/node_modules/protractor/built/frameworks/jasmine.js:104:14 [13:18:39] E/launcher - Process exited with error code 100

If I change my import {element, by, browser} from 'protractor'; to const by = require('protractor'); I get the message by.css is not a function.
There is a post already here: SyntaxError: Unexpected token import when trying to import protractor in e2e test for angular, but I'm not sure about transpiling my ts. I thought that was handled. If it isn't, how do I do it?
Here's the relevant code:
Page object:
import { browser, by, element } from 'protractor';

export class E2eTest {

    getUsernameBox() {
        return element(by.id('exampleInputEmail1'));
    }
    getPasswordBox () {
        return element(by.id('exampleInputPassword1'));
    }
    getLoginButton() {
        return element(by.class('.btn-success'));
    }

    navigateTo() {
        return browser.get('/');
    };

}

Test suite:
import { E2eTest } from './e2e.page';

describe ('Doc Portal App', () => {
    let page: E2eTest;

    beforeEach(() => {
        page = new E2eTest();
    });

    it ('Should log in to portal', () => {
        page.getUsernameBox().sendKeys('#####');
        page.getPasswordBox().sendKeys('#####');
        page.getLoginButton().click();
    });
});

Running Jasmine 3.1.0, Protractor 5.4.0, Typescript 2.9.2. My protractor.conf.js seems fine, but here's my tsconfig.app.json:
{
  "compilerOptions": {
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2016",
      "dom"
    ],
    "outDir": "../out-tsc/app",
    "target": "es6",
    "module": "es2016",
    "baseUrl": ""
  },
  "exclude": [ ]
}

Thanks in advance


text:
Q: activating threads C# i have this code in C#:
Thread t1 = new Thread(functionsActivations(3, 4000, 0, 4));
Thread t2 = new Thread(functionsActivations(3, 4000, 5, 9));
t1.start();
t2.Start();
Thread t3 = new Thread(functionsActivations(4, 4000, 0, 4));
Thread t4 = new Thread(functionsActivations(4, 4000, 5, 9));

It is not working. How can I tell it to call the method I gave it?
Secondly, I want t3 and t4 to be activated after t1 and t2 finish running. How can I do that?
Third, I want t1 and t2 to not block (so that t2 wouldn't have to wait until t1 finishes). Is what I did correct?

A: "It is not working" isn't a very clear set of symptoms. What are you observing?
EDIT: Okay, now that you've said what the compiler error is, it's much easier to diagnose. You're currently calling a method and trying to use the result as a task for the thread to execute. Assuming you actually want to make that method call when the thread is started, you want something like this:
C# 2:
Thread t1 = new Thread(delegate() { functionsActivations(3, 4000, 0, 4); });

C# 3:
Thread t1 = new Thread(() => functionsActivations(3, 4000, 0, 4));

An altnerative to having lambda expressions all over the place would be to write a utility method:
private static Action DeferFunctionActivations(int a, int b, int c, int d)
{
    return () => functionsActivations(a, b, d, d);
}

Then you could use:
Thread t1 = new Thread(DeferFunctionActivations(3, 4000, 0, 4));

etc.
For the rest of the post I'll assume C# 3.
Additionally, t1.start() should be t1.Start() - C# is case sensitive.
To answer your final point, t1 and t2 are currently independent - they won't be blocking each other unless you've got synchronization somewhere in the code that they're running.
If you only want t3 and t4 to start when t1 and t2 have finished, you could use Thread.Join:
Thread t1 = new Thread(() => functionsActivations(3, 4000, 0, 4));
Thread t2 = new Thread(() => functionsActivations(3, 4000, 5, 9));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Thread t3 = new Thread(() => functionsActivations(4, 4000, 0, 4));
Thread t4 = new Thread(() => functionsActivations(4, 4000, 5, 9));
t3.Start();
t4.Start();

Note that that means that this thread will wait until t1 and t2 have finished, too. If that's not good enough for you, there are various options but basically you'll want something else to asynchronously wait for t1 and t2 to complete. For example, you could tie up an extra thread to do that:
Thread t1 = new Thread(() => functionsActivations(3, 4000, 0, 4));
Thread t2 = new Thread(() => functionsActivations(3, 4000, 5, 9));
t1.Start();
t2.Start();
Thread t3 = new Thread(() => functionsActivations(4, 4000, 0, 4));
Thread t4 = new Thread(() => functionsActivations(4, 4000, 5, 9));
Thread t5 = new Thread(() =>
{
    t1.Join();
    t2.Join();
    t3.Start();
    t4.Start();
});
t5.Start();

Somewhat icky, but it should work.
Are you able to use .NET 4.0? If so, the Parallel Extensions framework makes a lot of this significantly easier.


text:
Q: Laravel query Builder in key/value pair I have created a table to store ticket's labels. I have saved multiple labels as comma(,) separated string in value column.
+----+-----------+-------+---------------+---------------------+---------------------+
| id | ticket_id | key   | value         | created_at          | updated_at          |
+----+-----------+-------+---------------+---------------------+---------------------+
|  9 |        22 | label | Important,Bug | 2016-10-10 14:48:07 | 2016-10-10 14:48:07 |
| 17 |        21 | label |               | 2016-10-10 16:46:13 | 2016-10-10 16:46:13 |
+----+-----------+-------+---------------+---------------------+---------------------+

Now I have to search the labels and get the associated ticket_id, My search terms is an array
array:1 [
  0 => "Important"
]

Please help me to write a query

A: You should try something like that:
$query = Model::where('value','like','%' . $array[0] . '%');

for($i = 1; $i < sizeof($array); $i++) {
    $query->orWhere('value','like','%' . $array[i] . '%');
}

return $query->get();

Warning, the first where method is only necessary after the 5.3 release. Before it, you may directly begin by an orWhere clause.

Eloquent scopes now respect the leading boolean of scope constraints.
  For example, if you are starting your scope with an orWhere constraint
  it will no longer be converted to normal where. If you were relying on
  this feature (e.g. adding multiple orWhere constraints within a loop),
  you should verify that the first condition is a normal where to avoid
  any boolean logic issues.

A: $filter = new Filter();
$query = $filter->where('key', 'label')
                ->where(function($query) use($labels) {
                    for ($i = 0; $i < count($labels); $i++) {
                        $query->orWhere('value', 'LIKE', '%' . $labels[$i] . '%');
                    }
                })
                ->get();

return $query;


text:
Q: How resume app after click notification with Java Android? I create a notification and I want to resume app after click notification. Now when I click notification , a notification dissapear , I want to resume my app (when is minimalize).
  public static void getSynchronizeNotification(Context context, DataResponse dataResponse) {

        Bitmap Largeicon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(NOTIFICATION_SYNCHRONIZE_ID);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
        KeyguardManager km = (KeyguardManager) context.getSystemService(KEYGUARD_SERVICE);
        final KeyguardManager.KeyguardLock kl = km.newKeyguardLock("IN");
        kl.disableKeyguard();

        PowerManager pm = (PowerManager) context.getSystemService(POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "SMOK Komunal");
        wl.acquire();
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
                .setCategory(Notification.CATEGORY_PROMO)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Zmiany po synchronizacji...")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(buildNotificationAfterSynchronizeText(dataResponse)))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setLargeIcon(Largeicon)
                .setContentIntent(pendingIntent)
                .setVibrate(vibratePattern)
                .setLights(Color.GREEN, 2000, 2000)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        notificationManager.notify(0, notificationBuilder.build());
//        wl.release();
    }

A: Edit this line
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);

A: I do this and it works :
In MainAcitivity I have :
public static Context currentContext;

Next in all activity in onCreate and onResume and do this :
MainActivity.currentContext = this;

And next when I build a notification I do this :
Intent intent = new Intent(context, MainActivity.currentContext.getClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

A: This works;
<activity android:name=".YourActivity" android:launchMode="singleTop">