text:
Q: Jquery replace a specific character combination I can't figure out why my jquery replacement code wouldn't work.
I try to make the follow replacement:
http://mysite.com/_thumbs/0000312/0312718/0312718_$varm.jpg

I added '$var' to the position where I want to put a number, we can take '1' for now.
So I need to replace $var for 1.
What I tried;
 var img = $('img', this).attr('src'); // I grabs the image url like above.
 img.replace(/$var/, 1)

But nothing happens.
Thanks in advance!
Nick

A: The dollar sign is a special character in regular expressions.
img.replace(/\$var/, "1");

Escaping the $ with a backslash will tell JavaScript that you want it to match a dollar sign. Otherwise, $ means "match the end of the search string".
edit — also note that if you want the updated string you'll need to save the return value from calling .replace():
img = img.replace(/\$var/, "1");

(You can of course save the replacement results in a different variable.)


text:
Q: Error when fitting elements found in data to its cumulative distribution I have a large simulated data set in which I have passed through values and what not for an analysis. My main objective is to take actual, real record values and compare it the simulated data via cumulative distribution.
I start out by defining the method of going through each bin of the data set by taking values that have a certain value x and match it to the "real" data analyzed with the same value x
bins = np.linspace(SimData.min(),SimData.max(), 24)

def CumuProb(SimData, bins, x, realValue):
    h, bins_ = np.histogram(be, bins=bins)
    hcum = np.cumsum(h)/float(np.cumsum(h).max())

    cbins = np.zeros(len(bins)+1)
    cbins[1:-1] = bins[1:]-np.diff(bins[:2])[0]/2.
    cbins[-1] = bins[-1]

    hcumc = np.linspace(0,1, len(cbins))
    hcumc[1:-1] = hcum

    p = [x, realValue]

    yi = np.interp(p[1],cbins, hcumc)
    return [p[1],yi]

This method works for large values fine. But, if I were to pass this through values <<1 but >0, this miserably fails.
For example, performing, on my project using this method gives:

Where you can see at the very bottom, their is 2 points, when their should be about 10 points all on the blue line (the actual data).
The main culprit is found from this traceback:
RuntimeWarning: invalid value encountered in divide hcum = np.cumsum(h)/float(np.cumsum(h).max())
So this has to do how I am most likely defining my bin size, which is defined at bin=np.linspace(np.log(binding).min(),np.log(binding).max(),24), which is going through the logarithmic x-axis values in the plot above for binning.
How do I fix this?

A: I can't be 100% sure, since the question lacks a lot of relevant information needed, but judging from how I intended to use this function, it seems odd to put realValue into the interpolation. If, what the name suggests, x is the x axis value of the data point to be investigated, the interpolation should take x in:
yi = np.interp(x,cbins, hcumc)
return [x,yi]

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does "SchemeError: pair is not callable" mean? I'm running a Scheme program and getting an error when I run this code with s = (1 2 3 4 5), saying SchemeError: pair is not callable: (1 2 3 4 5). I know what this error means in Python, but I'm not sure how it applies to Scheme.
This is my program.
(define (ordered? s)
    (define (helper val lastVal newS)
        (if (null? cdr(newS))
            (val)
            (if (<= lastVal car(newS))
                (helper #t car(newS) cdr(newS))
                (helper #f car(newS) cdr(newS))
            )
        )
    )
    (helper #t 0 s)
)

A: So I figured it out. I was using the car and cdr procedures wrong, so I was getting extra parenthesis around my list.


text:
Q: Alphabetically sort elements of a ListView I'm trying to alphabetically sort elements that I add to my ListView, using the Comparable java interface and its method Compareto().
So here is the code of the adapter I implemented : I try to use the method Collections.sort in addLocation().
You can check other files of my project on this post

public class LocationAdapter extends BaseAdapter {

        private List<Location> Locations;
        int monLayout;
        LayoutInflater inflater;

        public LocationAdapter(Context context, int layout){
            monLayout=layout;
            inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            Locations = new ArrayList<Location>();
        }

        private class Location implements Comparable{
            public String name;
            public String address;
            public Long date;

            public Location(String _name,String _address , Long _date){
                name=_name;
                address=_address;
                date=_date;

            }

            @Override
            public int compareTo(Object another) {

                int res;

                Location loc=(Location)another;
                char firstLetter = loc.name.charAt(0);
                char thisFirstLetter = this.name.charAt(0);

                if(thisFirstLetter<firstLetter){
                    res=1;
                }
                else if(thisFirstLetter<firstLetter){
                    res=-1;
                }
                else
                {
                    res=0;
                }

                return res;
            }
        }

        private class ViewHolder{

            TextView name_view;
            TextView address_view;
            TextView date_view;

            public ViewHolder(View rowLayout){

                name_view = (TextView)rowLayout.findViewById(R.id.name);
                date_view = (TextView)rowLayout.findViewById(R.id.date);
                address_view = (TextView)rowLayout.findViewById(R.id.address);
            }
        }

        public void addLocation(String _name,String _address,Long _date){
            //Création d'une nouvelle location avec les données en paramètres
            Location new_loc = new Location(_name, _address,_date);

            //Ajout de la location à la liste des locations
            Locations.add(new_loc);
            Collections.sort(Locations);
        }
    /*Méthodes de la classe mère*/

    @Override
    public int getCount() {
        return Locations.size();
    }

    @Override
    public Object getItem(int position) {
        return Locations.get(position);
    }

    @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view = convertView;

            if (view == null)
                view = inflater.inflate(monLayout, parent, false);

            ViewHolder holder = (ViewHolder)view.getTag();
            if (holder == null)
            {
                holder = new ViewHolder(view);
                view.setTag(holder);
            }

            Location location = (Location)getItem(position);

            holder.name_view.setText(location.name);
            holder.address_view.setText(location.address);

            Date date=new Date(location.date);

            SimpleDateFormat df = (SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM);
            String dateText = df.format(date);
            holder.date_view.setText(dateText);

            return view;
        }
}

A: Use custom Comparator:
Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.compareToIgnoreCase(s2);
        }
    });

or
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

In your order u can do like that:
Remove implements and use it instead of your Collections.sort(Locations);
Collections.sort(Locations, new Comparator<Location>() {
        @Override
        public int compare(final Location object1, final Location object2) {
            return object1.name.compareTo(object2.name);
        }
    }
);


text:
Q: FactoryGirl build attributes with sequence returns nil I have a very simple factory with sequence
FactoryGirl.define do

  factory :lecture do
    sequence(:name) {|n| "lecture #{n}" }
    sequence(:slug) {|n| "lecture-#{n}" }
  end
end

When I build it - it looks fine
(FactoryGirl.build :lecture)
=> #<Lecture id: nil, slug: "lecture-20", name: "lecture 20", position: nil, created_at: nil, updated_at: nil>

but when I try to access the attributes, I only get nil values
(FactoryGirl.build :lecture).attributes
=> {"name"=>nil,
 "slug"=>nil,
 "id"=>nil,
 "position"=>nil,
 "created_at"=>nil,
 "updated_at"=>nil}

When I use another factory without a sequence, it works fine. Also, using attributes_for works fine
FactoryGirl.attributes_for(:lecture)
=> {:name=>"lecture 23", :slug=>"lecture-23"}

I'd like to be able to use build so I get all attributes, including foreign-keys, but somehow it returns nil values... Any ideas what I might be doing wrong or how to fix it?


text:
Q: What happens to TCP connection on 3G tower switching? I'm randomly getting IOError: request data read error in Django's POST handler while uploading data on 3G network. The question why Django raises that particular exception has already been answered (summary: allegedly happens when client dropped TCP connection). However, in my case I'm trying to solve underlying issue.
From my attempts to narrow down the issue, I've found that:

*

*not reproducible on WiFi

*not reproducible on GPRS only

*reproducible on various types of handsets (both Android and iPhone) and multiple carriers

*seems to not have happened in some locations

*seems to have happened in other location, especially when I could see the data speed indicator switching between 3G, H and H+ (UMTS, HSDPA and HSPA+)

My wild guess is that what happens there is switching towers. So what happens to TCP connection when 3G switches between towers?

A: The TCP connection itself should not normally see any interruption to connectivity when you handover in a well performing network, and even if it did TCP would normally simply back off and retry.
There are actually different types of handover in 3G networks depending on what the 'tower' you are moving from is connected to in the operators access network and what the access nodes in turn are connected to in the operators core network. It also depends on how the core network is configured - some networks will have a one to one mapping between access nodes and core nodes and some will allow pools of access nodes share core nodes which will reduce the likelihood of having to transfer between one core node and another.
The following guide gives a good overview of handover types in a 3G network:
http://www.3g4g.co.uk/Tutorial/ZG/zg_handover.html


text:
Q: WooCommerce - Send New Order / Customer Invoice Email from functions.php file I am trying to send new order email and customer invoice email through functions.php file.
How to fire complete order object to send as an email?
I am trying two different type of code.
add_action('woocommerce_payment_complete', 'my_custom_checkout_field_looking');
function my_custom_checkout_field_looking( $order_id ) {
    $order = new WC_Order( $order_id );

    // first type of Code. Send Email but did not send complete order object.

    $mailer = WC()->mailer();
    $subject = 'New Order Email # ' . $order_id;
    $mailer->send( 'example@gmail.com', $subject, $mailer->wrap_message( $subject, $order ), '', '' );

    // Second type of Code. Do not send email and doing nothing

    global $woocommerce;
    $mailer2 = $woocommerce->mailer();
    // Email customer with order-processing receipt
    $email = $mailer2->emails['WC_Email_Customer_Invoice'];
    $email->trigger( $order );
    // Email admin with new order email
    $email = $mailer2->emails['WC_Email_New_Order'];
    $email->trigger( $order );
}

A: I think you need such type of code.
add_action('woocommerce_thankyou', 'my_custom_new_order_email');
function my_custom_new_order_email( $order_id ) {

        $order = new WC_Order( $order_id );

        $billing_address = $order->get_formatted_billing_address(); // for printing or displaying on web page
        $shipping_address = $order->get_formatted_shipping_address();
        $email = $order->billing_email;
        $name = $order->billing_first_name.' '.$order->billing_last_name;
        $billing_phone = $order->billing_phone;
        $date = date('M d, Y');

        $data   = '';
        $data   .= "

        You have received an order from $name. The order is as follows:

        Order # $order_id ( $date )

";
        if( sizeof( $order->get_items() ) > 0 ) {
            $data   .=    "

            Product

            Quantity

            Price

";
            $data   .= $order->email_order_items_table( false, true );
            $data   .=  "

";
            if ( $totals = $order->get_order_item_totals() ) {
                $i = 0;
                foreach ( $totals as $total ) {
                $i++;
                $label =    $total['label'];
                $value = $total['value'];
                $data .= "

                $label
                $value

";
                }
            }
            $data .= "

";
        }

        $data .=
        "

        Customer details

        Email:

        $email

        Tel:
        $billing_phone

Billing address

 $billing_address

Shipping address

 $shipping_address

";

        $mailer = WC()->mailer();
        $subject = 'New Customer Order';
        $mailer->send( 'abc@example.com,def@example.com', $subject, $mailer->wrap_message( $subject, $data ), '', '' );
}

Hopefully It will work for you.
Thanks


text:
Q: Sending sms and ussd in a C#.net application What is a good library to use to utilize sms and ussd services in a C#.net application?

A: I am currently using this one http://www.smsco.it/tomcat/en/sms_tutorials/sms_from_c_sharp.jsp for SMS and it's working fine!

A: MessagingToolkit is supposed to be good. I've never used it myself though, so I can't vouch for it.
You can find out more at http://platform.twit88.com.


text:
Q: Recommendations for aggregating MySQL data (millions of rows) Can anyone recommend a strategy for aggregating raw 'click' and 'impression' data stored in a MySQL table with over 100,000,000 rows?
Here is the table structure.
CREATE TABLE `clicks` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `companyid` int(11) DEFAULT '0',
  `type` varchar(32) NOT NULL DEFAULT '',
  `contextid` int(11) NOT NULL DEFAULT '0',
  `period` varchar(16) NOT NULL DEFAULT '',
  `timestamp` int(11) NOT NULL DEFAULT '0',
  `location` varchar(32) NOT NULL DEFAULT '',
  `ip` varchar(32) DEFAULT NULL,
  `useragent` varchar(64) DEFAULT NULL,
  `processed` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `type` (`type`),
  KEY `companyid` (`companyid`),
  KEY `period` (`period`),
  KEY `contextid` (`contextid`)
) ENGINE=MyISAM AUTO_INCREMENT=21189 DEFAULT CHARSET=latin1;

What I want to do is make this data easier to work with. I want to extract weekly and monthly aggregates from it, grouped by type, companyid and contextid.
Ideally, I'd like to take this data off the production server, aggregate it and then merge it back.
I'm really in a bit of a pickle and wondered whether anyone had any good starting points or strategies for actually aggregating the data so that it can be queried quickly using MySQL. I do not require 'real time' reporting for this data.
I've tried batch PHP scripts in the past but this seemed quite slow.

A: You can implement a simple PHP script with the whole monthly/weekly data aggregation logic and make it execute via cron job at a given time. Depending on the software context, it could possibly be scheduled for running at night. Additionally, you could pass a GET parameter in the request for recognizing the request source.

A: You might be interested in MySQL replication... set up a 2nd server who's sole job is just to run the reports on the replicated copy of the data set, and therefore you can tune it specifically for that job. If you set up your replication scheme as master-master, then when the report server updates it's own tables based the report findings, those database changes will automatically replicate back over to the production server.
Also I would highly recommend you read High Performance MySQL, 3rd Ed., and take a look at http://www.mysqlperformanceblog.com/ for further info on working with massive datasets in MySQL


text:
Q: SciChart Realtime zoom with minimum axis range I have a FIFO Real Time chart (pretty much taken from their published Example) of a SciChart graph. As it renders, it starts out completely zoomed in very close and as the line is drawn, it zooms out to accommodate the full size of the line.
        <s:SciChartSurface.XAxis>
            <s:NumericAxis x:Name="axisX" MinHeight="50" AutoRange="Always" AxisTitle="{Binding Path=XAxisTitle}" DrawMinorGridLines="False" DrawMinorTicks="False" TextFormatting="0.##">
                <s:NumericAxis.GrowBy>
                    <s:DoubleRange Max="0.1" Min="0.1" />
                </s:NumericAxis.GrowBy>
            </s:NumericAxis>
        </s:SciChartSurface.XAxis>

However, what I would like is for it to begin zoomed out by a certain amount already - e.g. the X axis would already be displaying from (for example) 0 - 10 and as the line is drawn it proceeds across the screen, only zooming if the line happens to get bigger than the space provided.
I've tried setting the VisibleRangeLimit, but while this does allow me to define the range of the chart area, the zoom doesn't kick in when the curve gets too big (so it literally goes "off the chart")
How can this be accomplished?

A: The reason for this is the Fifo Example in sciChart WPF uses XAxis AutoRange set to Always to scale the axis to fit the data. When the example starts, even if the Fifo buffer has a capacity of 10,000 points, it has no data in it, hence the axis is scaled small to accommodate the data.
There are two ways around this:

*

*Is to pre-fill your FIFO DataSeries with X=xValue, Y=double.NaN. Given enough values the chart will think it has to draw all these points so the XAxis will scale accordingly

*Is to take control of XAxis.VisibleRange yourself (do not use AutoRange). In this case, you need to set XAxis.VisibleRange to a window size to accommodate N points, and as you update data, update the window.
The FAQ 'How to create a StripChart in SciChart' demonstrates technique (2), how to update the visible-range of the XAxis to achieve scrolling behaviour.
Disclosure, I am the tech lead of the SciChart WPF Team


text:
Q: ERR_INCOMPLETE_CHUNKED_ENCODING : Gulp not working with React app All of a sudden, I am getting this error in my console. I don't get any error while I perform gulp on my project and I successfully get my Bundle.js as my output file.I googled it but didn't find anything useful

A: I was getting this error because of adBlocker extension in firefox .I disabled it and then error din't come. Whereas in chrome I had to uninstall all of my extensions to get rid of this error .


text:
Q: Floyd Warshall with maximum capacity constraint I need to find the best (shortest path) flow distribution for a net, where each node has export and import that I want to dispatch.
I believe the Floyd-Warshall algorithm is the best fit for this problem. But the problem is that each connection has a maximum capacity, meaning that the flow from u to v cannot exceed a certain number. How can I implement this restriction?
Also, how could I implement in the algorithm that if for a certain connection, there are two paths with the same minimum distance, then the dispatch is half in each way?


text:
Q: confused between work on /work for/work against/work to
whatever the tactic we had, just didn't work for them.

context: yesterday Barcelona lost to Liverpool 0-4.
I'm speaking as a Barcelona fan.
I'm not sure what preposition should be followed after "work".
what I want to mean is that our tactic didn't seem effective against Liverpool

A: Each of the prepositions (that follows work) constructs a different phrasal verb with a particular meaning.
Taking them in the order you give them:
..to work on... means to be labouring on, occupied with, busy with etc. It is also used in expressions such as to work on site or ....to work on time.
..to work for... can mean either to be employed by (somebody/a company)... or to work in the favour of/to assist. In this sense, none of the tactics that Barcelona tried assisted them/worked in their favour/helped them to succeed.
..to work against ... has the opposite meaning of opposing/hindering a person or enterprise.
..to work to... is used in certain expressions such as to work to rule, meaning to stick to every little rule and not to be flexible. It is also widely used as an infinitive, as in went to work to finish the job.


text:
Q: No shape error in tensorflow graph construction but getting shape mismatch error during graph computation There occurs no error in tensorflow graph construction, but I get a shape mismatch error during graph computation in tf.gradients (I guess that the error is in back propagation).
This is the error I get:

InvalidArgumentError (see above for traceback):
  Input to reshape is a tensor with 16777216 values, but the requested shape has 4096
  [[Node: gradients/truediv_grad/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0
      /device:GPU:0"](gradients/truediv_grad/Sum, gradients/truediv_grad/Shape)]]

A: I solved the issue , using two techniques:
1.Apparently if you are creating custom ops and gradients , you need to be very explicit in providing the shape information to tensorflow using set_shape or tf.reshape
2.Also when you are registering your gradient using tf.register_gradient which takes op and grad as inputs, you need to be careful while chaining the gradients i.e dy/dx = dy/dz*dz/dx.
Say dy/dz is the custom gradient we have created and dz/dxis the gradient of the previous ops as per the chain rule of differentiation.
tf.register_gradient(Mygrad)
def Mygrad(op,grad):
*****do stuff with op.inputs and calculate custom grads say cust_grad or dy/dz****
return cust_grad*grad

I changed this to following:
tf.register_gradient(Mygrad)
def Mygrad(op,grad):
*****do stuff with op.inputs and calculate custom grads say cust_grad or dy/dz****
return tf.matmul(tf.reshape(cust_grad,[calculated_shape]),tf.reshape(grad,expeced_shape))


text:
Q: Sorting a list of strings by the number within each string I'm trying to sort the list provided below, yes it's full of strange values, but it's the data I have to work with.
The expected result is:
["3 $", "4 $", "4a $", "5-5b $$", "6 $", "10 $", "10 b $", "11 $"]

But instead I get:
["10 $", "10 b $", "11 $", "3 $", "4 $", "4a $", "5-5b $$", "6 $"]

This happens because "10" < "3" is true.
But I'm at a loss as to how I would go about comparing these values without converting them to numbers, in which case another issue will arise, namely the sorting of values such as  "4 $", "4a $",  "4b $", "4c $".
let list = ["5-5b $$", "4 $", "10 $", "10 b $", "4a $", "6 $", "3 $", "11 $"];

Here is my code so far:
console.log(list.sort(function(a, b) {
 let x = a.replace(/\-/, ".").replace(/\$+/, "").replace(/\s/g, "");
 let y = b.replace(/\-/, ".").replace(/\$+/, "").replace(/\s/g, "");

 console.log(`Comparing ${x} to ${y}`)

 return x.localeCompare(y);
}))

All input is appreciated.


text:
Q: Returning the updated value of variable initialized in a method I have three methods. Let's call them Method 1, Method 2 and Method 3.
Each of these methods contain a String variable which is initailized within the method.
Note: These methods are called when a user clicks a Button, so in other words there's a click listener.
Now what I want to do, in the main method is creating a 4th String variable, which is initialized as such:
public class Main{

 String Variable4 = variable1 + variable2 + variable3
    System.out.println(Variable4);
}

The problem however is, that variable4 is null.
And this is because the variables in the 3 methods are null in the main method.
But they are initialized locally in the methods.
So how would I return the initialized variable in the main method?

A: If you have a variable depending on other variables, use a method instead of a variable.
public class Main{
    String[] variables = new String[3];

    public String getVariable4() {
        String s = "":
        for (int i = 0: i < variables.length - 1; i++) {
            s += variables[i] +"  ";
        )
        s += variables[variables.length - 1]:
        return s;
    }

    public void onClick(View v) {
        variables[0] ="blah";  // update the array
        label.setText(getVariable4()); // get the dynamic variable
    }
}

A: Yours functions have to return a value. And you need to call directly the function
public class Main{

 String Variable4 = "";
 Variable4 = Methode1() + Methode2() + Methode3();
    System.out.println(Variable4);
}

And for example your Methode1 :
public String Methode1(){
    String variable = "initialyze";
    return variable;
}

Hope that will help you :)


text:
Q: Question 23 Chapter 14 Spivak's Calculus: What is the author's intended method to find what condition $y$ must satisfy if $y'(x)=\frac{1+x^2}{1+y(x)}$ Question 23 from Chapter 14 of Spivak's Calculus is a multipart exercise. Here are two of the parts:

Suppose $G'=g$ and $F'=f$. Prove that if the function $y$ satisfies the differential equation $g(y(x))y'(x)=f(x)$ for all $x$ in some interval, then there is a number $c$ such that $G(y(x))=F(x)+c \quad \dagger_1$.

Find what condition $y$ must satisfy if $y'(x)=\frac{1+x^2}{1+y(x)} \quad \dagger_2$

Chapter 14 is the first introduction into the relationship between derivatives and integrals. The two relevant theorems introduced in this chapter are referred to as the First and Second Fundamental Theorems of Calculus, which read as

*

*If $f$ is continuous at $c$ in $[a,b]$, then the function $F(x)=\int_a^x f$ is differentiable at $c$ and $F'(c)=f(c)$.

*If $f$ is integrable on $[a,b]$ and $f=g'$ for some function $g$, then $\int_a^b f = g(b)-g(a)$
I mention these theorems because I am concerned that I am solving the problems $\dagger_1$  and $\dagger_2$ in a manner that is not intended...and am therefore 'missing the point' of the exercise.

Here is how I solved $\dagger_1$:
If $G'=g$, then $(G\circ y)'=(G'\circ y)\cdot y'=(g\circ y)\cdot y'$. Therefore, if $\forall x \in I: (G\circ y)'(x)=g(y(x))y'(x)=f(x)=F'(x)$, by the Mean Value Theorem: $ \forall
 x \in I: (G\circ y)(x)=F(x)+c$

Here is how I solved $\dagger_2$:
If $y'(x)=\frac{1+x^2}{1+y(x)}$, then $(1+y(x))\cdot y'(x)=1+x^2$. Letting $g(t)=1+t$ and $f(t)=1+t^2$, we can rewrite this as: $g(y(t))\cdot y' (t)=f(t)$.
Now, if $g(t)=1+t$, then for any $a \in \mathbb R: G(x)=\int_a^x g(t)dt=(x-a)+\frac{x^2}{2}-\left(\frac{a^2}{2}\right)=x+\frac{x^2}{2}-a-\frac{a^2}{2}=x+\frac{x^2}{2}+c_1$. This implies that $G(y(x))=y(x)+\frac{y(x)^2}{2}+c_1$.
Similarly, if $f(t)=1+t^2$, then for any $a \in \mathbb R: F(x)=\int_a^x f(t)dt=(x-a)+\left(\frac{x^3}{3}-\frac{a^3}{3}\right)= \cdots =x+\frac{x^3}{3}+c_2$
We can apply the result of $\dagger_1$ to show that $G(y(x))=F(x)+c_3 \iff y(x)+\frac{y(x)^2}{2}+c_1=x+\frac{x^3}{3}+c_2+c_3$.
We then let $c=c_2+c_3-c_1$, which gives us that $y(x)+\frac{y(x)^2}{2}=x+\frac{x^3}{3}+c
$
You can then complete the square solving for $y(x)$.
Is the approach that I laid out the appropriate path? Or am I missing something here?
I was playing around with the possibility that $\int_a^{y(x)}g(t)dt=\int_a^xg(t)y'(t)dt$, but this doesnt seem appropriate as I do not even know whether or not $y'$ is integrable.


text:
Q: flatMap creates multiples lines in DataFrame Based on previous SO answers:

*

*Is there a way to skip/throw-out/ignore records in Spark during a map?

*Spark - How to handle error case in RDD.map() method correctly?
It seems that doing "map and filter out error cases" should be possible in a single operatoin using flatMap.
Given sample data:
spark.read.text("/mnt/seedx-ops-prod/genee-local-datasync/genee-3/genee/logs/genee_python-20190417T075453.005.log").show(4, False)

+---------------------------------------------------------------------------------------------+
|value                                                                                |
+---------------------------------------------------------------------------------------------+
|2019-04-17 07:54:51.505: 2019-04-17 10:54:51 INFO [main.py:64] Read machine_conf.ini         |
|2019-04-17 07:54:52.271: 2019-04-17 10:54:52 INFO [app.py:93] Running web server on port 9090|
|2019-04-17 08:05:10.720: 2019-04-17 11:05:10 INFO [app.py:166] Exiting event loop...         |
|2019-04-17 08:05:10.720: <_WindowsSelectorEventLoop running=False closed=False debug=False>  |
+---------------------------------------------------------------------------------------------+

I expect successful parsing for the first 3 lines, followed by a parse error that would not produce results for the 4th line.
def parseTheNonSuckingDaemonPythonLogs(row):
  try:
    parts = re.findall(r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{1,3}): (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) ([A-Za-z]{1,5}) (.*)', row.value)[0]
    return Row(os_ts=parts[0], log_ts=parts[1], log_level=parts[2], message=parts[3])
  except:
    return Row()

The expected result is
+-----------------------+-------------------+---------+-------------------------------------------+
|os_ts                  |log_ts             |log_level|message                                    |
+-----------------------+-------------------+---------+-------------------------------------------+
|2019-04-17 07:54:51.505|2019-04-17 10:54:51|INFO     |[main.py:64] Read machine_conf.ini         |
|2019-04-17 07:54:52.271|2019-04-17 10:54:52|INFO     |[app.py:93] Running web server on port 9090|
|2019-04-17 08:05:10.720|2019-04-17 11:05:10|INFO     |[app.py:166] Exiting event loop...         |
+-----------------------+-------------------+---------+-------------------------------------------+

The actual results looks as following:
genee3_python_logs_text = spark.read.text("/mnt/seedx-ops-prod/genee-local-datasync/genee-3/genee/logs/genee_python-20190417T075453.005.log")

clean_genee3_python_logs = genee3_python_logs_text.rdd.flatMap(parseTheNonSuckingDaemonPythonLogs)

from pyspark.sql import Row

row = Row("val")
genee3_python_logs_df = clean_genee3_python_logs.map(row).toDF()
genee3_python_logs_df.select('*').show(truncate=False)

+-------------------------------------------+
|val                                        |
+-------------------------------------------+
|INFO                                       |
|2019-04-17 10:54:51                        |
|[main.py:64] Read machine_conf.ini         |
|2019-04-17 07:54:51.505                    |
|INFO                                       |
|2019-04-17 10:54:52                        |
|[app.py:93] Running web server on port 9090|
|2019-04-17 07:54:52.271                    |
|INFO                                       |
|2019-04-17 11:05:10                        |
|[app.py:166] Exiting event loop...         |
|2019-04-17 08:05:10.720                    |
+-------------------------------------------+

A: I think I've managed to get it working, I'm still not sure about the functional transformations that help it be the case.
Wrap the Row in another Row inside the parsing logic:
def parseTheNonSuckingDaemonPythonLogs(row):
  try:
    parts = re.findall(r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{1,3}): (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) ([A-Za-z]{1,5}) (.*)', row.value)[0]
    return Row(Row(os_ts=parts[0], log_ts=parts[1], log_level=parts[2], message=parts[3]))
  except:
    return Row()

Drop the Row adaptation inside the DataFrame declaration:
genee3_python_logs_df = clean_genee3_python_logs.toDF()

Result:
genee3_python_logs_df.show(truncate=False)

+---------+-------------------+-------------------------------------------+-----------------------+
|log_level|log_ts             |message                                    |os_ts                  |
+---------+-------------------+-------------------------------------------+-----------------------+
|INFO     |2019-04-17 10:54:51|[main.py:64] Read machine_conf.ini         |2019-04-17 07:54:51.505|
|INFO     |2019-04-17 10:54:52|[app.py:93] Running web server on port 9090|2019-04-17 07:54:52.271|
|INFO     |2019-04-17 11:05:10|[app.py:166] Exiting event loop...         |2019-04-17 08:05:10.720|
+---------+-------------------+-------------------------------------------+-----------------------+


text:
Q: python drop lines conditional in goupby in a rolling period I want to drop lines when each id shows more than 10 records (drop just lines >10) in his rolling 12h period
dataframe example:
                id          start_time
9847171   144439.0 2022-04-11 08:06:44
15012964  212035.0 2022-04-11 08:06:44
8636104   128662.0 2022-04-11 08:06:44
14825759  199657.0 2022-04-11 08:06:44
16694869   10705.0 2022-04-11 08:07:01
           ...                 ...
6632763   115796.0 2022-04-12 06:45:01
12752832  177783.0 2022-04-12 06:45:01
16061068  328305.0 2022-04-12 06:45:01
10327943  152200.0 2022-04-12 06:45:01
16569557  389311.0 2022-04-12 06:45:01

first of all i wanted to find how many times id is in a rolling period of 12h, but probabily i'm doing it wrong:
example.groupby('id').rolling('12h', on="start_time").count()

i think i'm not too far away but i need your help, please
Thanks


text:
Q: SharePoint 2013 Site collection restore to another SharePoint 2013 error? I have backup of site collection from on SharePoint 2013 which is down.
I want to restore it to the new SharePoint 2013 site collection.
Below is my command:
Restore-SPSite -Identity <http://af-spt1-srv/sites/test> -Path <\\AF-SP-SRV\SharePoint\hrc.bak> [-DatabaseServer <af-dbt1-srv>] [-DatabaseName <WSS_Content_test>] [-HostHeader <Host header>] [-Force] [-GradualDelete] [-Verbose]

Wwhen I run the command it gives error see image:

A: The correct sintax is:
Restore-SPSite -Identity http://af-spt1-srv/sites/test -Path \\AF-SP-SRV\SharePoint\hrc.bak -DatabaseServer af-dbt1-srv -DatabaseName WSS_Content_test -HostHeader Host header -Force -GradualDelete -Verbose

You do not have to use < and > and neither [ and ]
Restore-SPSite

A: Simply, you have just copied all the arguments for the cmdlt Restore-SpSite. You only need to use some of the arguments to be able to restore a backup.
This should work for you.
Restore-SPSite -Identity "http://af-spt1-srv/sites/test" -Path "\\AF-SP-SRV\SharePoint\hrc.bak" -DatabaseServer af-dbt1-srv -DatabaseName WSS_Content_test

Just make sure that the account that are gonna restore the backup has permission to the location where the backup is.
And it's always good to run powershell/management shell as an administrator.


text:
Q: why does dagger 2 generated components gets deleted on project rebuild? The problem exists when the code that uses the generated 'Dagger' prefixed on a component is not commented out. If it was commented out, the generated Dagger 2 files are generated.
BookModule
@Module
public class BookModule {

    @Provides
    public Book providesBook(){
        return new Book();
    }

}

BookComponent
@Component(modules = BookModule.class)
public interface BookComponent {

    void inject(MainActivity activity);

    public Book getBook();

}

MainApplication
public class MainApplication extends Application {

    public static BookComponent mBookComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        mBookComponent = DaggerBookComponent.builder().bookModule(new BookModule()).build();
    }
}

Build.gradle(Application)
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Build.gradle(Project)
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.example.bryan.myapplication"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        jackOptions{
            enabled = true
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:support-v4:24.2.0'
    compile group: 'com.google.dagger', name: 'dagger', version: '2.10-rc1'
    apt group: 'com.google.dagger', name: 'dagger-compiler', version: '2.10-rc1'
    compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3'

}

Error Stacktrace
ERROR: C:\bin\AndroidProjects\MyApplication\app\src\main\java\com\example\lloyd\myapplication\MainApplication.java:12.26: DaggerBookComponent cannot be resolved

com.android.jack.api.v01.CompilationException: Failed to compile
    at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:144)
    at com.android.builder.core.AndroidBuilder.convertByteCodeUsingJackApis(AndroidBuilder.java:1931)
    at com.android.build.gradle.tasks.JackTask.doMinification(JackTask.java:148)
    at com.android.build.gradle.tasks.JackTask.access$000(JackTask.java:73)
    at com.android.build.gradle.tasks.JackTask$1.run(JackTask.java:112)
    at com.android.builder.tasks.Job.runTask(Job.java:51)
    at com.android.build.gradle.tasks.SimpleWorkQueue$EmptyThreadContext.runTask(SimpleWorkQueue.java:41)
    at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:223)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.android.jack.frontend.FrontendCompilationException: Failed to compile
    at com.android.jack.Jack.buildSession(Jack.java:1053)
    at com.android.jack.Jack.run(Jack.java:540)
    at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:124)
    ... 8 more

mBookComponent = DaggerBookComponent.builder().bookModule(new BookModule()).build();

The code from above is in the MainApplication and it is the problem, if I commented it out, it rebuilds completely fine. But when I left it as it is, it got an error saying the 'DaggerBookComponent' cannot be resolved, by this time the generated DaggerBookComponent is deleted which results in cannot be resolved

A: When you do a rebuild, the build system looks at the Dagger module and component classes and generates the actual classes that make all of dagger work.  When you do a normal incremental build, it doesn't (it assumes the old versions are still good).  This means when you rebuild if there's some error in your program or in your dagger components/modules it will not be able to rebuild these files.
So basically, you have a bug somewhere, likely (although not necessarily) in your dagger setup.  When you fix it, you'll stop having problems.


text:
Q: "Inverse rc" impulse response circuit I am a digital design engineer and am struggling to come up with an analog circuit that could produce an (RC) curve like below. It does not have to be an exact RC curve. Something that comes close would do perfectly fine.

Thanks,
Robert

A: This is a dangerous kind of want, as there has to be some sort of cutoff, you can't increase without bound (at least for long).
As far as replicating that behaviour, a real pole on the right side of the s-plane will have an step response of that nature. As for getting a pole there, it shouldn't be too hard, I don't think I've ever had a circuit naturally stable before compensating :P

MATLAB Code:
L = tf(1, [1 -10]) % real pole on right half plane
pzmap(L)
%%
step(L)
xlim([0 .5])

As for another method (I'd recommend this one I think), the voltage to current relationship of a diode is exponential, meaning if you increase the forward voltage applied, the current increases proportional to a*e^(V/b), where a and b are relatively constant (both a and b will vary with temperature, something a high current can cause to rise, so be careful with power dissipation!). Look up diode current equation for the full picture.

Convert this current to voltage (transimpedance amp) and you will have an exponentially growing voltage in response to a linear increase in input.

If you want to cut out some of that long initial tail, just start sweeping the diode voltage at around 200mV.


text:
Q: ggplot2: overlay control group line on graph panel set I have a stacked areaplot made with ggplot2:
dists.med.areaplot<-qplot(starttime,value,fill=dists,facets=~groupname,
    geom='area',data=MDist.median, stat='identity') +
    labs(y='median distances', x='time(s)', fill='Distance Types')+
    opts(title=subt) +
    scale_fill_brewer(type='seq') +
    facet_wrap(~groupname, ncol=2) + grect #grect adds the grey/white vertical bars

It looks like this:

I want to add a an overlay of the profile of the control graph (bottom right) to all the graphs in the output (groupname==rowH is the control).
So far my best efforts have yielded this:
cline<-geom_line(aes(x=starttime,y=value),
  data=subset(dists.med,groupname=='rowH'),colour='red')

dists.med.areaplot + cline

I need the 3 red lines to be 1 red line that skims the top of the dark blue section. And I need that identical line (the rowH line) to overlay each of the panels.
The dataframe looks like this:
> str(MDist.median)
'data.frame':   2880 obs. of  6 variables:
 $ groupname: Factor w/ 8 levels "rowA","rowB",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ fCycle   : Factor w/ 6 levels "predark","Cycle 1",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ fPhase   : Factor w/ 2 levels "Light","Dark": 2 2 2 2 2 2 2 2 2 2 ...
 $ starttime: num  0.3 60 120 180 240 300 360 420 480 540 ...
 $ dists    : Factor w/ 3 levels "inadist","smldist",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value    : num  110 117 115 113 114 ...

The red line should be calculated as the sum of the value at each starttime, where groupname='rowH'. I have tried creating cline the following ways. Each results in an error or incorrect output:
#sums the entire y for all points and makes horizontal line
cline<-geom_line(aes(x=starttime,y=sum(value)),data=subset(dists.med,groupname=='rowH'),colour='red')

 #using related dataset with pre-summed y's
> cline<-geom_line(aes(x=starttime,y=tot_dist),data=subset(t.med,groupname=='rowH'))
> dists.med.areaplot + cline
Error in eval(expr, envir, enclos) : object 'dists' not found

Thoughts?
ETA:
It appears that the issue I was having with 'dists' not found has to do with the fact that the initial plot, dists.med.areaplot was created via qplot. To avoid this issue, I can't build on a qplot. This is the code for the working plot:
cline.data <- subset(
        ddply(MDist.median, .(starttime, groupname), summarize, value = sum(value)),
        groupname == "rowH")
cline<-geom_line(data=transform(cline.data,groupname=NULL), colour='red')

dists.med.areaplot<-ggplot(MDist.median, aes(starttime, value)) +
  grect + nogrid +
  geom_area(aes(fill=dists),stat='identity') +
  facet_grid(~groupname)+ scale_fill_brewer(type='seq') +
  facet_wrap(~groupname, ncol=2) +
  cline

resulting in this graphset:

A: This Learning R blog post should be of some help:
http://learnr.wordpress.com/2009/12/03/ggplot2-overplotting-in-a-faceted-scatterplot/
It might be worth computing the summary outside of ggplot with plyr.
cline.data <- ddply(MDist.median, .(starttime, groupname), summarize, value = sum(value))
cline.data.subset <- subset(cline.data, groupname == "rowH")

Then add it to the plot with
last_plot() + geom_line(data = transform(cline.data.subset, groupname = NULL), color = "red")


text: Q: Visual Studio Code HTML Preview issue I'm having an issue with VS Code, when I try to use JAVA Script in an HTML file. When I use the HTML preview it keeps saying that some content is disabled. But when I go to update the settings to allow the content, it never enables it. I've looked around the internet and couldn't find anything that would help me troubleshoot this issue. I'm just learning how to code, so I don't know that my code is good, but any help with the settings would be greatly appreciated. Thanks.


text:
Q: How to make airbnb react date to selecet only a set of dates? I am using airbnb react dates as a react calendar component. What I want to do is pass an array of dates. And I want to customize the calendar so only those can be selectable by the user. I don't find much in the document. If anyone has ever done this before please let me know.
https://github.com/airbnb/react-dates

A: Might be late in the game, but check out isDayBlocked property. It accepts a function that takes a day and returns boolean. e.g.

isDayBlocked(day) { return blockedDays.includes(day); }

Another useful prop is isOutsideRange. Has slightly different semantic, but could be useful based on what your requirements are.
More here in "Date selection rules" section: https://github.com/airbnb/react-dates


text:
Q: How do we share folder on windows host to windows based docker container? My requirement is to mount an nfs drive to windows based docker container.
I tried below command:
docker run -v "$HOME\foo:C:\Users\ContainerAdministrator\foo" --mount type=volume,dst=M:\,volume-opt=type=nfs,volume-opt=device=:FileSystem-D,volume-opt=o=addr=192.168.0.10 -p 80:80 -p 81:81 -p 443:443 -p 8080:8080 -p 8081:8081 -p 4848:4848 -it --entrypoint="docker-entrypoint.bat" docker/win2019 cmd

producing following error:
"docker: Error response from daemon: create 47becc3936dec62c463726b91fa4206324326fa36d148aabaec1aceca2a8dd6e: options are not supported on this platform."

A: The simplest way is to,

*

*Mount the NFS to the host.

*Use Docker to mount the file path of the NFS share, that is mounted onto your host machine, so you are using the host pc to connect to the network share and not directly from the container.


text:
Q: Is it possible to send to n clients data at the same time using Tcp Sockets? I am trying to set up a Socket server. I have managed to communicate with a client. What i am trying to do is to send the same responses more clients, lets say 2. Is this possible? Can anyone provide a hint?

A: The technology you're describing is multicast, but you probably should not be using it. Instead, create seperate threads on the server for each client, so that they communicate with each other at the same time.


text:
Q: How to substract (last column, last row) minus (last column, first row) from a df in python I have a dataframe with index being datetime and the columns with intigers. I am trying to do the following (last column last row minus last column first row). I am having difficulty getting the correct output. Please help.
df8['new_port'] = df8.mean(axis=1)
print(df8)

print(df8['new_port'].iloc[-1:])
print(df8['new_port'].iloc[:1])
print(df8['new_port'].iloc[:1] - df8['new_port'].iloc[-1:])

Output is the following

A: The problem is that you're choosing a set of elements when you do df8['new_port'].iloc[-1:].
You have to remove the colon to just choose the last element.
df8['new_port'].iloc[-1] # last row element from your last column
df8['new_port'].iloc[0] # first row element from your last column

df8.iloc[-1,-1] # last row last column
df8.iloc[0,-1] # first row last column

df8.iat[-1,-1]  # last row last column
df8.iat[0,-1] # first row last column

Or much easier as Sayandip Dutta said it
df8['new_port'].iat[1] - df8['new_port'].iat[-1]


text:
Q: Scrolling in viewport bootstrap tour I have an issue with bootstrap tour.
I have a very long page, and the tour needs to work on mobile devices as well. Unfortunately the bootstrap tour function scrollIntoView() doesn't seam to work at all, as if i'm at the top of the page, it doesn't scroll down till the element i want to highlight.
Here's _scrollIntoView bootstrap tour code:
Tour.prototype._scrollIntoView = function(element, callback) {
      var $element, $window, counter, offsetTop, scrollTop, windowHeight;
      $element = $(element);
      if (!$element.length) {
        return callback();
      }
      $window = $(window);
      offsetTop = $element.offset().top;
      windowHeight = $window.height();
      scrollTop = Math.max(0, offsetTop - (windowHeight / 2));
      this._debug("Scroll into view. ScrollTop: " + scrollTop + ". Element offset: " + offsetTop + ". Window height: " + windowHeight + ".");
      counter = 0;
      return $('body, html').stop(true, true).animate({
        scrollTop: Math.ceil(scrollTop)
      }, (function(_this) {
        return function() {
          if (++counter === 2) {
            callback();
            return _this._debug("Scroll into view.\nAnimation end element offset: " + ($element.offset().top) + ".\nWindow height: " + ($window.height()) + ".");
          }
        };
      })(this));
    };

I've been searching everywhere for this issue, and already tried some of the suggestion founded on the bootstrap tour support page, but nothing.
The default scrollTop value is the following:
scrollTop = Math.max(0, offsetTop - (windowHeight / 2));

and basically it calculates the element offset and it scrolls it to the middle of the window.
Now, i think that the problem i have is that if the offset is very long (let's say 1100px on a small mobile device with window.height() 480px) the result of the above will be 1100 - (480/2) = 860px, still below the viewport.
Do you have any suggestions at all on what formula should I use to scroll the element to inside the viewport reliable in any case and on any device?
Here's what i tried so far:
var offsetTop = $element.offset().top;
$('body, html').animate({
 scrollTop: scrolltop},300);

and i tried these different scrolltop formulas:
var scrollTop = (windowHeight / 2) + (offsetTop - windowHeight) + $element.height()
var scrolltop = (windowHeight / 2) + (offsetTop - windowHeight)
var scrollTop = (windowHeight / 2) + (offsetTop - windowHeight) - $element.height()
var scrollTop = $element.height()

But no luck till now.
Thanks in advance for any help or suggestions


text:
Q: snmp v3 traps not working when configuring same user with different authentication type I am using Linux based snmp (net-snmp) in my Linux device. To receive snmp trap on Linux host machine, I have configured snmptrapd in /etc/snmp/snmptrapd.conf file as below (After stopping snmpd daemon)
createUser user MD5 "password123" DES "encrypt123"

authuser log user authPriv

Above configuration allow me to receive snmp trap on Linux host machine when I execute below command from my Linux device
snmptrap -Ci -v3 -u user -a MD5 -A password123 -x DES -X encrypt123 -l authPriv 10.103.0.110 '' Test-MIB::statusChangeNotification Test-MIB::statusChangeAlarm s 'status change'

Now if I execute above snmptrap command with same user and SHA/DES configuration (as below) then in that case snmptrap command is failing with "snmpinform: Authentication failure (incorrect password, community or key)" error message. (snmptrapd is stopped and started after SHA/DES configuration as above.)
snmptrap -Ci -v3 -u user -a SHA -A password123 -x DES -X encrypt123 -l authPriv 10.103.0.110 '' Test-MIB::statusChangeNotification Test-MIB::statusChangeAlarm s 'status change'

Can anybody suggest possible reason behind this error?
Does snmptap command maintain usmUser table which not allow same user entry with different authentication type?
Is there any way to reset usmUser table?
Is there any additional configuration required?

A: Have you tried removing the quotation marks from both your username and password in the snmptrapd.conf?

A: It should not work. This is absolutely expected behavior. The user configuration should match on both sides (trap sender and trap receiver).
The SHA1 and MD5 are totally different auth protocols. They do produce different hash codes for the same input data.


text:
Q: D3 Clicking a symbol attached to a line I have a D3 tree (very similar to this: https://observablehq.com/@mx60s/collapsible-tree) and when I click on a line, it adds a symbol as a child. I'd like to be able to click on the symbol and have it open up a menu, but for some reason I can't get it to respond to a click. I've tried making it sit behind the line so you'd just click on the line again in the same area, but I can't get that to work with z-index or anything.
Here's the relevant code:
linkEnter.on('click', d => {

    // Get location of the mouse click
    var x = d3.mouse(d3.event.currentTarget)[0]
    var y = d.target.x

    fault = link
      .enter()
      .append('path')
      .attr('stroke-width', 1)
      .attr('fill', '#555')
      .attr('d', d3.symbol().type(d3.symbolCross).size(50))
      .on('click', console.log("Hello!"))
})

The .on('click') event doesn't respond - help!


text:
Q: Are regular expression adequate for analyzing large text? I have a text of about ~1000000 words (just an example) and I want to parse it in just one iteration. And what I want to do is every time an expression is matched, change it for something else. For example:
The expressions:
| Expression     | New text |
|----------------|----------|
| ab             | A        |
| #{1,3}cb       | B        |
| [1234567890]db | C        |

And the text:

Lorem ipsum dolor sit amet, ##cbconsectetur adipiscing elit. Vestibulum posuere ligula in diam volutpat #cb, vitae laoreet ligula ultrices. In quis aliquam urna, in ab suscipit purus. Nunc posuere efficitur 9db nibh, tempor convallis mauris porta lobortis.

Will output the text:

Lorem ipsum dolor sit amet, Bconsectetur adipiscing elit. Vestibulum posuere ligula in diam volutpat B, vitae laoreet ligula ultrices. In quis aliquam urna, in A suscipit purus. Nunc posuere efficitur C nibh, tempor convallis mauris porta lobortis.

Assuming those "regular" expressions wont overlap with each other, is there a way to implement this in c++ using std::regex ?
I have tried to do so, but there are two main problems:

*

*It will only match the very first and the very last expression.

*It will only will iterate over the text once for each expression.

Is there any way to solve this or the best solution is to program a parser for this specific purpose

A: As EJP says, this is trivial using (f)lex, even if you don't know anything about parser generators. (You should take a glance at flex's slightly idiosyncratic regular expression syntax, though. As with every regex-oriented tool, it has its own quirks.)
Here's a complete flex program for your task:
file replacer.l
%option noinput nounput noyywrap
%%
ab         { fputs("A", stdout); }
"#"{1,3}cb { fputs("B", stdout); }
[0-9]db    { fputs("C", stdout); }

The last line could have been [1234567890], but [0-9] and [[:digit:]] are more idiomatic. As illustrated in the second-last line, it's normal to quote special characters by putting them inside quotation marks, something which few regex tools allow. Note that "abc"* is "any number of repetitions of abc", which is quite different from abc*.
The biggest limitation is that there are no captures, although that doesn't seem relevant to your question, and there are almost always simple workarounds.
To compile and run that:
$ flex -o replacer.c replacer.l
$ gcc -o -Wall replacer replacer.c -lfl

$ ./replacer < lorem
Lorem ipsum dolor sit amet, Bconsectetur adipiscing elit. Vestibulum
posuere ligula in diam volutpat B, vitae laoreet ligula ultrices. In
quis aliquam urna, in A suscipit purus. Nunc posuere efficitur C nibh,
tempor convallis mauris porta lobortis.

I've been known to build quick-and-dirty tools which generate, compile and run flex programs, because the result can be a lot faster than cobbling things together from standard utilities when the input files are large. See, for example, this answer on a companion site, which adds an actual main to the tiny flex program, in order to avoid relying on -lfl.

A: I'm not aware how to do this with std::regex but you could try boost::iostreams::regex_filter. The example from their site only uses one filter but I'm sure you could tack on more. The example:
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/regex.hpp>
#include <boost/regex.hpp>
#include <iostream>

using namespace boost::iostreams;

int main()
{
  char buffer[16];
  array_sink sink{buffer};
  filtering_ostream os;
  os.push(regex_filter{boost::regex{"Bo+st"}, "C++"});
  // push more filters here
  os.push(sink);
  os << "Boost" << std::flush;
  os.pop();
  std::cout.write(buffer, 3);
}

The caveat is that according to the docs it will read all of your text into memory at once. Your 1 million words shouldn't be a problem but for gigabyte sized files you could run into issues.
If it were me I would just do the replacement by hand since it's probably not that complex.

A: Here is what you can do.
Let r1, r2, ..., rn be your regular expressions, and r be their alternation (r1)|(r2)|...|(rn).

*

*Find the first occurence of r.

*Compare the occurence separately with r1, r2, ..., rn. When found a match, write to the destination text everything before the first occurence, and the replacement.

*Repeat with the rest of the text.


text:
Q: Can't draw in wpf using graphsharp unless I call the method before the InitializeComponent method I followed the video tutorial on http://graphsharp.com on how to use graph# library with WPF, and it was quite easy to locate some vertices and the edges joining them. The code of this graph was written in a method which was called in the MainWindow method before the InitializeComponent method, and thus when compiling, the graph appears automatically.
The problem is that I tried to call the same method of drawing in the button_click method, but nothing appears each time I click the button.
Here's my code
public partial class MainWindow : Window
{
    private IBidirectionalGraph<object, IEdge<object>> _graphToVisualize;

    public IBidirectionalGraph<object, IEdge<object>> GraphToVisualize
    {
        get { return _graphToVisualize; }
    }

    public MainWindow()
    {
        //CreateGraphToVisualize();     //When compiling with this instruction uncommented, the graph is drawn
        InitializeComponent();
    }

    private void CreateGraphToVisualize()
    {
        var g = new BidirectionalGraph<object, IEdge<object>>();

        // add the vertices to the graph
        string[] vertices = new string[5];
        for (int i = 0; i < 5; i++)
        {
            vertices[i] = i.ToString();
            g.AddVertex(vertices[i]);
        }

        // add edges to the graph
        g.AddEdge(new Edge<object>(vertices[0], vertices[1]));
        g.AddEdge(new Edge<object>(vertices[1], vertices[2]));
        g.AddEdge(new Edge<object>(vertices[2], vertices[3]));
        g.AddEdge(new Edge<object>(vertices[3], vertices[1]));
        g.AddEdge(new Edge<object>(vertices[1], vertices[4]));

        _graphToVisualize = g;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        CreateGraphToVisualize();
    }
}

}

A: your problem is, that the window use a binding to the graphvisualize
<Window x:Class="MainWindow "
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:graphsharp="clr-namespace:GraphSharp.Controls;assembly=GraphSharp.Controls"
        xmlns:zoom="clr-namespace:WPFExtensions.Controls;assembly=WPFExtensions"
        Title="Window1" Height="300" Width="300" x:Name="root">
  <Grid>
    <zoom:ZoomControl>
      <graphsharp:GraphLayout x:Name="graphLayout"
                              Graph="{Binding ElementName=root,Path=GraphToVisualize}"
                              LayoutAlgorithmType="FR" OverlapRemovalAlgorithmType="FSA"
                              HighlightAlgorithmType="Simple" />
    </zoom:ZoomControl>
  </Grid>
</Window>

use a dependency property or use INotifyPropertyChanged interface to solve your problem
public partial class MainWindow : Window, INotifyPropertyChanged
{
    private IBidirectionalGraph<object, IEdge<object>> _graphToVisualize;

    public IBidirectionalGraph<object, IEdge<object>> GraphToVisualize {
      get { return this._graphToVisualize; }
      set {
        if (!Equals(value, this._graphToVisualize)) {
          this._graphToVisualize = value;
          this.RaisePropChanged("GraphToVisualize");
        }
      }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropChanged(string name) {
      var eh = this.PropertyChanged;
      if (eh != null) {
        eh(this, new PropertyChangedEventArgs(name));
      }
    }

    private void CreateGraphToVisualize()
    {
        var g = new BidirectionalGraph<object, IEdge<object>>();

        // add the vertices to the graph
        string[] vertices = new string[5];
        for (int i = 0; i < 5; i++)
        {
            vertices[i] = i.ToString();
            g.AddVertex(vertices[i]);
        }

        // add edges to the graph
        g.AddEdge(new Edge<object>(vertices[0], vertices[1]));
        g.AddEdge(new Edge<object>(vertices[1], vertices[2]));
        g.AddEdge(new Edge<object>(vertices[2], vertices[3]));
        g.AddEdge(new Edge<object>(vertices[3], vertices[1]));
        g.AddEdge(new Edge<object>(vertices[1], vertices[4]));

        GraphToVisualize = g;
    }
}

hope this helps


text:
Q: Playing multiple audio files in javascript with help of html I'm trying to play a Background music and many audio files also need to played when the background music is playing.
So how can i get it done with the help of "javascript" and "html" ..
Thanks

A: Try the following to get started:
track1 = new Audio('track1.mp3');
track2 = new Audio('track2.mp3');
track3 = new Audio('track3.mp3');

track1.play();
track2.play();
track3.play();

You can start reading about the HTML Audio Spec here: http://html5doctor.com/native-audio-in-the-browser/


text:
Q: python subprocess.call() not executing in loop I have the following piece of code that generates plots with gnuplot:
import sys, glob, subprocess, os, time
for file in glob.glob('comb_*.out'):
    fNameParts = file[5:].split('.')[0].split('-')
    gPlotCmd = []
    gPlotCmd = 'unset border; set xl "rotation period #"; set yl "T [K]"\n'
    gPlotCmd += 'set key above\n'
    gPlotCmd += 'set grid xtics ytics\n'
    gPlotCmd += 'set term post eps enh color solid\n'
    gPlotCmd += 'set xrange [20:876]\n'
    gPlotCmd += 'set output "fig_TestRelax-' + fNameParts[1] + '-' + fNameParts[2] + '-' + fNameParts[3]  + '-' + fNameParts[4] + '.eps"\n'
    conf = fNameParts[1] + '-' + fNameParts[2] + '-' + fNameParts[3]
    gPlotCmd += 'plot "' + file + '" using ($1/36000):($9-$3) w l lw 5 title "OP3-OP1 ' + conf + '", "' + file + '" using ($1/36000):($6-$3) w l lw 3 title "OP2-OP1 ' + conf + '", "' + file + '" using ($1/36000):($9-$6) w l lw 1 title "OP3-OP2 ' + conf + '"'
    fw = open('temp.plt','w+')
    fw.writelines(gPlotCmd)
    subprocess.call(["gnuplot","temp.plt"])
    print(file)

In the last loop execution the subprocess.call(["gnuplot","temp.plt"]) does not seem to be executed. At the end of the program, temp.plt exists with data from the last iteration. Also print(file) is executed during the last loop. Also if I plot the temp.plt left after the program I get the last plot (so there is no problem on the side of the data). Only the line subprocess.call(["gnuplot","temp.plt"]) is not executed. I also tried popen and monitor stdout and stderr but both were empty (as in all other iterations.
The checked the problem occurs both on linux and windows and in versions 3.3.5 and 2.7.3.
I conclude that there is something wrong with the script but I do not know what.

A: @lvc's and yours answer are correct; it is a buffering issue and fw.flush() should fix it. But you don't need the temporary file, you could pass the input commands to gnuplot directly without writing them to disk:
from subprocess import Popen, PIPE

p = Popen('gnuplot', stdin=PIPE)
p.communicate(input=gPlotCmd.encode('ascii'))

A: One likely error here is that the file temp.plt isn't actually written to disk at the time you run gnuplot. Python doesn't necessarily flush its buffers immediately after a call to writelines. This would mean that when gnuplot is launched from your script, it sees an empty file. It doesn't give an error, because an empty input isn't an error, and it has no way of knowing its expecting anything else. By the time you run it outside of your script, Python has exited and hence can't be holding anything in its own buffers anymore.
Use the with statement to ensure that fw is closed once you're done with it:
with open('temp.plt', 'w') as fw:
    fw.writelines(gPlotCmd)

subprocess.call(["gnuplot","temp.plt"])

A: It seems I figured that out. I am missing fw.close(). The last lines of code should look:
fw = open('temp.plt','w+')
fw.writelines(gPlotCmd)
fw.close()
subprocess.call(["gnuplot","temp.plt"])
print(file)

Now the code produces the intended plots.


text:
Q: Pandas dataframe not saving after sort I'm trying to sort a dataframe by a column. I'm writing a function to return the top n amount of results from the totals column.
Here is my function:
def get_most(self, column, amt):
        most = OrderedDict()
        self.data = self.data.sort_values(by=[column])
        for i in range(amt):
            most.update({i : self.data.loc[i, :]})
        return most

When I call the function like so:
most_amt = self.get_most('Total', 3)
    for key, value in most_amt.items():
        print(key, value)

It returns the first 3 rows in the dataframe before the sort. I've also tried using the inplace attribute, like so:
self.data.sort_values(by=[column], inplace=True)

But to no avail.
The app itself is a little tracker I was making for myself to track the spread of the coronavirus. I'm using data from a github repo, and the input is a 312 row csv file. The first three rows are (I added the spaces on this question to make it easier to read, there are no spaces in the actual file):
Hubei,China,2020-03-21T10:13:08,67800,3139,58946
NaN,  Italy,2020-03-21T17:43:03,53578,4825, 6072
NaN,  Spain,2020-03-21T13:13:30,25374,1375, 2125
etc. etc
NaN,  China, 2020-03-23,        81305,3259,71857
NaN,  US,    2020-03-23,        25493, 307,  171

My expected output would then be:
NaN,  China, 2020-03-23,        81305,3259,71857
NaN,  Italy,2020-03-21T17:43:03,53578,4825, 6072
NaN,  US,    2020-03-23,        25493, 307,  171

Instead, it is just the first three rows of the CSV.
Any help would be appreciated.
Thanks!

A: I think this is the right approach...  Realize the command in In[20] will return a new data frame.
In [17]: data = {'zone':['us', 'italy', 'china', 'south pole'],
    ...:         'qty': [ 10, 40, 12, 3]}

In [18]: df = pd.DataFrame(data)

In [19]: df
Out[19]:
         zone  qty
0          us   10
1       italy   40
2       china   12
3  south pole    3

In [20]: df.sort_values('qty', ascending=False)[:3]    #top 3
Out[20]:
    zone  qty
1  italy   40
2  china   12
0     us   10


text:
Q: Layout/indexing issue? On my website I have a div which animates in via a jQuery click function and it should show up over other divs which have animated in on $(document).ready(). However, it shows up behind these divs ONLY on my website's home page and NOT on any other page, only on mobile devices.
On homepage:

On any other page:

The only difference between the two types of pages is that on the home page, the navigation menu and the looseleaf div animate in like so
For the navigation menu:
setTimeout(function(){
            $('#avmenu ul li').each(function(i) {
                var $fc = $(this);
                setTimeout(function() {
                    $fc.addClass('flipInBottomBack').css({'pointer-events':'auto'});
                    }, i*250); // delay 250 ms
                });
            }, 6000);

With flipInBottomBack being a CSS keyframe animation with opacity: 0 at the beginning, transitioning to opacity: 1.
While the looseleaf div animates in via CSS keyframe animation with a delay set in the animation class itself. It has the following CSS styles:
#welcome-box {
    width: 681px;
    height: auto;
    position: absolute;
    top: 160px;
    background: url(https://dl.dropbox.com/s/ab9udqlsxbxaelw/LooseLeafExtended.png);
    background-size: cover;
    border-radius: 10px;
    box-shadow: 0 0 10px 5px #000;
    opacity: 0;
}

On any other page, they are merely shown by removing the animation class for the looseleaf div, and by executing this code for the navigation menu:
$('#avmenu ul li').show().css({'opacity':'1'});

I have played around with the CSS index attribute, but it doesn't seem to work even when the homework div has the highest index. Why is it that it the div shows as desired on every page but the homepage?

A: Please include z-index on your code.
#welcome-box {
width: 681px;
height: auto;
position: absolute;
top: 160px;
background: url(https://dl.dropbox.com/s/ab9udqlsxbxaelw/LooseLeafExtended.png);
background-size: cover;
border-radius: 10px;
box-shadow: 0 0 10px 5px #000;
opacity: 0;
z-index: 12;
}

the value of z-index may change based on the upper div.


text:
Q: Having trouble implementing recursion in Python I've read as many recursion threads as possible but I'm still kind of lost.  I'm not looking for anyone to specifically code this for me but I would greatly appreciate some direction.
I have a big block of JSON that I have imported into Python as a dictionary.  I have a function that will look through the records and add the IDs to a list.  However, this function will only look at the first "level" of children.  Can someone suggest how I begin to call this function recursively so it will follow the tree for however many levels deep it goes?
BTW, my data is essentially a dichotomous tree so I need it to follow multiple branching paths.
Here is the very messy function I have currently:
def addFighter(fighterDict, database):
    childID = [child["id"] for child in fighterDict["children"]]
    database.append(childID)

    for child in childID:
        addFighter(child)

I know my for loop is wrong, but I'm not sure where to find the proper resources that will explain the next steps.
Thank you for your help!
Edit:
Yes, I meant dichotomous tree.  Sorry if this is not a CS term.  I come from a wildlife biology background.  :)
My data is a Brazilian jiujitsu black belt lineage.  For example, Mitsuyo Maeda trained Luis Franca and Carlos Gracie Sr.  Luis Franca trained Oswaldo Fadda, who trained 9 people.  Carlos Gracie Sr. trained 21 people and so on.  The data is many levels deep and contains 1,664 black belts.
I have converted my data from JSON to a big nested dictionary.  I'm trying to convert it to a flat dictionary so it can be imported into Postgres using Psycopg2.  My end goal is to have a table that lists a fighter in one column and the second column would be a list of IDs or named of the people they trained.
Edit2:
Snippet of code:  (I'm not sure of the best way to format this here)
{"id":-301,"name":"The Beginning","data":"Mitsoyo Maeda, children [id]","children":    [{"id":467,"name":"Takeo Iano ","data":"Mitsoyo Maeda, children [id]","children":[{"id":974536,"name":"Francisco Sa ","data":"Mitsoyo Maeda, children [id]","children":[{"id":975533,"name":"Daniel Beleza ","data":"Mitsoyo Maeda, children [id]","children":[]},{"id":1168951,"name":"Carlos Pinto Sa ","data":"Mitsoyo Maeda, children [id]","children":[{"id":1169948,"name":"Reginaldo de Almeida ","data":"Mitsoyo Maeda, children [id]","children":[]},{"id":1272639,"name":"Ademir Oliveira ","data":"Mitsoyo Maeda, children [id]","children":[]},{"id":1273636,"name":"Daniel Taveras ","data":"Mitsoyo Maeda, children [id]","children":[]}]}]}]},{"id":1464,"name":"Mitsuyo Maeda ","data":"Mitsoyo Maeda, children [id]","children":[{"id":2461,"name":"Luis Franca ","data":"Mitsoyo Maeda, children [id]","children":[{"id":4455,"name":"Oswaldo Fadda ","data":"Mitsoyo Maeda, children [id]","children":[{"id":83218,"name":"Sergio Amarel ","data":"Mitsoyo Maeda, children [id]","children":[]},{"id":84215,"name":"Ronald Bauer ","data":"Mitsoyo Maeda, children [id]","children":[{"id":1230765,"name":"Victor da Costa ","data":"Mitsoyo Maeda, children [id]","children":[]}]},{"id":85212,"name":"Beto Ferrao ","data":"Mitsoyo Maeda, children [id]","children":[{"id":160984,"name":"Andre Assuncao ","data":"Mitsoyo Maeda, children [id]","children":[]}]},

A: That looks pretty close. From what I understand of the situation, this would be more appropriate:
database = []

def addFighter(fighterDict, database):
  # add this fighters id to the database
  database.append(fighterDict["id"])

  # get children if any
  children = fighterDict.get("children", [])

  for child in children:
    # for each child, run the addFighter method
    addFighter(child, database)

addFighter(someDictOfFighters, database)

print database

So, it seems like you have fighter dictionaries, that at least contain ids and a children key with values that are more fighter dictionaries. So something like: {"id": 1, "children": [{"id": 2, "children": [{"id": 4}]}, {"id": 3}]}. Think I got that right.
Passing this to the function, it gets the first id (1) and adds it to the database. It then sees the children (with ids 2 and 3) and runs the function on each of them.
For id 2, it adds 2 to the database, then runs the function on its children (4).
4 has no children so it adds 4 to the database, gets an empty list for the children and doesn't run any more recursion.
We then go up all the way back to the first instance of the function, and call it on the dict with id 3. 3 will be added to the database, and an empty list will exist for the children, and the function will not be called again from there.
We head back out to the first call, and we are done with the for loop. We know have, assuming database was a list, database = [1, 2, 4, 3].


text:
Q: Loop examples in bash Any examples for "loop" in bash?
for i in {1..5}; do echo $i; done
1
2
3
4
5

AND
for i in 1 2 3 4 5; do echo "Welcome $i times"; done
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

AND
# {START..END..INCREMENT}
for i in {0..10..2}; do echo "Welcome $i times"; done
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

AND
for i in $(seq 1 3 20); do echo "Welcome $i times"; done
Welcome 1 times
Welcome 4 times
Welcome 7 times
Welcome 10 times
Welcome 13 times
Welcome 16 times
Welcome 19 times

AND
for (( c=1; c<=5; c++ )); do echo "Welcome $c times..."; done
Welcome 1 times...
Welcome 2 times...
Welcome 3 times...
Welcome 4 times...
Welcome 5 times...

A: The for is superflous:
echo -e "\n"{1..5}

1
2
3
4
5

echo -e "\nWelcome "{1..5}" times"

Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

a recursive function:
toN () { max=$2 ; cur=$1; echo $cur; if (( cur < max )); then toN $((cur+1)) $max ; fi }
toN 0 5
0
1
2
3
4
5

a while-loop would be a bit boring, wouldn't it?
i=0; while ((i < 4)); do echo $((++i)); done ;

An not so very well known interactive loop in bash can be build with select:
select x in cat lolcat foo bar quit
do
  echo $x
  if [[ "$x" == "quit" ]]
  then
    break
  fi
done

1) cat
2) lolcat
3) foo
4) bar
5) quit
#? 1
cat
#? 2
lolcat
#? 2
lolcat
#? 1
cat
#? 5
quit


text:
Q: Code to find matching data and replace the data in the cell to the right I have two sets of Data on the same sheet, link below.
One is a very large list of products and their respective quantity in stock. (A:F)
Next to it is a list of (up to) forty of those items. (H:I)
I need a script that will find which of the forty items match the items on the"master list" and if they match change the old quantity (i.e: E3) to the new quantity (i.e: J3).
Hoping someone can help me as it is my last step in the project and I am stumped.
https://docs.google.com/spreadsheets/d/1fCaV9h2YUjgLIH5e5kxkHzvdEQc1IUtB60U356smiAY/edit#gid=1835594398
Thank you in advance.


text:
Q: Htaccess redirect with cakePHP I have a cakePHP app working at http://domain1.com/domain2, and want to point http://domain2.com/ to this application.
I have done this change the document root of domain2 to public_html/domain2, but, when I go to: domain2.com all css, javascript and images are not loaded, with a message saying controller not found.
What I can do?
All domains have a folder with their domains without the TLD at domain1.com, I think if I create a htaccess and get the domain without TLD, and finally change rewriteBase, will work as expected, but don't know how to do this.
Current htaccess of domain2:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

A: You can try adding an htaccess file in domain2's document root with the following rules:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} \.(css|js|png|jpe?g|gif|bmp|ico)$ [NC]
RewriteRule ^/?domain2/(.*) /$1 [L,PT]

This should remove the domain2 part of the links.


text:
Q: Function that concatenates a string and a integer converts to float before converting to string I've written an if-else function that, based on the number of the quarter, concatenates a string (i.e. '1/1/') with an integer converted to a string (i.e. str(2017)). I have three data frames I want to use this on. Two of the data frames produce the expected result (i.e. '1/1/2017'). The last data frame produces the following '1/1/2017.0'which makes it not convert to a datetime.
I'm at a loss because based on the dtypes, all three dataframes list both quarter and year as int64, and all three dataframes originally come from the same csv.
My first guess was that I had converted my years to a float at some point when I was preparing the last data frame. I tried to ensure that the year column was an integer with .astype(). The year column is listed under .dtypes as an int64 before and after the function is applied.
Data Frame
from pandas import DataFrame

Data = {'quarter': [1,2,3,4],
         'year': [2017,2017,2017,2017]}
df = DataFrame(Data, columns = ['quarter', 'year'])

This is the function I am using
def f(row):
    if row['quarter'] == 1:
        val = '1/1/' + str(row['year'])
    elif row['quarter'] == 2:
        val = '4/1/' + str(row['year'])
    elif row['quarter'] == 3:
        val = '7/1/' + str(row['year'])
    else:
        val = '10/1/' + str(row['year'])
    return val

My expected result would be '1/1/2017', '4/1/2017', '7/1/2017', '10/1/2017'
I don't receive any error messages or warnings.

A: Not sure why your code doesn't work with the third dataset, but you could use pandas' functions instead of writing your own. It might resolve your problem.
>>> df['date'] = pd.to_datetime(
...     df['year'].astype(str).str.cat(df['quarter'].astype(str), sep='Q'))
>>> df
   quarter  year       date
0        1  2017 2017-01-01
1        2  2017 2017-04-01
2        3  2017 2017-07-01
3        4  2017 2017-10-01

You could change date format like:
>>> df['date'].dt.strftime('%m/%d/%Y')
0    01/01/2017
1    04/01/2017
2    07/01/2017
3    10/01/2017
Name: date, dtype: object


text:
Q: Bouncing Ease Equation in C# I'm trying to add a bounce effect to an element of a game I'm making using C#. I can't seem to find the correct easing equation for this. Here's what I'm using for the time being:
t.position += (destination-t.position)*0.05f;
    if((destination-t.position).magnitude <= 0.01f)
    {
        t.position = destination;
    }

Can anyone help me with changing it to a bouncing equation?

A: if(setUpEase)
    {
        // Set the destination of each boardspace
        if(!oneTime)
        {
            beginning = new Vector3(t.position.x, t.position.y, t.position.z);
            destination = new Vector3(t.position.x, t.position.y-10, t.position.z);
            change = new Vector3(0, -10, 0);
            setUpDuration = Random.Range (1.0f, 3.0f);
            oneTime = true;
        }

        // BOUNCING
        currentTime += Time.deltaTime;
        float t2 = currentTime/setUpDuration;
        if(currentTime < setUpDuration)
        {
            if (t2 < (1/2.75f))
            {
                t.position = change*(7.5625f*t2*t2) + beginning;
            }
            else if (t2 < (2/2.75f))
            {
                t.position = change*(7.5625f*(t2-=(1.5f/2.75f))*t2 + 0.75f) + beginning;
            }
            else if (t2 < (2.5f/2.75f))
            {
                t.position = change*(7.5625f*(t2-=(2.25f/2.75f))*t2 + 0.9375f) + beginning;
            }
            else
            {
                t.position = change*(7.5625f*(t2-=(2.625f/2.75f))*t2 + 0.984375f) + beginning;
            }
        }
        else
        {
            t.position = destination;
            if(boardId < 113 && boardId > 92)
                pie.setUpEase2 = true;
            setUpEase=false;
        }
    }


text:
Q: Using qsort with an array of strucs When I try to use qsort to sort an array of structs, I get this error: qsort cannot convert from int to __compar_fn_t.
the source code is:
struct idpar_exchange
{
int idp;
long long int exchange_d;

};

int ptg_partitioning::compare_by_data(const void* a, const void* b)
{
struct idpar_exchange *ia= (struct idpar_exchange *)a;
struct idpar_exchange *ib= (struct idpar_exchange *)b;
return ia->exchange_d - ib->exchange_d;
}

struct idpar_exchange v[list_part.size()][list_part.size()];

qsort(v[i],(sizeof(v[i])/(sizeof(struct idpar_exchange))),sizeof(struct idpar_exchange),compare_by_data);


text:
Q: Platform specific files file.ios.js | file.android.js not detected correctly According to the react native documentation "React Native will detect when a file has a .ios. or .android. extension and load the relevant platform file when required from other components". I am trying to import a different store for each of the platform some.store.ios.js and some.store.android.js and instantiate it inside a single shared component my.component.js.
some.store.android.js
const SomeStore = class {
    consturctor() {
        console.log('Android')
    }
}
export default SomeStore

some.store.ios.js
const SomeStore = class {
    consturctor() {
        console.log('IOS')
    }
}
export default SomeStore

my.component.js functional component
import SomeStore from 'stores/some.store'
const MyComponent = observer(() => {
    [someStore]= useState(() => new SomeStore())
}

Unfortunately, I get the log IOS for both of the platforms. I have tested on real mobile devices.
The workaround that I am currently using is exporting stores with different names, importing both and selecting the needed on inside the component:
import SomeStoreAndroid from 'stores/some.store.android'
import SomeStoreIOS from 'stores/some.store.ios'

...

if(Platform.OS === "android") {
    [someStore]= useState(() => new SomeStoreAndroid())
} else {
    [someStore]= useState(() => new SomeStoreIOS())
}

But this shouldn't be needed, why doesn't the first (the natural) method work?


text:
Q: Flutter: ListView.builder pagination page refresh when adding more items to the list I have a ListView.builder widget which returns a list view which is coming from an API. This API has pagination so I added a scroll listener to listen to scroll to the bottom of the first page items and then call the API to load next page data.
  void _scrollListener() {
if (controller.position.maxScrollExtent == controller.position.pixels) {
  loadMoreData();
}}

I use provider as my state management method. So when I need to load more data , the app call the API which is in the provider model and add the data a list(the list which builds the ListView.buider) .
Container(
        child: AbsorbPointer(
      absorbing: contactsModel.isLoading,
      child: Container(
        child: Column(
          children: [
            Container(
                padding:
                    EdgeInsets.only(top: 20.0, left: 22.0, right: 22.0),
                width: w,
                child: searchPeopleField),
            Expanded(
              child: !contactsModel.isLoading
                  ? Stack(
                      children: [
                        Container(
                          child: contactsModel.allContacts.isNotEmpty
                              ? ListView.separated(
                                  controller: controller,
                                  scrollDirection: Axis.vertical,
                                  separatorBuilder:
                                      (BuildContext context, int index) =>
                                          Divider(
                                              height: 3,
                                              color: kBlack029,
                                              indent: 20,
                                              endIndent: 20),
                                  padding: const EdgeInsets.all(8),
                                  itemCount:
                                      contactsModel.allContacts.length,
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    return contactListView(
                                        context,
                                        index,
                                        contactsModel.allContacts,
                                        flag,
                                        baseUrl,
                                        urlLoad,
                                        widget.isFromAct,
                                        highlightText);
                                  })
                              : Center(
                                  child: contactsModel.isFromSearch
                                      ? UpsNoData()
                                      : noAPIData(w, h),
                                ),
                        ),
                        Visibility(
                            visible: contactsModel.isLoading,
                            child: Center(
                              child: progressIndicator(h),
                            )
                        )
                      ],
                    )
                  : Center(child: progressIndicator(h)),
            ),

This is how my UI works for this function. My problem is when I scroll down and load more data it adds next page data to the list. But it refreshes the page and goes back to the top of the list. See the below video.
click to see video(GIF)
How can I solve this? I want to list to be able to scroll from where it started to load more data.
  paginatingContactsList(context,step) async {
checkNetworkStatus(context).then((value) async {
  if (value == true) {
    isLoading = true;
    notifyListeners();
    await paginateContactsData(http.Client(), context,step).then((res) {
      resData = res;
      if(res != null && res.data != null) {
        for(var items in res.data){
          allContacts.add(items);
        }
      }
      isLoading = false;
      notifyListeners();
    });
    isFromSearch = false;
    notifyListeners();
  } else {
    Toast.show('Offline'.tr(), context,
        duration: 2, backgroundColor: Colors.redAccent);
  }
});

}


text:
Q: How to store data in a JSON file in React? In the src folder of a shopping app that I made with react and react-router, I've got a JSON file containing basic info about some products.
In the app component, I import the data and assign to the local state and pass it via props to my child components for their usage.
export default function App() {
  const [products, setProducts] = useState(require("./products.json"));
  ...
}

While all that worked, I want to trigger an event when the page gets reloaded and write the modified data from the state into the JSON file, so that the data is not lost.
window.onbeforeunload = () => {
  console.log("Page Reloaded");

  fs.writeFile("products.json", JSON.stringify(products), (ex) => {
    if (ex) throw ex.message;

    console.log("State copying successful.");
  });
};

I can see the Page Reloaded getting logged just for a moment before the page actually gets reloaded, but the data I wished to save remains unchanged.
I suspect the fs module isn't getting imported properly since I have logged it and got an empty object.  I've tried importing it manually as well as calling it with the require function.
import fs from "fs";

Any help would be really appreciated.


text:
Q: call trait method when struct method has same name In the following code:
pub trait Thinger {
    fn print_thing(&self) where Self: core::fmt::Debug {
        println!("trait method: {:?}", self);
    }
}

#[derive(Debug)]
pub struct Thing(f64);

impl Thing {
    fn print_thing(&self) where Self: core::fmt::Debug {
        println!("method: {:?}", self);
    }
}

impl Thinger for Thing {}

fn main() {
    let thing = Thing(3.14);
    thing.print_thing();
}

how do I call Thinger's print_thing method?
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0717f5615e10e3a1349f6db9cb9c3306
I've seen this in The Book, but I can't find it anywhere.

A: Thinger::print_thing(&thing)

<Thing as Thinger>::print_thing(&thing)

Here is the fragment of The Book you have been referring to.

A: Aleksander Krauze nailed it, but there is another way to do it for completeness:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4450b905f10198967090c8f56e3acfeb
Thinger::print_thing(&thing);


text:
Q: How to write & read a txt file inside a temporary directory? I want to have a temporary directory and inside a txt file that will be removed once the temp directory is closed. But when I try to write a txt file (created inside a temporary directory), the txt file is not written, with no content in it.
EXAMPLE:
import tempfile

message = 'this is my message'

with tempfile.TemporaryDirectory(dir='../', prefix='temp_') as td:
    td = td.replace(chr(92), '/')
    with open(f'{td}/filename.txt', 'w+') as temporary_file:
        temporary_file.write(message)
        temporary_file.read()
        # do some stuff here
# the temporary directory was closed, removing the txt file.


text:
Q: Creating _MouseLeftButtonDown for dynamically created rectangles in WPF My application shows the layout of an office floor where the seats are depicted as a rectangle and the margins, strokes, height, width and alignment are saved in the database for each Seat ID. Based on the allocation status, the fill of the rectangle is either red or green. Allocation status and the occupancy details are saved in the SQL db. I need to have separate MouseLeftButtonDown method for each rectangles. which will show me the occupant details.
//Code Behind
public SeatUserControl()
        {
         string cubeId = "";
         string status = "";
         string name = "";
         string number = "";
         int height = 0;
         int width = 0;
         int leftMargin = 0;
         int topMargin = 0;
            InitializeComponent();
            SqlDataAdapter data = new SqlDataAdapter();
            DataTable dt = new DataTable();
            string SqlQuery = "select c.SeatId,c.Height,c.Width,c.Stroke,c.MarginTop,c.MarginLeft,e.Status,e.EmpName,e.EmpNumber from SeatDetails c Join MasterData e ON c.SeatId =e.SeatId";
            SqlConnection sqlconn = new SqlConnection(connectionstring);
            sqlconn.Open();
            data = new SqlDataAdapter(SqlQuery, sqlconn);
            data.Fill(dt);
            try
            {
                foreach (DataRow row in dt.Rows)
                {
                    leftMargin = int.Parse(row["MarginLeft"].ToString());
                    topMargin = int.Parse(row["MarginTop"].ToString());
                    height = int.Parse(row["Height"].ToString());
                    width = int.Parse(row["width"].ToString());
                    status = row["Status"].ToString();
                    cubeId = row["SeatId"].ToString();
                    name = row["EmpName"].ToString();
                    number = row["EmpNumber"].ToString();
                    PlaceRectangles();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            sqlconn.Close();
        }
        public string PlaceRectangles()
        {
            Rectangle rect = new Rectangle();
            rect.Height = height;
            rect.Width = width;
            SolidColorBrush StrokeBrush = new SolidColorBrush(Colors.Black);
            rect.Stroke = StrokeBrush;
            rect.VerticalAlignment = VerticalAlignment.Top;
            rect.HorizontalAlignment = HorizontalAlignment.Left;
            rect.Margin = new Thickness(leftMargin, topMargin, 0, 0);
            rect.RadiusX = 8;
            rect.RadiusY = 5;
           if (status.Equals("Allocated"))
            {
                SolidColorBrush myBrush = new SolidColorBrush(Colors.RoyalBlue);
                rect.Fill = myBrush;
            }
           else if (status.Equals("Available"))
            {
                SolidColorBrush myBrush = new SolidColorBrush(Colors.Red);
                rect.Fill = myBrush;
            }
           else
            {
                SolidColorBrush myBrush = new SolidColorBrush(Colors.White);
                rect.Fill = myBrush;
            }
            seatCanvas.Children.Add(rect);
     }
}

//XAML
<UserControl x:Class="SpaceAllocator.SeatUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="580" d:DesignWidth="800">
    <Grid Height="580" Width="800">
        <Canvas Name="seatCanvas" Height="580" Width="800" Margin="0,3,-2,78">       </Canvas>
    </Grid>
</UserControl>
enter code here

A: When you create a rectangle add an event handler:
System.Windows.Shapes.Rectangle rect = new System.Windows.Shapes.Rectangle();
rect.MouseLeftButtonDown += rect_MouseLeftButtonDown;
// apply margins and what not

Then you handle your mouse left button down here:
void rect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
      var rect = sender as System.Windows.Shapes.Rectangle;
      // do whatever
}

A: If you call this code at startup of your application, an event handler is added automatically to all new objects of type Rectangle:
EventManager.RegisterClassHandler(typeof(Rectangle), MouseLeftButtonDownEvent,
    new MouseButtonEventHandler(OnMouseDown), false);

private void OnMouseDown(object sender, MouseButtonEventArgs e)
{
}


text:
Q: Analyzing binary taken from memory dump in IDA Pro I'm having problems with analyzing a simple binary in IDA Pro.
When running a program, i dumped part of its memory (for example, unpacked code section in the memory) into a file, using WinDbg.
I would like to analyze it using IDA, but when trying to just load the binary - it will only show its raw data.
Of course the binary is not a full PE file, so I'm not expecting a deep analysis, just a nicer way to read the disassembly.
So the question is - How can i make IDA disassemble the binary?
Thanks! :)

A: select an appropriate address and press c
that is MakeCode(Ea); ida will convert the raw bytes to code and disassemble it
pasted below is a simple automation with an idc script but idas automation is imho subpar so you should stick with manual pressing of C in user interface
:dir /b
foo.dmp
foo.idc
:xxd foo.dmp
0000000: 6a10 6830 b780 7ce8 d86d ffff 8365 fc00  j.h0..|..m...e..
0000010: 64a1 1800 0000 8945 e081 7810 001e 0000  d......E..x.....
0000020: 750f 803d 0850 887c 0075 06ff 15f8 1280  u..=.P.|.u......
0000030: 7cff 750c ff55 0850 e8c9 0900 00         |.u..U.P.....
:type foo.idc
#include <idc.idc>
static main (void) {
        auto len,temp,fhand;
        len = -1; temp = 0;
        while (temp < 0x3d && len != 0 ) {
                len = MakeCode(temp);
                temp = temp+len;
        }
        fhand = fopen("foo.asm","wb");
        GenerateFile(OFILE_LST,fhand,0,0x3d,0x1F);
        fclose(fhand);
        Wait();
        Exit(0);
}
:f:\IDA_FRE_5\idag.exe -c -B -S.\foo.idc  foo.dmp

:head -n 30 foo.asm | tail
seg000:00000000 ; Segment type: Pure code
seg000:00000000 seg000          segment byte public 'CODE' use32
seg000:00000000                 assume cs:seg000
seg000:00000000 assume es:nothing, ss:nothing, ds:nothing, fs:no    thing, gs:nothing
seg000:00000000                 push    10h
seg000:00000002                 push    7C80B730h
seg000:00000007                 call    near ptr 0FFFF6DE4h
seg000:0000000C                 and     dword ptr [ebp-4], 0

with windbg you can get the disassembly right from command line like this
:cdb -c ".dvalloc /b 60000000 2000;.readmem foo.dmp 60001000 l?0n61;u 60001000 60001040;q" calc
0:000> cdb: Reading initial command '.dvalloc /b 60000000 2000;.readmem foo.dmp 60001000 l?0n61;u 60001000 60001040;q'
Allocated 2000 bytes starting at 60000000
Reading 3d bytes.
60001000 6a10            push    10h
60001002 6830b7807c      push    offset kernel32!`string'+0x88 (7c80b730)
60001007 e8d86dffff      call    5fff7de4
6000100c 8365fc00        and     dword ptr [ebp-4],0
60001010 64a118000000    mov     eax,dword ptr fs:[00000018h]
60001016 8945e0          mov     dword ptr [ebp-20h],eax
60001019 817810001e0000  cmp     dword ptr [eax+10h],1E00h
60001020 750f            jne     60001031
60001022 803d0850887c00  cmp     byte ptr [kernel32!BaseRunningInServerProcess (7c885008)],0
60001029 7506            jne     60001031
6000102b ff15f812807c    call    dword ptr [kernel32!_imp__CsrNewThread (7c8012f8)]
60001031 ff750c          push    dword ptr [ebp+0Ch]
60001034 ff5508          call    dword ptr [ebp+8]
60001037 50              push    eax
60001038 e8c9090000      call    60001a06
6000103d 0000            add     byte ptr [eax],al
6000103f 0000            add     byte ptr [eax],al
quit:

ollydbg 1.10 view-> file-> (mask any file) -> foo.dmp -> rightclick -> disassemble