text:
Q: how to call my service in angular using setInterval I have a service which gets returns some data at the page load,
getAllTurbinesStat(){
  return this.http.get(this.url_stat_Turbines_all);
}

in my component I consume this service:
this.service.getAllTurbinesStat().subscribe( s => {
   this.allStats.push(s);
});

allStat is an array, now every 3 minutes this function should be run to update data, should setInterval be in service or in my component? And how should I write it? Because the first time I don't need the setinterval, because once the page loaded first time, my data is updated.

A: You can try this.
First create one function in your component like this.
getAllTurbinesStat() {
  this.service.getAllTurbinesStat().subscribe(s => {
    this.allStats.push(s);
  });
}

And then in from ngOnInit() or from constructor of your component use this.
this.getAllTurbinesStat();
setInterval(() => this.getAllTurbinesStat(), 180000);

A: You can use interval for that like below:
in you service
 getAllTurbinesStat(){
  return this.http.get(this.url_stat_Turbines_all);
 }

 getData(): {
   return interval(3000).pipe(
      switchMap( () => this.getAllTurbinesStat())
   )

 }

in your component
this.service.getData().subscribe( s => {
   this.allStats.push(s);
});

A: You can use timer from rxjs.
import { timer } from 'rxjs';

/*
  timer takes a second argument, how often to emit subsequent values
  in this case we will emit first value after 0 second and subsequent
  values every 3 minutes after
*/
const source = timer(0, 180000);
//output: 0,1,2,3,4,5......
const subscribe = source.subscribe(val => console.log(val));

For you case.
  return timer(0, 180000).pipe(
      flatMap( () => this.getAllTurbinesStat())
   )

A: First call your function one time in the ngOnInit of your component then get on with setInterval.
ngOnInit() {
   getAllTurbinesStat();
   setInterval(getAllTurbinesStat(), 3000);
}

getAllTurbinesStat() {
  return this.http.get(this.url_stat_Turbines_all);
}


text:
Q: jquery json facebook wall i try to follow this tutorial (http://tutorialzine.com/2011/03/custom-facebook-wall-jquery-graph/) but when i put my ID and ACCESS_TOKEN nothing happend, doesnt show the wall. Look, http://recorramisiones.com.ar/rutadelaselva/fbwall/. My ID an ACCESS_TOKEN works because the script show the facebook page title (RUTA DE LA SELVA). All the code is in the page tutorial. Can anyone help me? Thanks a lot

A: First of all, you shouldn't show your app access token in the source code. Anybody can steal it from there...
You can combine to two requests into one like this:
https://graph.facebook.com/larutadelaselvamisioneraguarani/?fields=name,picture,posts&access_token={access_token}

and you will receive a valid response. So if "nothing is shown", the problem is in your surrounding JS code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ERROR Windows headers require the default packing option on winnt.h I have an old C++ program I recovered to update and re-use it with Visual Studio 2019.
When I try to compile winnt.h, it gives the error:

Windows headers require the default packing option. Changing this can lead to memory corruption. This diagnosis can be disabled by building with WINDOWS_IGNORE_PACKING_MISMATCH defined

I saw this post Static assertion failed with "Windows headers require the default packing option..." and I already changed the packing option from 4bytes to default (Project Settings > C/C++ > Code Generation > Struct Member Alignment (change to Default)).
What am I missing? How can I solve it?

A: *

*Check if #pragma pack is used in the code. If you use #pragma pack, do not set Struct Member Alignment in the project configuration, because it will disturb the direct alignment of other code.

*Check whether your project platform settings are consistent with the property page settings.


text:
Q: Java ssh (jsch) set stream to UI instead of console I have a java program that uses the following lines to send ssh input/output to the console window.
channel.setInputStream(System.in);
channel.setOutputStream(System.out);

How might I acheive this using a UI instead of the console. For example, I have a UI with JTextPane panelOutput and JTextPane panelInput.
Same question as this person (unanswered):
Java Redirecting Input and Output Stream of Terminal to GUI (JSch)
Also, Is there an existing open source java program that does this already?

A: This site has a java ssh UI download:
http://www.ganymed.ethz.ch/ssh2/
In the zip, it is the file: SwingShell.java


text:
Q: How can I federate Azure AD B2C to Azure AD to protect an API? I have the need to incorporate Azure AD B2C into an web app that is already working with Azure AD. I found the poor Microsoft documentation an says that i have to federate Azure Ad B2C to Azure AD (https://learn.microsoft.com/en-us/azure/active-directory-b2c/faq?tabs=app-reg-ga). next I found this article that tries to explain the process https://medium.com/the-new-control-plane/connecting-azure-ad-b2c-to-azure-ad-via-the-b2c-custom-identity-provider-42fbc2832e32 but sadly it´s not clear enough.
If I create 2 different tenants which one should I use to protect my .Net 5 API and which one should I use to authenticate my web Angular 11 App?

A: You have two options

*

*User AAD B2C to federate to AAD using OIDC. Your apps will trust AAD B2C. You need to change the metadata URLs in the APIs to trust B2C tokens.

*Have your application and APIs trust both tokens, and through the app allow users to login via AAD B2C or AAD accounts.

I would recommend option 1.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/code-samples#web-apps-and-apis


text:
Q: Fitting a line to an asymptotic distribution in r I'm working on a school assignment, where I am supposed to preform a non linear regression on y= 1-(1/(1+beta*X))+U, we generate Y with a given beta value, and then treat X and Y as our observations and try to find the estimate of beta.
I've been trying to use the nls fuction, but the result always come out being very close to whatever starting value I select, not to the beta. Heres the code that I'm using so far:
set.seed(1)
Ut = (c(rnorm(1000, mean=0, sd=(sqrt(1)))))
Xt = (c(rnorm(1000, mean=0, sd=(sqrt(1)))))
beta = 3
Yt = (1-(1/(1+beta*Xt))+Ut)
df <- data.frame (Xt, Yt)
m<- nls (Yt ~ I(1-(1/(1+(betaF*Xt)))+Ut), data= df, start = list(betaF= 1))
summary (m)

In this case the estimate for beta comes out as being close to 1, not close to 3 as it should. Where am I going wrong? The function is asymptotic, should i be using a different function such as NLSstAsymptotic?


text:
Q: Powershell Datetime Filter Is Not Using Correct ShortDate Pattern I am trying to filter LastWriteTime on the Get-ChildItem function, however when I try to filter using a british date, it fails because it's not in the American format.
When I run (Get-Culture).DateTimeFormat.ShortDatePattern I receive dd/MM/yyy which is the correct format.
However when I execute the powershell filter statement :-
GCI 'C:\ | ?{$_.LastWriteTime -ge '21/01/2018'}
I receive the following :-
Cannot convert value "21/01/2018" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
However if I alter the date to 01/21/2018 I receive the correct results.
I have attempted to use $_.LastWriteTime.ToString('dd-MM-yyyy') -ge '01[![enter image description here][1]][1]/01/2018' which doen't work correctly as it returns dates from 2017.

A: Convert your date string to a date object first:
$date = get-date '21/01/2018'
gci C:\ | ? {$_.LastWriteTime -ge $date }


text:
Q: Notepad++ - Replace all array indexes incrementally I need to get rid of specific discovered_items from an array. An item that is incremented incorrectly causes the array to fail.
I have an array with varying digits that goes over 15000+, starting at one digit (0), all the way to five digits (example 13802), but the value that follows the colon has to remain. Say records 9000-11000 get taken out, I'd like to incrementally redo the whole numbering. How can I replace the values only inside the bracket ? If notepad++ cannot do it, is there a different program / method ?
discovered_items[13802]: 3629890649953796096


text:
Q: Simple calculation for all combination (brute force) of elements in two arrays, for better performance, in Julia I am new to Julia (some experience with Python). The main reason I am starting to use Julia is better performance for large scale data processing.
I want to get differences of values (int) of all possible combinations in two arrays.
Say I have two arrays.
a = [5,4]
b = [2,1,3]
Then I want to have differences of all combinations like
a[1] - b[1], a[1] - b[2] .....  a[3] - b[1], a[3] - b[2]
The result will be 3 x2  array [3 2; 4 3; 2 1]
Then something I came up is
a = [5,4]
b = [2,1,3]
diff_matrix = zeros(Int8, size(b)[1], size(a)[1])
for ia in eachindex(a)
    for ib in eachindex(b)
        diff_matrix[ib,ia]= a[ia] - b[ib]
    end
end
println(diff_matrix)

It works but it uses iteration inside of iteration and I assume the performance will not be great. In real application, length of array will be long (like a few hundreds), and this process needs to be done for millions of combinations of arrays.
Is there any better (better performance, simpler code) approach for this task ?

A: If you wrapped the code in a function your code would be already reasonably fast.
This is exactly the power of Julia that loops are fast. The only thing you need to avoid is using global variables in computations (as they lead to code that is not type stable).
I write the code would be "reasonably fast", as it could be made faster by some low-level tricks. However, in this case you could just write:
julia> a = [5,4]
2-element Vector{Int64}:
 5
 4

julia> b = [2,1,3]
3-element Vector{Int64}:
 2
 1
 3

julia> permutedims(a) .- b
3×2 Matrix{Int64}:
 3  2
 4  3
 2  1

and this code will be fast (and much simpler as a bonus).


text:
Q: NotifyDataSetChanged does not update the RecyclerView correctly I am trying to implement a fairly basic logic within my recyclerview adapter but notifyDataSetChanged() is giving me quite the headache.
I have a filter method that looks like this:
fun filter(category: Int) {
    Thread(Runnable {
        activeFiltered!!.clear()

        if (category == -1) {
            filterAll()
        } else {
            filterCategory(category)
        }

        (mContext as Activity).runOnUiThread {
            notifyDataSetChanged()
        }
    }).start()
}

where filterAll() and filterCategory() functions are quite easy:
private fun filterAll() {
    activeFiltered?.addAll(tempList!!)
}

private fun filterCategory(category: Int) {
    for (sub in tempList!!) {
        if (sub.category == category) {
            activeFiltered?.add(sub)
        }
    }
}

When I run this code and filter the list by category the activeFiltered list is updated correctly and contains the items I expect, but when notifyDataSetChanged() is run it only cuts the list's range without updating the items.
Is there a way to fix this?
I also tried, instead of notifyDataSetChanged() to use:
activeFiltered!!.forEachIndexed {index, _ ->  notifyItemChanged(index)}

but the problem is still there.
It isn't a threading issue either since I tried putting the whole logic in the main thread and the list still wasn't updated correctly.
This is my onBindViewHolder():
override fun onBindViewHolder(viewHolder: ActiveViewHolder, pos: Int) {
    sub = activeFiltered!![pos]
    inflateView()

}

This is where I inflate my text, sub is the instance variable set in the onBindViewHolder():
private fun inflateView() {
        viewHolder.title.text = sub.title
    }

A: It seems the implementation of onBindViewHolder() is incorrect. In order to update a list item, the passed in viewHolder parameter should be used (not the viewHolder you created in the onCreateViewHolder()).
The correct implementation should be like
override fun onBindViewHolder(viewHolder: ActiveViewHolder, pos: Int) {
    val sub = activeFiltered!![pos]
    inflateView(viewHolder, sub)
}

private fun inflateView(viewHolder: ActiveViewHolder, sub: <YourDataType>) {
    viewHolder.title.text = sub.title
}

By the way, it is not a good practice to hold something as a member field in order to access it in several methods. Feel free to pass it as arguments to such methods. In the above code I passed the sub as argument and not stored it as a member.
And also it is not necessary to hold the viewHolder that you create in onCreateViewHolder(). We mostly need them in some callback methods (like onBindViewHolder(), etc) and these methods will receive the right viewHolder as arguments.

A: I think you are using the original array in onBindView() instead of the filtered one.


text:
Q: How to use flume for uploading zip files to hdfs sink I am new to flume.My flume agent having source as http server,from where it getting zip files(compressed xml files) on regular interval.This zip files are very small (less than 10 mb) and i want to put the zip files extracted into the hdfs sink.Please share some idea how to do this.Do i have to go for a custom interceptor.

A: Flume will try to read your files line by line, except if you configure a specific deserializer. A deserializer lets you control how the file is parsed and split into events. You could of course follow the example of the blob deserizalizer, which is designed for PDFs and such, but I understand that you actually want to unpack them and then read them line by line. In that case you would need to write a custom deserializer which reads Zip and writes line by line events.
Here's the reference in the documentation:
https://flume.apache.org/FlumeUserGuide.html#event-deserializers


text:
Q: Пошаговое описание десктопного клиент приложения на Java Доброго времени суток
Просьба у меня довольно обычна для новичка в программировании. Заключается она в том, что я хочу сделать клиент приложение для VK, а познаний мало от слова совсем. Поэтому буду очень признателен если вы сможете описать поэтапно создание (использование API, получение токена, как его использовать), т.к. опыт был только в создании клиент-серверного приложения на плюсах. Заранее благодарен.

A: *

*Прочитайте учебник по Java

*Прочитайте документацию VK SDK

*Попытайтесь написать приложение

*Если что-то не получится, создайте вопрос на SO с описание конкретной проблемы.


text:
Q: How to improve grammar? I'm an non-immigrant came to US for my research purpose. I am not a native English speaker. I have never taken English that much seriously, may be because I had no problem in speaking English and understanding others who speak in English to me.
I can comprehend, express myself and pronounce English good enough. But what I struggle at is with grammar.
I have seem most of Americans don't mind about English grammar, unless that makes no sense. And for most of the time people don't follow grammar despite english being their first language.  But for me it's a big deal. I'm into academics and sooner or later a major part of my work will involve writing academic papers.
My question is, is there any natural way to learn English? I know that if I keep reading grammar books, then I will only improve my knowledge in English, but not actively use them when I actually take with others, or have to be consciously be aware of the concepts while writing/communicating with other. Is there any other technique or routine that I can put into practice so that I not only learn English but also start applying them naturally. To rephrase myself, I want to built my grammar intuition quickly.

A:
I have seem most of Americans don't mind about English grammar, unless that makes no sense.

That's very true, but rather unfortunate.  I'm glad you have noticed this, and it doesn't stop there.  We must, however, solidify our words into a form in which our thoughts are strongly conveyed: proper English.  This starts with correct grammar.
As a native English speaker, I do not know what it's like to learn English as a second language.  I can, however, provide a few suggestions:

*

*Read the classics.  The use of language in these works remains relevant to this day.

*Work through a strong grammar textbook.  Try to make the rules of English second-nature; these boundaries are there for a reason.

*Learn to diagram sentences.  You'll at least be able to visualize how each word and phrase changes the meaning of a sentence.

*Start writing.  This could be simply writing for yourself in a journal or self-assigned essay.

A: I'm sure you know the basics of English grammar, ie you understand grammar terms, you can distinguish between useful terms, and terms that you don't find useful and that you are able to change as you like, and high-flying terms that don't help much.
You can communicate in English and read English books. So you don't improve your grammar knowledge by working through a grammar. Most of it will be stuff you know. And it is boring to get grammatical things explained you already know.
The other way is more interesting. When reading you find structures or grammar points you are unsure about or that are new to you then consult your grammar and see if it has an item in its register and if the grammar can present the grammatical problem. It is a complicated technique to find things in a grammar you search an answer for. And not always grammars have an answer. As to use of prepositions or verb constructions a modern dictionary as Longman's DCE is often better. But a grammar can give an idea how verb constructions (with infinitive, participle, gerund, adjective) can  be arranged in a reasonable way so that someone can handle such things.
It is worthwhile working with a grammar this way, it takes time but it really improves your understanding of grammar. And sometimes you will find some things in grammars that can be arranged in a better order or that can be described in better and simpler terms.
It is useful to work with two different grammars. Interesting to see how differently things can be explained in grammar.


text:
Q: Finding $f'(0)$ when $f(x)=\int\limits_0^x\sin\left(\frac{1}{t}\right)dt$ I need to show that $f'(0)=0$ for
$$
f(x)=\int\limits_0^x\sin\left(\frac{1}{t}\right)dt
$$
But fundamental theorem of calculus is unapplicable here. What should I do?

A: Here is one approach:

*

*Use integration by parts to show that $f(x)=x^2\cos(1/x)-\int_0^x 2t\cos(1/t)dt$ for $x\neq 0$.

*Use this to show that $\left|\dfrac{f(x)}{x}\right|\leq 2|x|$.

A: To strengthen the convergence of an integral, a integration by parts is always a good idea.
Here we have
$$\begin{aligned}
f(x)
&=\int_0^x\sin\left(\frac 1t \right) dt\\
&= \left[ t^2 \cos\left(\frac 1t \right)\right]_0^x - \int_0^x 2t\cos\left(\frac 1t \right)dt\\
&= x^2 \cos\left(\frac 1x \right) - \int_0^x 2t\cos\left(\frac 1t \right)dt
\end{aligned}$$
You can apply the fundamental theorem of calculus for the second term, since it is the integral of a continuous function. The first term is a $O(x^2)$, so it is differentiable at zero with null derivative. In the end, we get $f'(0) = 0$.
[Reminder — A function $f$ is derivable at zero with derivative $a$ if and only if $f(x) = f(0) + ax + o(x)$ when $x\to 0$.]

A: You can use the fundamental theorem of calculus to show that $f$ is differentiable in an interval around $0$ and apply Rolle's theorem.


text:
Q: How do I get the currently visible text from a QTextEdit or QPlainTextEdit widget? It seems like this would be a common thing to do, but I can't find how.
I have a QTextEdit or QPlainTextEdit widget with a bunch of text. Enough that scrolling is necessary.
I want another widget to give some information about the currently visible text. To do this, I need to know

*

*when the visible text changes

*what's the text?

I see that QPlainTextEdit has the method firstVisibleBlock, but it's protected. This tells me that it's not really something I should be using in my application. I wouldn't otherwise  need to subclass from the edit window.
I also see that there's the signal updateRequest but it's not clear what I do with the QRect.
How do I do it or where do I find a hint?

A: I've written a minimal program that as two QTextEdit fields. In the left field you write and the text you are writing is shown in the second text edit too. You get the text of a QTextEdit by using toPlainText() and the signal is textChanged().
I've tested it and what you write in m_pEdit_0 is shown in "real-time" in m_pEdit_1.
main_window.hpp
#ifndef __MAIN_WINDOW_H__
#define __MAIN_WINDOW_H__

#include <QtGui/QtGui>
#include <QtGui/QMainWindow>
#include <QtGui/QApplication>

class main_window : public QMainWindow
{
    Q_OBJECT

public:
    main_window( QWidget* pParent = 0 );
    ~main_window();

public Q_SLOTS:
    void on_edit_0_text_changed();

private:
    QHBoxLayout* m_pLayout;
    QTextEdit* m_pEdit_0;
    QTextEdit* m_pEdit_1;
};

#endif // !__MAIN_WINDOW_H__

main_window.cpp
#include "main_window.hpp"

main_window::main_window( QWidget *pParent ) : QMainWindow( pParent )
{
    m_pEdit_0 = new QTextEdit( this );
    m_pEdit_1 = new QTextEdit( this );

    connect( m_pEdit_0, SIGNAL( textChanged() ), this, SLOT( on_edit_0_text_changed() ) );

    m_pLayout = new QHBoxLayout;
    m_pLayout->addWidget( m_pEdit_0 );
    m_pLayout->addWidget( m_pEdit_1 );

    QWidget* central_widget = new QWidget( this );
    central_widget->setLayout( m_pLayout );

    setCentralWidget( central_widget );
}

main_window::~main_window()
{
}

void main_window::on_edit_0_text_changed()
{
    m_pEdit_1->setText( m_pEdit_0->toPlainText() );
}

main.cpp
#include "main_window.hpp"

int main( int argc, char* argv[] )
{
    QApplication a(argc, argv);

    main_window mw;
    mw.show();

    return a.exec();
}

Edit:
This would work too, but would lack in performance for huge documents:
void main_window::on_edit_0_text_changed()
{
    QStringList text_in_lines = m_pEdit_0->toPlainText().split( "\n" );

    m_pEdit_1->clear();

    for( int i = 0; i < text_in_lines.count(); i++ )
    {
        m_pEdit_1->append( text_in_lines.at( i ) );
    }
}


text:
Q: Place a picture box inside another: VS2008 hope i can get some help here.
For a VB app, I try to place one picturebox over GDI+ drawn image (or another picturebox) in visual studio 2008, and the picturebox includes transparent areas which don't come up transparent.
I have looked through many methods but they don't suit my situation:
a background is drawn using GDI, and for my app I need a picturebox stationary upon it. (the stationary image cant be GDI+ drawn too, because the background updates every while, which causes it to disappear. tried to redraw image also but it makes an ugly flickering effect).
when i try to use picturebox as background, and assign it as parent for the overlaying image for transparency effect, the above image doesn't show at all. here is the VB code:
Dim back As PictureBox
Dim silhouetteAs PictureBox
Dim img As Bitmap = New Bitmap(imgPath)
img.MakeTransparent(Color.White)
back = New PictureBox()
silhouette= New PictureBox()
silhouette.Parent = back
silhouette.Size = New Point(width, height)
silhouette.Location = New Point(xpos, ypos)
silhouette.Image = img
silhouette.BackColor = Color.Transparent
back.Parent = MAIN
back.Size = New Point(width, height)
back.Location = New Point(xpos, ypos)
back.BackColor = Color.Blue

where back is the background and silhouette is the on-top image.
can someone please provide an example of how transparency achieved through parenting pictureboxes? or any other solution to this situation?

A: Never mind, found out what was wrong - when I assigned another picturebox as a parent, I didn't update the location of the overlaying picturebox relatively. the correction would be to
add:
silhouette.location=new point(0,0)

forgot that the coordinates are relative to the parent and not the form anymore.


text:
Q: Mysql (fulltext?) search for products I am building a very simple product catalog that will store products inside mysql table and I want to search products as fast as possible (and as relevant as possible). The products database will be quite large (about 500.000 products) which is why searches using "like" that are not using indexes are very slow.
I have many fields but the only ones I want to search are:

*

*product_id = bigint

*title = varchar(255)

*description = text

I tried experimenting with fulltext search but there were some problems:

*

*I couldn't search by product_id since it is big integer and can not be indexed inside fulltext index (sometimes user knows the ID of the product)

*if I search for "Meter XY-123" I get no search results even though the single product's title as well as description contains both words ("meter" and "xy-123")

*I couldn't search for substrings - e.g. if product's title is "Foobar 123" it should be returned even if user searches for:

*

*foo bar 123

*bar 123

*foobar 12

*foo

*etc.

*results should also be returned ordered by some kind of relevance.. e.g. if I have two products "foobar 123" and "foobar 456" and user searches for "foobar 4" then both products should be returned (match any word) but second product should be ranked higher (because it contains also number 4) than the first one (that doesn't contain number 4).

*products should also be ranked based on which field the value is found in. In this case product_id field has bigger weight than title which has also higher weight than description. E.g. if user searches for "1234" then:

*

*first ranked product should be the one that has product_id 1234

*afterwards there should be ranked products that include "1234" inside the title

*afterwards products that include this number inside description

What would be the best way to do searches on this table like this? The only way that gives results that are good in my case is splitting the query string and querying multiple queries using "like" operator for every string and somehow calculate the weight but this solution works very slow (even more than 15 seconds for a single query which is too slow).
I don't expect everything to be possible using only single query but I am looking for a solution that would be fast and as relevant as possible. If this means building some kind of custom word index or similar I am also willing to do this, I just need an idea how to manage this?
thank you!

A: We migrated search to Sphinx.. Now we need to fine-tune the results.


text:
Q: Show text in a richTextBox on a secon form on the first form I've a load button that load the file and call the second form. In the second form I've a richTextBox that has to show me text from the opened file, but it doesn't show nothing, here is what i've tried (I made richTextBox1 public to have access to it)
private void btnLoad_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();

        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            FormEditor f2 = new FormEditor();
            f2.ShowDialog();
            using (System.IO.StreamReader sr = new System.IO.StreamReader(ofd.FileName))
            {
                f2.richTextBox1.Text = sr.ReadToEnd();
            }
        }

    }

If I try the same code putting richTextBox in the first form it works.

A: When you open f2 (f2.ShowDialog()), the code for filling richtextbox has not been executed, so you get an empty textbox on f2 (The code after ShowDialog() , will execute as soon as you close f2). Try:
FormEditor f2 = new FormEditor();
using (System.IO.StreamReader sr = new System.IO.StreamReader(ofd.FileName))
{
     f2.richTextBox1.Text = sr.ReadToEnd();
}
f2.ShowDialog();

A: FormEditor should be reponsible of showing the text, not the current form.
Write constructor with parameter for FormEditor and pass text to it, then save it in a variable and show it in richtextbox on form load.
Your FormEditor class should look like this:
private string textForEdit{get;set;}
public FormEditor(string txt)
{
    textForEdit = txt;
}

private void FormEditor_load(object sender, EventArgs e)
{
    richTextBox1.Text = textForEdit;
}

Then, change inside of your if block to this:
using (System.IO.StreamReader sr = new System.IO.StreamReader(ofd.FileName))
{
    FormEditor f2 = new FormEditor(sr.ReadToEnd());
    f2.ShowDialog();
}


text:
Q: Dynamically instantiate Rails nested STI subclass? Let's say I have a class like:
class Basket < ActiveRecord::Base
  has_many :fruits

Where "fruits" is an STI base class having subclasses like "apples", "oranges", etc...
I'd like to be able to have a setter method in Basket like:
def fruits=(params)
  unless params.nil?
    params.each_pair do |fruit_type, fruit_data|
      fruit_type.build(fruit_data)
    end
  end
end

But, obviously, I get an exception like:
NoMethodError (undefined method `build' for "apples":String)

A workaround I thought of works like this:
def fruits=(params)
  unless params.nil?
    params.each_pair do |fruit_type, fruit_data|
      "#{fruit_type}".create(fruit_data.merge({:basket_id => self.id}))
    end
  end
end

But that causes the Fruit STI object to be instantiated before the Basket class, and so the basket_id key is never saved in the Fruit subclass (because basket_id doesn't exist yet).
I'm totally stumped.  Anyone have any ideas?

A: Instead of adding a setter method in Basket, add it in Fruit:
class Fruit < ActiveRecord::Base
  def type_setter=(type_name)
    self[:type]=type_name
  end
end

Now you can pass the type in when you build the object through an association:
b = Basket.new
b.fruits.build(:type_setter=>"Apple")

Note that you can't assign :type this way, since it is protected from mass assignment.
EDIT
Oh, you wanted to run different callbacks depending on the subclass? Right.
You could do this:
fruit_type = "apples"
b = Basket.new
new_fruit = b.fruits << fruit_type.titleize.singularize.constantize.new
new_fruit.class # Apple

or define a has_many association for each type:
require_dependency 'fruit' # assuming Apple is defined in app/models/fruit.rb

class Basket
  has_many :apples
end

then
fruit_type = "apples"
b = Basket.new
new_fruit = b.send(fruit_type).build
new_fruit.class # Apple

A: In Ruby terms, "#{x}" is simply equivalent to x.to_s which for String values is exactly the same as the string itself. In other languages, like PHP, you can de-reference a string and treat it as a class, but that's not the case here. What you probably mean is this:
fruit_class = fruit_type.titleize.singularize.constantize
fruit_class.create(...)

The constantize method converts from a string to the equivalent class, but it is case sensitive.
Keep in mind that you're exposing yourself to the possibility someone might create something with fruit_type set to "users" and then go ahead and make an administrator account. What's perhaps more responsible is to do an additional check that what you're making is actually of the right class.
fruit_class = fruit_type.titleize.singularize.constantize
if (fruit_class.superclass == Fruit)
  fruit_class.create(...)
else
  render(:text => "What you're doing is fruitless.")
end

One thing to watch out for when loading classes this way is that constantize will not auto-load classes like having them spelled out in your application does. In development mode you may be unable to create subclasses that have not been explicitly referenced. You can avoid this by using a mapping table which solves the potential security problem and pre-loading all at once:
fruit_class = Fruit::SUBCLASS_FOR[fruit_type]

You can define this constant like this:
class Fruit < ActiveRecord::Base
  SUBCLASS_FOR = {
    'apples' => Apple,
    'bananas' => Banana,
    # ...
    'zuchini' => Zuchini
  }
end

Using the literal class constant in your model will have the effect of loading them immediately.


text:
Q: Display empty dates in grouping? I'm currently using MySQL to count the number of rows created by date for the past week.
This is a sample of what my Table looks like:

With the following SQL query (and considering it's April 20, 2013)
SELECT DATE(Date) AS Date,
       COUNT(id) AS Count
FROM notes
WHERE UNIX_TIMESTAMP(Date) + 604800 >= UNIX_TIMESTAMP()
GROUP BY DAY(Date)
ORDER BY Date ASC

I get the following result.

However, since I'm going through the past week I also want the days where there are no rows like such:

How would I accomplish this?

A: I believe the simplest way is
select a.*, b.`Count`
   FROM
   (
   select date(now()) as dt
   union all
   select date(now()-interval 1 day)
   -- then the same for - 2 day, -3 , etc
   )a
   LEFT JOIN
   (
     --your query
   )b ON (a.dt = b.`date`)


text:
Q: C++ Timer class, also usage in QNX with pulse message I wrote a timer class for my project. I used standard C++ function calls for it.
I want to create a timer (start, stop, pause, continue, reset) it and also pass it new timings.
If the timer fires before I stop it, I want to get a qnx pulse message on a given channel.
This is the header:
#ifndef TIMER_H_
#define TIMER_H_

#include <time.h>
#include <sys/neutrino.h>
#include "HWaccess.h"
#include "address.h"

#define MILLISECONDS_NANOSECONDS_CONV   1000000
#define SECONDS_MILLISECONDS_CONV       1000

class Timer {
public:
    /**
     * Constructor creates a new timer, attaches to the given
     * channel.
     * Does not start timer!
     *
     * @param chid
     * @param seconds
     * @param milliseconds
     * @param msg
     */
    Timer(int chid, int sec, int msec, int msg);

    /**
     * Deletes timer after detach from channel
     */
    virtual ~Timer();

    /**
     * Starts the timer
     */
    void start();

    /**
     * Stops timer and resets it to initial values
     */
    void stop();

    /**
     * Pauses the timer
     */
    void pause();

    /**
     * Continues the timer
     */
    void cont();

    /**
     * Resets the timer to initial values
     */
    void reset();

    /**
     * Changes timer values to new given values and
     * resets it
     * Does not start the timer!
     *
     * @param seconds
     * @param milliseconds
     */
    void changeTime(int sec, int msec);

private:
    /**
     * Timer ID
     */
    timer_t timerid;

    /**
     * Timerstruct for running timer
     */
    struct itimerspec timer;

    /**
     * Timerstruct for backing up the running timer
     */
    struct itimerspec backupTimer;

    /**
     * timer value: seconds
     */
    int seconds;

    /**
     * timer value: milliseconds
     */
    int miliSeconds;

    /**
     * Connection ID for timeout pulse
     */
    int coid;

    /**
     * Event structure for timer if it fires
     */
    struct sigevent event;
};

#endif /* TIMER_H_ */

...and the implementation:
#include "Timer.h"

Timer::Timer(int chid, int sec, int msec, int msg) {
    if ((coid = ConnectAttach(0, 0, chid, _NTO_SIDE_CHANNEL, 0)) == -1) {
        printf("Timer: Error in ConnectAttach\n");
    }

    SIGEV_PULSE_INIT(&event, coid, SIGEV_PULSE_PRIO_INHERIT, PULSE_FROM_TIMER, msg/*Timer abgelaufen*/);

    if (timer_create(CLOCK_REALTIME, &event, &timerid) == -1) {
        printf("Timer: Error in timer_create()\n");
    }

    seconds = sec;
    miliSeconds = msec;

    reset();
}

Timer::~Timer() {
    if (ConnectDetach(coid) == -1) {
        printf("Timer: Error in ConnectDetach\n");
    }

    if (timer_delete(timerid) == -1) {
        printf("Timer: Error in timer_delete()\n");
    }
}

void Timer::start() {
    if(timer_settime(timerid, 0, &timer, NULL) == -1){
        printf("Timer: Error in timer_settime()\n");
    }
}

void Timer::stop() {
    // stop timer
    timer.it_value.tv_sec = 0;
    timer.it_value.tv_nsec = 0;
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_nsec = 0;
    if(timer_settime(timerid, 0, &timer, NULL) == -1){
        printf("Timer: Error in timer_settime()\n");
    }

    // reset it
    reset();
}

void Timer::pause() {
    timer.it_value.tv_sec = 0;
    timer.it_value.tv_nsec = 0;
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_nsec = 0;

    // backup running timer values
    if(timer_gettime(timerid, &backupTimer) == -1){
        printf("Timer: Error in timer_gettime()\n");
    }
    // disarm
    if(timer_settime(timerid, 0, &timer, NULL) == -1){
        printf("Timer: Error in timer_settime()\n");
    }
}

void Timer::cont() {
    // recover old values
    timer = backupTimer;
    // Arm timer
    if(timer_settime(timerid, 0, &timer, NULL) == -1) {
        printf("Timer: Error in timer_settime()\n");
    }
}

void Timer::reset(){
    timer.it_value.tv_sec = seconds;
    timer.it_value.tv_nsec = miliSeconds * MILLISECONDS_NANOSECONDS_CONV;
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_nsec = 0;
}

void Timer::changeTime(int sec, int msec){
    seconds = sec;
    miliSeconds = msec;
    reset();
}

1) Can I set the timer struct's values to zero (to stop the timer) and backup the values in another back struct the way I am doing it? Or is the running timer decremented in the timer struct?
2) Can i easily restore the old timer values with a simple timer = backupTimer?
3) And finally, if I create and start a timer in a function, something like this:
void coolClass::interestingFunction() {
    //do other time consuming stuff here...
    Timer timer(chid, 10, 0);
    timer.start();
}

... then the timer is created on the stack and when I exit this function (and its variables etc.) are no longer valid. Will the timer still count down and fire my pulse? Or will I have to use a classifier in my header file for this timer?

A: Ok i fixed all my problems ;>
if some1 is interested in how, heres the modified code:
#include "Timer.h"

Timer::Timer(int chid, int sec, int msec, int msg) {
    if ((coid = ConnectAttach(0, 0, chid, _NTO_SIDE_CHANNEL, 0)) == -1) {
        printf("Timer: Error in ConnectAttach\n");
    }

    SIGEV_PULSE_INIT(&event, coid, SIGEV_PULSE_PRIO_INHERIT, PULSE_FROM_TIMER, msg/*Timer abgelaufen*/);

    if (timer_create(CLOCK_REALTIME, &event, &timerid) == -1) {
        printf("Timer: Error in timer_create()\n");
    }

    seconds = sec;
    miliSeconds = msec;

    reset();
}

Timer::~Timer() {
    if (ConnectDetach(coid) == -1) {
        printf("Timer: Error in ConnectDetach\n");
    }

    if (timer_delete(timerid) == -1) {
        printf("Timer: Error in timer_delete()\n");
    }
}

void Timer::start() {
    //TODO running flag, wg doppelt pause / continue
    if(timer_settime(timerid, 0, &timer, NULL) == -1){
        printf("Timer: Error in timer_settime()\n");
    }
}

void Timer::stop() {
    // Stoppe den Timer
    if(timer_settime(timerid, 0, NULL, NULL) == -1){
        printf("Timer: Error in timer_settime()\n");
    }

    // Zuruecksetzen
    reset();
}

void Timer::pause() {
    // disarm (da erster Wert NULL)
    if(timer_settime(timerid, 0, NULL, &backupTimer) == -1){
        printf("Timer: Error in timer_settime()\n");
    }
}

void Timer::cont() {
    // Arm, da Werte im struct wieder != 0
    if(timer_settime(timerid, 0, &backupTimer, NULL) == -1) {
        printf("Timer: Error in timer_settime()\n");
    }
}

void Timer::reset(){
    timer.it_value.tv_sec = seconds;
    timer.it_value.tv_nsec = miliSeconds * MILLISECONDS_NANOSECONDS_CONV;
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_nsec = 0;
}

void Timer::changeTime(int sec, int msec){
    seconds = sec;
    miliSeconds = msec;
    reset();
}


text:
Q: List Comprehension in Python Let's say I have a list of tuples:
a = [(1, 2), (3, 4), (4, 5)]

and another list, no tuples:
b = [1, 2, 3]

How would I use list comprehension to multiply only the first value of each tuple in a by each respective value in b? That is, [a[0][0] * b[0], a[1][0] * b[1], a[2][0] * b[2]]
(Should equal [1, 6, 12])

A: >>> a = [(1, 2), (3, 4), (4, 5)]
... b = [1, 2, 3]
>>> [x[0]*y for x, y in zip(a, b)]
[1, 6, 12]

The zip function is the key.

A: For instance, you can use
[a[0]*b for a,b in zip(a,b)]
The zip function creates a list of tuples. The list is as long as the shortest list of arguments to zip, and the ith element of each tuple comes from the ith argument of zip.
>>> c = [1, 2, 3]
>>> d = [4, 5, 6]
>>> zip(c,d)
[(1, 4), (2, 5), (3, 6)]

A: For giant lists you better use izip from itertools as you don't need to create a new list before iterating over it: http://pymotw.com/2/itertools/#producing-new-values. A huge advantage of this methodology is that you are not limited to sequences. You can use generators as well.
import itertools as it

a = [1,2,3,4,5]
b = [6,7,8,9,10]

for e in it.izip(a,b):
    print e

This prints the tuples:
(1, 6)
(2, 7)
(3, 8)
(4, 9)
(5, 10)


text:
Q: Convert column dummies into row dummies in R I'm trying to convert several column dummies into one dummies.
What I have now:
HS2002 <- c(30343, 30344, 30345, 30346, 30349)
Original.rate <- c(10, 12, 10, 13, 2)
2004 <- c(0, 0, 0, 1, 0)
2005 <- c(0, 1, 0, 1, 0)
2006 <- c(1, 1, 0, 1, 0)
format1 <- data.frame(HS2002, Original.rate, `2004`, `2005`, `2006`)

What I want to have:
HS2002 <- c(30343, 30343, 30343, 30344, 30344, 30344, 30345, 30345, 30345, 30346, 30346 30346, 30349, 30349,30349)
Year <- c(2004, 2005, 2006,2004, 2005, 2006,2004, 2005, 2006,2004, 2005, 2006,2004, 2005, 2006,)
Original.rate(10, 10, 10, 12, 12, 12, 10, 10, 10, 13, 13, 13, 2, 2, 2)
Treatment <- (0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0)
format2 <- data.frame(HS2002, Year, Original.rate, Treatment)

The dataset I'm actually using has 2004 to 2016 data, and thousands of different HS2002 codes. I suspect the solution is some variation expand.grid or what's illustrated in How to convert multiple columns to individual rows in R, but I haven't gotten melt in reshape2 to work yet.
Fairly new to R at this point, so I'm hoping I don't have to resort to for loop yet. Any ideas? Thanks in advance.


text:
Q: Capturing groups with condition on existence I have url like
http://localhost:8080/web/group/555/content/777/image?arg1=1&arg2=2#anchor

There are 3 parts i'm trying to get: group number, content number and the view type value which is "image" in the sample above (can be one of predefined set of values and it is guarateed no values with text "group" or "content").
I got following regexp so far (it has 3 capturing groups i need)
/.*(?:\/group\/([\d]+))(?:\/content\/([\d]+))\/([\w]+).*/g

which works only when all the parts are present.
The problem is any of the part can be absent (except "view type"), so next urls are also valid:
http://localhost:8080/web/content/777/image
// which has $1="", $2="777", $3="image"
http://localhost:8080/web/nogroup/555/content/777/video
// which has $1="", $2="777", $3="video"
http://localhost:8080/web/audio
// which has $1="", $2="", $3="audio"

Is there a way to tell regexp: if there is no matching for the group $1 set its value to ""?

A: You need to add a question mark ? after each of the groups that can be present but aren't necessary for a match and it will automatically populate them with "":
/.*(?:\/group\/([\d]+))?(?:\/content\/([\d]+))?\/([\w]+).*/g


text:
Q: Issues with overriding the Opportunity New button When I try to override the new button, I get an error, and it looks like the record was trying to be saved.  What's going on ?
Here's the code
<apex:page standardController="Opportunity" extensions="OpportunityController" action="{!oppRenamer}" >

</apex:page>

apex
public OpportunityController(ApexPages.StandardController controller) {
        string url = ApexPages.currentPage().getUrl() ;
        this.oppId = ApexPages.currentPage().getParameters().get('id');

        if (this.oppId != null){
            //do  pre existing stuff
        }
        }else{
            //do nothing. this is the case of a new opp being created.
        }

    }

    public PageReference oppRenamer() {
        PageReference pr = new PageReference('/006/e');
        Map<String, String> m = pr.getParameters();
        // Keep existing parameters
        m.putAll(ApexPages.currentPage().getParameters());
        // Add Opportunity name parameter
        m.put('opp3', 'DO NOT MODIFY');
        // Turn off the override so you go to the default UI page (and not an infinite loop)
        m.put('nooverride', '1');
        if  (m.keySet().contains('save_new')){
            m.remove('save_new');
            m.put('save_new', '0');
        }
        return pr;
    }

A: the save_new parameter was messing it up. when i just remove it, it works.


text:
Q: How to insert data from drop down menu to SQL I need to make a couple of dropdown menus, and then insert the data into a SQL database. But it doesn't let me take data from the dropdown menu like it does with entries, how can I get and add data from the dropdown menu to my sql database?
Currently it gives the error "AttributeError: 'OptionMenu' object has no attribute 'get'"
I tried to remove .get() from the end of it, but that didn't help.
Here is my code:

def vorm():
    #Aken
    top= Toplevel(ws)
    top.geometry("720x200")
    top['bg'] = '#26658f'

    options= [
        "P",
        "V"
    ]

    clicked = StringVar()
    clicked.set("P")

    #Tekst
    Kuupäev = Label(top,text="Kuupäev", background="#26658f")
    Kuupäev.grid(row=0,column=0,padx=(10, 10))
    Tellimus= Label(top,text="Tellimus", background="#26658f")
    Tellimus.grid(row=0,column=1,padx=(10, 10))
    Pos = Label(top,text="Pos", background="#26658f")
    Pos.grid(row=0,column=2,padx=(10, 10))
    Klient = Label(top,text="Klient", background="#26658f")
    Klient.grid(row=0,column=3,padx=(10, 10))
    Toode = Label(top,text="Toode", background="#26658f")
    Toode.grid(row=0,column=4,padx=(10, 10))
    Operatsioon = Label(top,text="Operatsioon", background="#26658f")
    Operatsioon.grid(row=2,column=0,padx=(10, 10))
    Kogus = Label(top,text="Kogus", background="#26658f")
    Kogus.grid(row=2,column=1,padx=(10, 10))
    Käsi = Label(top,text="Käsi", background="#26658f")
    Käsi.grid(row=2,column=2,padx=(10, 10))
    Operaator = Label(top,text="Operaator", background="#26658f")
    Operaator.grid(row=2,column=3,padx=(10, 10))
    Pink = Label(top,text="Pink", background="#26658f")
    Pink.grid(row=2,column=4,padx=(10, 10))
    #Kirjakastid
    Kuupäev_entry = Entry(top)
    Kuupäev_entry.grid(row=1,column=0,padx=(10, 10))
    Tellimus_entry = Entry(top)
    Tellimus_entry.grid(row=1,column=1,padx=(10, 10))
    Pos_entry = Entry(top)
    Pos_entry.grid(row=1,column=2,padx=(10, 10))
    Klient_entry = Entry(top)
    Klient_entry.grid(row=1,column=3,padx=(10, 10))
    Toode_entry = Entry(top)
    Toode_entry.grid(row=1,column=4,padx=(10, 10))
    Operatsioon_entry = Entry(top)
    Operatsioon_entry.grid(row=3,column=0,padx=(10, 10))
    Kogus_entry = Entry(top)
    Kogus_entry.grid(row=3,column=1,padx=(10, 10))
    Käsi_entry = OptionMenu(top, clicked, *options)
    Käsi_entry.grid(row=3,column=2,padx=(10, 10))
    Operaator_entry = Entry(top)
    Operaator_entry.grid(row=3,column=3,padx=(10, 10))
    Pink_entry = Entry(top)
    Pink_entry.grid(row=3,column=4,padx=(10, 10))

    #"Tühjenda"
    def delete():
        Kuupäev_entry.delete(0, 'end')
        Tellimus_entry.delete(0, 'end')
        Pos_entry.delete(0, 'end')
        Klient_entry.delete(0, 'end')
        Toode_entry.delete(0, 'end')
        Operatsioon_entry.delete(0, 'end')
        Kogus_entry.delete(0, 'end')
        Käsi_entry.delete(0, 'end')
        Operaator_entry.delete(0, 'end')
        Pink_entry.delete(0, 'end')

    #"Salvesta"
    def submit_it():
        con1 = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=192.168.1.8;DATABASE=HUT;UID=######;PWD=######')

        cur2 = "insert into PROD_MachiningEventsTEST ([Date], [Order], [Position], [Client], [Product], [Operation], [Amount], [OpeningSide], [Operator], [Machine]) values(?,?,?,?,?,?,?,?,?,?)"
        val = (Kuupäev_entry.get(), Tellimus_entry.get(), Pos_entry.get(), Klient_entry.get(), Toode_entry.get(), Operatsioon_entry.get(), Kogus_entry.get(), Käsi_entry.get(), Operaator_entry.get(), Pink_entry.get())
        cur1 = con1.cursor()
        cur1.execute(cur2,val)

        con1.commit()
        con1.close()
        close_win(top)

A: You need to use the tkinter variable (clicked) linked to the OptionMenu (Käsi_entry) instead:
val = (Kuupäev_entry.get(), Tellimus_entry.get(), Pos_entry.get(),
       Klient_entry.get(), Toode_entry.get(), Operatsioon_entry.get(),
       Kogus_entry.get(), clicked.get(), Operaator_entry.get(), # used clicked instead of Käsi_entry
       Pink_entry.get())


text:
Q: How to fail ASP.NET Web API deserialization when types do not match I am having a problem with silently failing deserialization in ASP.NET Web API (version 5.1.2). I would like the deserialization to raise an error instead but I am unable to find a configuration for it.
My specific (simplified) case is this. A client application (AngularJS) sends a HTTP POST request to the ASP.NET Web API backend. As a payload there are a bunch of strings:
["ABC100", "ABC200", "ABC300"]

However, the server is expecting a list of integers:
List<int> Ids { get; set; }

What ends up happening is that the deserialization fails, the Ids list will be empty and there are no errors.
Ids: []

Of course the mismatch needs to be fixed as well, but it seems obvious to me that the POST request should fail in this case. How can I make it the default?

A: One solution to this problem seems to be checking the ModelState.IsValid property right at the start of the controller method:
[HttpPost]
[Route("Stuff/Ids/")]
public void PostStuff(List<int> Ids)
{
    if(!ModelState.IsValid)
        throw new Exception("ModelState is not valid.");

    // Carry on...
}

The ModelState.IsValid is indeed false in the case described by my question.
The check can be made global by creating an action filter out of it. Instructions for this can be found for example in this article: Model Validation in ASP.NET Web API


text:
Q: Why do I have to use an extra method in this code? I don't get why I have to use square() in this code? Why can't I just add n times n to the String s?
static int square(int n){
   return n*n;
}
static void ausgabe(int n){
   String s;
   int i = n;
   s = "SquareOf" + i + " = " + square(i);
   Sysout(s);
}

my solution would be to miss out the square method and just add like this
s = "SquareOf" + i + " = " + i*i;

I tried and the result is always right. But our book suggests the first way and I would just like to know why they make it more complicated in my eyes.
Thanks in advance.

A: Well, you are partially right, BUT software is developed better when you split thing according of what they do...
The method Ausgabe have a job: display the result only
The method square have a job: do the math operation only
So the whole point behind soft development is not that the code works
we try to do something else:

*

*it must work

*it must be easy to maintain

*it must be easy to improve

all those requirements are related to the project's complexity and can be reached based on a single responsibility principle

A: For something as trivial as i*i you wouldn't need a method. However if instead have to do a more complicated operation which would require quite a few lines of code, then it would be a good idea to put that in its own method in order to keep your code clean and easy to read, understand and maintain. Moreover if you need to do the same operation at multiple points in your program, then a method would be beneficial as you do not have to copy/paste the same code over and over again in different places.


text:
Q: Hide "refresh" action bar item while showing indetermidate progress bar in action bar Im a big fan of Jakes ActionbarSherlock classes.
I have a news feed in my app, and would like to show a indetermidate progressbar when fetching data to that news feed.
So i use this code:
...
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setSupportProgressBarIndeterminateVisibility(false);
...

This works fine but the progressbar is displayed next to my refresh action bar item. I would like to hide the refresh item while showing the indetermidate progress.
Any ideas how to do this?
Thanks!


text:
Q: Using all the dates in a given table I've been currently working on a stored procedure that grabs all the clients I have in the database that have loans. How I'm filtering the results is by the start and end dates given when generating the data. The way my data works is that the returned table will have multiple date fields, 9 date fields to be precise. Each of these date fields are used depending on the LoanStatus field that is also a part of this table. LoanStatus can have values such as Settled, Approved, Cancelled.. What I want to do is to filter the results using this start and end date but applying it to all of the date fields
In my head I've got a couple of pseudo ways to possibly work this issue out:
First Possible Solution
Need some code that'll allows me to essentially do this:
allDatefields > @startDate AND allDatefields < @endDate.

Second Possible Solution
Is to only take into consideration the date field that matches with the loan status. For example, if the LoanStatus is Settled, then look at the DateSettled column of the table, or if the LoanStatus is Approved, then look at the ApprovalDate column of the database.
Personally, I would love to be able to filter through and apply the @startDate and @endDate to all date fields rather than have to look at each date seperately.
Is there a way in SQL Server to apply a WHERE clause to all date fields in a table?

A: To my knowledge, the where clause does not support your first scenario. I think you might have to settle for something like this:
(LoanStatus = 'Approved' and ApprovalDate > @startDate AND ApprovalDate < @endDate) OR (LoanStatus = 'Settled' and SettleDate > @startDate AND SettleDate < @endDate) OR ... same for the rest of loan status values


text:
Q: Select from MYSQL where the first four characters are I have a database, in one of the fields occasionally I get an entry which starts off as mail.domainname.com
Is it possible using mysql and php to select only the rows from the field hostname where the first 4 characters = 'mail'?

A: Case sensitive:
SELECT * FROM tbl WHERE hostname LIKE BINARY 'mail%'

Case insensitive:
SELECT * FROM tbl WHERE hostname LIKE 'mail%'

A: One way to do it is to use LIKE
SELECT * FROM tablename WHERE hostname LIKE 'mail%'

Another is to use SUBSTR()
SELECT * FROM tablename WHERE SUBSTR(hostname, 1, 4) ='mail'

A: Yes, you can use SQL LIKE operator: http://www.w3schools.com/sql/sql_like.asp

A: Simply use:
SELECT * FROM your_table WHERE SUBSTR(field_name, 1, 4) = 'mail'


text:
Q: Couldn't run a ffmpeg process by using supervisor This issue seems to be weird, at least for me.
I'm trying to run a ffmpeg process using the supervisor as follows:
[program:myprocessname]
command="/usr/bin/ffmpeg -loglevel quiet -i ..."
process_name=%(program_name)s
numprocs=1
umask=022
priority=999
autostart=true
autorestart=unexpected
startretries=3
exitcodes=0
stopsignal=TERM
stopwaitsecs=10
user=vagrant

This program never gets run, in spite of changing the command to the absolute path where the FFmpeg is located.
This is what I get (from log) when I try to run it:
{
    "description": "can't find command '/usr/bin/ffmpeg -loglevel quiet -i
 ...'",
    "exitstatus": 0,
    "group": "myprocessname",
    "logfile": "/var/log/supervisor/myprocessname-stdout---supervisor-oxWFk5.log",
    "name": "myprocessname",
    "now": 1554747933,
    "pid": 0,
    "spawnerr": "can't find command '/usr/bin/ffmpeg -loglevel quiet -i ...'",
    "start": 1554747575,
    "state": 200,
    "statename": "FATAL",
    "stderr_logfile": "/var/log/supervisor/myprocessname-stderr---supervisor-WNmJv6.log",
    "stdout_logfile": "/var/log/supervisor/myprocessname-stdout---supervisor-oxWFk5.log",
    "stop": 0
}

It might be that FFmpeg spawns processes where the supervisor couldn't handle?
Any idea, please?

A: This issue has been fixed by removing the quotes from the command
[program:myprogam]
command="/usr/bin/ffmpeg ... With qoutes"
...

Changed to:
[program:myprogam]
command=/usr/bin/ffmpeg ... No quotes
...

A: Look for more information in the following logs:
"stderr_logfile": "/var/log/supervisor/myprocessname-stderr---supervisor-WNmJv6.log"
"stdout_logfile": "/var/log/supervisor/myprocessname-stdout---supervisor-oxWFk5.log"
It seems that ffmpeg is not installed in /usr/bin. Or not installed at all.


text:
Q: Directly Obtaining the $n$th Value of a Lucas Sequence (As an aside: This question lies relatively upon the border between the realms of Computer Science and Mathematics, and thus may be appropriate for StackOverflow as well.)
I am in need of a method of computationally finding the $n$th number of a Lucas Sequence of the first kind.
Given integer parameters $P$ and $Q$, a Lucas Sequence of the first kind $U_n(P, Q)$is defined by the following recurrence relation:
$U_0(P, Q) = 0$
$U_1(P, Q) = 1$
$U_n(P, Q) = P \cdot U_{n-1}(P, Q) - Q \cdot U_{n-2}(P, Q)$ for $n > 1$
This naturally lends itself to a recursive process, however for large values of $n$, this tends to be particularly time intensive, and cannot be performed by a computer in any reasonable amount of time.
I managed to implement the process iteratively, which massively reduced the time required to calculate the $n$th value, but for large numbers, the process is still quite time consuming.  This is due to the fact that both recursive and iterative algorithms require computing every value $U_0(P, Q), U_1(P, Q), ... ,U_{n-1}(P, Q)$ in order to obtain a value for $U_n(P, Q)$.  This leads me to my question:
Is there a way of computing the $n$th number of a Lucas Sequence of the first kind (given parameters $P$ and $Q$) directly, without calculating each prior value in the sequence?  A direct equation, if such a thing exists, could be computed in relatively trivial time.

A:
Is there a way of computing the $n$th number of a Lucas Sequence of
  the first kind (given parameters $P$ and $Q$) directly, without
  calculating each prior value in the sequence?

Yes (assuming $P^2 \ne 4Q$), but it's unlikely to give any computational advantage:
$$U_n(P,Q) = \frac{a^n - b^n}{a - b}$$
where
$$a = \frac{P+\sqrt{P^2 - 4Q}}{2}\\
b = \frac{P-\sqrt{P^2 - 4Q}}{2}.$$
(Koval's algorithm might be the fastest available.)


text:
Q: How to fade animate background images (full size) I'm looking for a script ! I want to do like the footer of this website ( animation between the background images where it's written '' Don't miss any update '')  : https://getgoldee.com/
Does anyone know a similar script or is able to get it from this website ?
Thank you for your answers !

A: This is how I would do it with a couple of jQ lines:

var $bg = $('#bg'),
    $bgDIV = $('div', $bg), // Cache  your elements
    n = $bgDIV.length,      // count them (used to loop with % reminder)
    c = 0;                  //  counter

(function loopBG(){
  $bgDIV.eq(++c%n).hide().appendTo($bg).fadeTo(3000,1, loopBG);
}());   // start fade animation
*{margin:0; padding:0;}

body{
  width:100%;
  height:100%;
}

#bg{
  position:absolute;
  top:0;
  width:100%;
  height:100%;
}
#bg:after{
  content:"";
  position:absolute;
  top:0; left:0;
  z-index:1;
  width:100%;
  height:100%;
  background:url(//i.stack.imgur.com/D0AZ1.png);
}
#bg > div{
  position:absolute;
  top:0;
  width:100%;
  height:100%;
  background: none 50%;
  background-size: cover;
}
#bg > #one{   background-image: url('//i.stack.imgur.com/T3U9b.png'); }
#bg > #two{   background-image: url('//i.stack.imgur.com/UKeA2.png'); }
#bg > #three{ background-image: url('//i.stack.imgur.com/hrArW.png'); }

A: If you analize its sources, the code handling this animation is in the file:
https://getgoldee.com/js/main.js
The code is quite simple:
var footerBgContainer = $('.footer-bgs');

function setFooterBackground(bgNumber) {
    var prev = footerBgContainer.find('.bg');

    setTimeout(function () {
        prev.remove();
    }, 4100);

    var el = document.createElement('div');
    el.className += 'bg bg' + bgNumber;

    footerBgContainer.append(el);

    setTimeout(function () {
        el.className += ' show';
    }, 20);
}

function footerBgRotating(interval) {
    var current = 1;

    setInterval(function () {
        setFooterBackground((current % 3) + 1);
        current++;
    }, interval);
}

footerBgRotating(4000);

As you can see, it changes CSS class with a timeout function.
Styles are: (animation is in CSS)
footer .bg {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
    opacity: 0;
    -webkit-transition: opacity 4s linear;
    -moz-transition: opacity 4s linear;
    -o-transition: opacity 4s linear;
    transition: opacity 4s linear
}

footer .bg.show {
    opacity: 1;
    -webkit-transition: opacity 4s linear;
    -moz-transition: opacity 4s linear;
    -o-transition: opacity 4s linear;
    transition: opacity 4s linear
}

footer .bg.bg1 {
    background: url("../img/footer-bg1.png") no-repeat;
    background-size: cover
}

footer .bg.bg2 {
    background: url("../img/footer-bg2.png") no-repeat;
    background-size: cover
}

footer .bg.bg3 {
    background: url("../img/footer-bg3.png") no-repeat;
    background-size: cover
}


text:
Q: Приложение для устройства на первую работу Доброго времени суток.
Ситуация такая, собираюсь устраиваться на junior .NET разработчика, это будет первая работа. Хочу написать какое-то осмысленное и более-менее полезное приложение (или даже два), выложить на гитхаб и добавить ссылку в резюме. Считаю, что это увелит шансы попасть на работу, т.к. работодатель увидит хоть какой-то реальный код, ну или как минимум увеличит шансы попасть на собеседование.
Собственно я хочу, чтобы вы предложили идею такого приложения, оно должно быть не очень сложным, уровня джуниора. Приложение будет десктопным, писаться будет на WinForms или WPF.
Сам вот пока ничего интересного не придумал, кроме банальных органайзеров или менеджеров задач ничего в голову пока не пришло.
Может вы посоветуете?
A: Если Вы можете сами спроектировать и разработать приложение, то это уже немножко выше junior'а.
Что можно посоветовать:

*

*Сортировщик картинок. Сортирует картинки на группы по определенным признакам (размер, формат, цветовая гамма), поиск дубликатов.

*Преобразователи текстов. Например, есть много старых книг/статей в текстовом формате с текстовой графикой. Этот текст анализируется и на выходе получается более-менее приличный pdf.

*Простой графический (векторный) редактор.

A: Сделайте какую-нибудь настольную игру, шашки там или шахматы. Или Го, модная штука же! Искусственный интеллект делать не надо, это сложно и не для джуниора. Пусть играют двое игроков. Можно и сеть прикрутить, кстати, в качестве продвинутой фичи.
Или например многосторонний чат-клиент (это уже непросто!).
A: Я считаю что ваше приложение должно уметь следующее
-показать работу с базовыми конструкциями и типа языка
-работать с СУБД (наверное использовать ORM без этого никуда)
-работа с сетью
-работа с XML
Из всего этого мне кажется что проще всего написать клиента к какому либо популярному веб-сервису или соц сети - получать сохранять и обрабатывать данные. Возможно какой то анализатор активности в Твитер или ВК. Полет фантазии большой но главное использовать в этом приложении мэйнстрим технологии.
A: Напишите, небольшой клиент для Вконтакта (например, получение списка друзей):

*

*покажете умение работать с WebAPI

*подключите к солюшену сторонние библиотеки с помощью NuGet

*добавьте логирование с помощью NLog (пакет NLog)

*сохраняйте данные в базе данных (SQL, SQLite, Mongo, etc) - покажите, что умете работать с БД

*сохраняйте настройки приложения в XML

В общем, огромный простор для показа (и закрепления) своих навыков.
A: Напиши небольшой чат(клиент-сервер).
В нем покажешь работу с сетью, многопоточность, разработка GUI, можно подключить работу с SQL.
A: Я в свое время писал геоинформационную систему на plain C - это сразу после окончания Универа.
Когда пересаживался на Java писал апплет-калькулятор.
A: Как вариант - игру тетрис, танчики, бота для браузерной игрушки - довольно интересно может быть.
A: *

*Клиент для hashcode.ru (с треем и оповещениями о новых темах)

*Скриншотер (для снятия скриншотов с экрана)

*игру "Жизнь" Конвея (она простенькая совсем)

Это то, что первое в голову пришло. Может потом дополню еще...


text:
Q: Json Array from PHP MySQL I am getting my json response from php file for my android app in this form
[{"countryname":"India","flag":"http:\/\/india.in\/india.png"}]

and I need it in this form, please suggest me some help.
{"countries":[{"countryname":"India","flag":"http:\/\/india.in\/india.png"}]}

A: You have your array in php, which you encode into json. Now you need to add another array-level around like this:
$country = array('countryname' -> 'India', ...);
$countries = array('countries' => $country );
echo json_encode($countries);

This is just my guess, because you didn't show any code.
Update
$sql=mysql_query("select * from t1 ORDER BY timestamp DESC");
while($row=mysql_fetch_assoc($sql)) {
    $output[]=$row;
}
// json_encode($output); doesn't do anything useful

$countries = array('countries' => $output);

echo json_encode($countries);


text:
Q: Spark combineByKey over reduceBykey using Java I have the below dataset:
    key   value
---------------------------
    key1,CLASS-A,YES,1
    key2,CLASS-B,YES,2
    key2,CLASS-B,YES,1
    key1,CLASS-A,YES,4
    key3,CLASS-C,DEFAULT,1

OUTPUT should look like:
    key   value
---------------------------
key1,    CLASS-A,YES,5
key2,    CLASS-B,YES,3
key3,    CLASS-C,NO,1

While using reduceByKey to obtain the result , i found that whenever there is a key with only one value , in this case key3, the reduceByKey is not called as there is nothing to reduce against.And I get :
   key   value
---------------------------
key1,    CLASS-A,YES,5
key2,    CLASS-B,YES,3
key3,    CLASS-C,DEAFULT,1

Can  I achieve this using combineByKey in Spark (Java) .
What I tried so far :
reduceByKey(
                    new Function2<String, String, String>() {

                        @Override
                        public String call(String s1, String s2) throws Exception {
                            String[] vals1 = StringUtils.split(s1, ",");
                            String[] vals2 = StringUtils.split(s2, ",");

                            String jobStat1 = vals1[0];
                            String jobStat2 = vals2[0];

                            String reducedJobStat;

                            boolean s1 = jobStat1.equals("YES")

                            boolean s2 = jobStat2.equals("YES");

                            if (s1 || s2) {

                                reducedJobStat = "YES";
                            } else {

                                reducedJobStat = "NO";
                            }

                            return reducedJobStat;
                        }
                    }
            )

A: the fundamental difference between reduceByKey and combineByKey in spark is that reduceByKey requires a function that takes a pair of values and returns a single value, whereas combineByKey allows for you to simultaneously transform your data and it requires three functions. The first is to create the new value type from the existing value type, the second adds an existing value type to a new value type, and the third adds to of the new value type.
The best example I have seen of combineByKey is at http://codingjunkie.net/spark-combine-by-key/
For your specific case, I'd recommend keeping it simple and using reduceByKey followed by mapValues to accomplish the desired transformation on key3. This might look something like:
reduced_rdd.mapValues(v => (v._1, if (v._2 == "DEFAULT") "NO" else v._2, v._3))

A: So , I got an alternate solution using combinerByKey. The code for reduceByKey looks simpler, but I am doing a mapValues after the reduceByKey(please look the question for reason) to get the result .
CombineByKey is fairly simple if we understand how it internally works .
Example using CombineByKey
Input :
key   value

key1,CLASS-A,YES,1
key2,CLASS-B,YES,2
key2,CLASS-B,YES,1
key1,CLASS-A,YES,4
key3,CLASS-C,DEFAULT,1

 //The CreateCombiner will initialise the 1st Key in the 1st partition . Here Lets divide the input into 2 partitions:

 Partition 1:                                            Partition 2:

     key        value                                key   value
 ---------------------------                 ---------------------------
     key1,  CLASS-A,YES,1                       key1,           CLASS-A,YES,4
     key2,  CLASS-B,YES,2                       key3,           CLASS-C,DEFAULT,1
     key2,  CLASS-B,YES,1

public class CreateCombiner implements Function<String, String> {

    @Override
    public String call(String value) {  //value here is "CLASS-A,YES,1"
        String jobStatus = value.split(",")[0];

        if (jobStatus.equals("YES")
                || jobStatus.equals("DEFAULT") {

            return "YES"+ " " + value.split(" ")[1] + " " + value.split(" ")[2];
        } else {
            return "NO" + " " + value.split(" ")[1] + " " + value.split(" ")[2];
        }

    }
}
 When the Key1 in 1st partition is encounterd, the CreateCombiner will initialise that key's. (key1 here)  value,In our case  we change the value(2nd string(YES/NO/DEFAULT)).
 Becase in my usecase I want to change all "DEFAULT" to "YES" .
 It replaces all the YES and DEFAULT strings to YES and otherwise to NO. Now Same for Key2 in the 1st partition .
 Again when it finds key2 in the 1st partition , the MergeValue class is called. It will merge the values . So here Key2 has 2 values(CLASS-B,YES,2 and CLASS-B,YES,1). It merges both.
 like (key2,CLASS-B,YES,3)

 The MergeCombiner  takes the combiners (tuples) created on each partition and merges them together. So in my case the logic is same as in MergeValue.

public class MergeValue implements Function2<String, String, String> {

    // MergeCombiner will decide the jobStatus and add the outCount and lbdCount.
    // This is a Merging function that takes a value and merges it into the previously collecte value(s).

    @Override
    public String call(String v1, String v2) throws Exception {

        String[] vals1 = StringUtils.split(v1, ",");
        String[] vals2 = StringUtils.split(v2, ",");

        String jobStat1 = vals1[0];
        String jobStat2 = vals2[0];

        String reducedJobStat;

        boolean stat1Process = (jobStat1.equals("YES"))
                || (jobStat1.equals("DEFAULT"));

          boolean stat2Process = (jobStat2.equals("YES"))
         || (jobStat2.equals("DEFAULT"));
        if (stat1Process || stat2Process) {

            reducedJobStat = "YES";
        } else {

            reducedJobStat = "NO";
        }

        int outCount = Integer.parseInt(vals1[1]) + Integer.parseInt(vals2[1]);

        int lbdCount = Integer.parseInt(vals1[2]) + Integer.parseInt(vals2[2]);
        return reducedJobStat + " " + Integer.toString(outCount) + " " + Integer.toString(lbdCount);

    }

}

public class MergeCombiner implements Function2<String, String, String> {

    // This fucntion combines the merged values together from MergeValue.
    // Basically this function takes the new values produced at the partition level and combines them until we end up
    // with one singular value.
    @Override
    public String call(String v1, String v2) throws Exception {

        String[] vals1 = StringUtils.split(v1, ",");
        String[] vals2 = StringUtils.split(v2, ",");

        String jobStat1 = vals1[0];
        String jobStat2 = vals2[0];

        String reducedJobStat;

        //Here we decide the jobStatus from 2 combiners , if both of them are complete ie jobStat1 and jobStat2 is COMP
        // LETE, then the Status is marked as complete.
        boolean stat1Process = (jobStat1.equals("YES");

        boolean stat2Process = (jobStat2.equals("YES");

        if (stat1Process || stat2Process) {

            reducedJobStat = "YES";
        } else {

            reducedJobStat = "YES";
        }

        int outCount = Integer.parseInt(vals1[1]) + Integer.parseInt(vals2[1]);

        int lbdCount = Integer.parseInt(vals1[2]) + Integer.parseInt(vals2[2]);

        return reducedJobStat + " " + Integer.toString(outCount) + " " + Integer.toString(lbdCount);

    }

Call to combineByKey
combineByKey(new CreateCombiner(), new MergeValue(), new MergeCombiner());

The same code Inmplemented using reduceByKey:
 reduceByKey(
                         new Function2<String, String, String>() {

                             @Override
                             public String call(String s1, String s2) throws Exception {
                                 String[] vals1 = StringUtils.split(s1, " ");
                                 String[] vals2 = StringUtils.split(s2, " ");

                                 String jobStat1 = vals1[0];
                                 String jobStat2 = vals2[0];

                                 String reducedJobStat;

                                 boolean stat1Process = (jobStat1.equals("YES")) ||
                                         (jobStat1.equals("DEFAULT");

                                 boolean stat2Process = (jobStat2.equals("YES")) ||
                                         (jobStat2.equals("DEFAULT");

                                 if (stat1Process || stat2Process) {

                                     reducedJobStat = "YES";
                                 } else {

                                     reducedJobStat = "NO";
                                 }

                                 int outCount = Integer.parseInt(vals1[1]) + Integer.parseInt(vals2[1]);

                                 int lbdCount = Integer.parseInt(vals1[2]) + Integer.parseInt(vals2[2]);

                                 return reducedJobStat + " " + Integer.toString(outCount) + " " + Integer.toString(lbdCount);
                             }
                         } ).mapValues(new Function<String, String>() {
                     @Override
                     public String call(String s) throws Exception {
                         String jobStatus = s.split(" ")[0];

                         if (jobStatus.equals("YES")
                                 || jobStatus.equals("DEFAULT") {

                             return "YES" + " " + s.split(" ")[1] + " " + s.split(" ")[2];
                         } else {
                             return "NO" + " " + s.split(" ")[1] + " " + s.split(" ")[2];

                         }

                     }
                 });


text:
Q: Apply a function with two dataframe as argument I'm looking the way to run function that take two dataframes as arguments df1 and df2.
What I want is to create a new column in df1 from the information in df2 without using a loop because my entire df1 is 3M rows and df2 700k rows.
For that I compare if the data the value of X of df1 is included in the from and the to of df2
I tried with apply of pandas library but I got errors like:

ValueError: Can only compare identically-labeled Series objects

Here is the sample of my code.
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'X':[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9,
                         2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9],
                    'Z':['F1','F2','F2','F1','F1','F2','F2','F1','F2','F2',
                         'F1','F1','F1','F1','F1','F1','F1','F1','F1','F1']})

df2 = pd.DataFrame({
           'from': [1.0, 1.5, 1.8, 2.2, 2.6],
           'to': [1.5, 1.8, 2.2, 2.6, 2.9],
           'Z': ['F1', 'F1', 'F2', 'F1', 'F2'],
           'Y': ['foo', 'bar', 'foobar', 'foo', 'zoo']
})
def asign(df1, df2):
    if df1['Z'] == df2['Z']:
        idx = np.where((df1[X] >= df2['from']) & (df1[X]<= df2['to']))[0]
        df1['Y'] = df2['Y'][idx]
        return df1

df1.groupby('Z').apply(asign, df2)

The output must be like:
>>> df1
out[0] :
    X    Z   Y
0   1.0  F1  foo
1   1.1  F2  bar
2   1.2  F2  foobar
3   1.3  F1  foo
4   1.4  F1  foobar
5   1.5  F2  bar
6   1.6  F1  foo
7   1.7  F2  bar

The value of the column Y to be created in df1 is conditioned by the fact that the row belongs to the group Z either F1 or F2 and that the value of X is greater or equal to from and less than to
Please can you help me to manage this?
Thank you

A: Better solution using pd.cut()
The old solution below works well, but it might not be very efficient as it first creates a large data frame and then selects a subset of rows from it. This solution instead creates bins using pd.cut and then merges the dataframes, directly creating the desired output.
In addition, this gives additional flexibility on how to make the merge.
df1 = pd.DataFrame({'X':[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9,
                         2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9],
                    'Z':['F1','F2','F2','F1','F1','F2','F2','F1','F2','F2',
                         'F1','F1','F1','F1','F1','F1','F1','F1','F1','F1']})

df2 = pd.DataFrame({
           'bmin': [1.0,   1.5,   1.8,      2.2,   2.6],
           'bmax': [1.5,   1.8,   2.2,      2.6,   2.9],
           'Z':    ['F1',  'F1',  'F2',     'F1',  'F2'],
           'Y':    ['foo', 'bar', 'foobar', 'foo', 'zoo']
})

# Adding new column to the dataframes
bins = sorted(df2.bmin.unique()) + [df2.bmax.max()]

df1.loc[:, 'bin'] = pd.cut(
    df1.X,
    bins=bins,
    labels=False,        # Makes cut return int indices for the bins
    include_lowest=True, # Otherwise 1.0 would be NaN
)
df2.loc[:, 'bin'] = pd.cut(
    0.5 * (df2.bmin + df2.bmax),
    bins=bins,
    labels=False,
    include_lowest=True,
)

# Merge on all relevant columns. Change how to 'inner' for an inner join
merged = pd.merge(df1, df2, on=["Z", "bin"], how='outer')

Sample of the output
      X   Z  bin  bmin  bmax       Y
0   1.0  F1    0   1.0   1.5     foo
1   1.3  F1    0   1.0   1.5     foo
2   1.4  F1    0   1.0   1.5     foo
3   1.1  F2    0   NaN   NaN     NaN
4   1.2  F2    0   NaN   NaN     NaN

Old solution using merge followed by query
Perhaps you'd be interested in DataFrame.query()?
In the code below, I use query on a merge of the dataframes on Z. Note that the output data from this code differs from the one you write, but I don't see how
1   1.1  F2  bar

could result from your input data since you want both the bin and Z to match? What I can see, there are no bins encapsulating 1.1 in df2 that also has Z=F2. Apologies if I didn't understand you question.
Note that I renamed the columns for the bin limits in df2 as you can't use Python keywords in numexpr query.
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'X':[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9,
                         2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9],
                    'Z':['F1','F2','F2','F1','F1','F2','F2','F1','F2','F2',
                         'F1','F1','F1','F1','F1','F1','F1','F1','F1','F1']})

df2 = pd.DataFrame({
           'bmin': [1.0,   1.5,   1.8,      2.2,   2.6],
           'bmax': [1.5,   1.8,   2.2,      2.6,   2.9],
           'Z':    ['F1',  'F1',  'F2',     'F1',  'F2'],
           'Y':    ['foo', 'bar', 'foobar', 'foo', 'zoo']
})

merged = pd.merge(
    df1,
    df2,
    on='Z',
)
merged = merged.query('bmin <= X < bmax')
merged = merged.sort_values(by="X")[['X', 'Z', 'Y']]

Gives the output
      X   Z       Y
0   1.0  F1     foo
3   1.3  F1     foo
6   1.4  F1     foo
10  1.7  F1     bar
50  1.8  F2  foobar
52  1.9  F2  foobar
20  2.2  F1     foo
23  2.3  F1     foo
26  2.4  F1     foo
29  2.5  F1     foo


text:
Q: iframe prevents iScroll scrolling on mobile Safari I am using iScroll on my mobile enable website (using iPhone here) to scroll inside a div.
In this this div, I have an iframe with a fixed height like this:

    Other stuff

Now, while scrolling within the div, everything works as expected but I cannot scroll when the scrolling gesture begins on the iframe.
The problem is described here pretty well: https://github.com/cubiq/iscroll/issues/41
So, I used the css workaround from that post by applying pointer-events:none to the iframe.
Now scrolling works perfectly but I cannot click any links which are defined within the iframe because all click/touch events on the iframe seems to be blocked due to pointer-events: none.
So, I thought:

"Ok, while the user scrolls, I need pointer-events:none. If he is
  not scrolling (and instead clicking), I must set pointer-events:auto
  in order to let the click/touch events pass."

So I did this:
CSS
#theIframe{pointer-events:none}

JavaScript
$("#theIframe").bind("touchstart", function(){
  // Enable click before click is triggered
  $(this).css("pointer-events", "auto");
});

$("#theIframe").bind("touchmove", function(){
  // Disable click/touch events while scrolling
  $(this).css("pointer-events", "none");
});

Even adding this doesn't work:
$("#theIframe").bind("touchend", function(){
  // Re-enable click/touch events after releasing
  $(this).css("pointer-events", "auto");
});

No matter what I do: Either scrolling doesn't work or clicking the link inside the iframe doesn't work.
Doesn't work. Any ideas?

A: I found the perfect solution. Works great on iOS and Android.
The basic idea is to put a div layer on top of that iframe. This way scrolling works smoothly.
If the user wants to tap/click on an element on that iframe I simply catch that click on the layer, save the x and y coordinates and trigger a click event on the iframe's content at these coordinates:
HTML:

Other stuff

CSS:
#layer{
    position:absolute;
    opacity:0;
    width:100%;
    height:100%;
    top:0;
    left:0;
    right:0;
    bottom:0;
    z-index:2
}

JavaScript:
$('#layer').click(function(event){
    var iframe = $('#theIframe').get(0);
    var iframeDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;

    // Find click position (coordinates)
    var x = event.offsetX;
    var y = event.offsetY;

    // Trigger click inside iframe
    var link = iframeDoc.elementFromPoint(x, y);
    var newEvent = iframeDoc.createEvent('HTMLEvents');
    newEvent.initEvent('click', true, true);
    link.dispatchEvent(newEvent);
});

A: I found a solution for this, it happens to be close to what other guys already mentioned on github but this may be useful for whoever wants to find a fast working resolution for this problem.
I'm assuming a few things, like there's only one iscroll container, here represented as ID. This is not properly tested and needs refactor. It's working in my project, but I changed it here slightly for the example but I guess you'll easily understand what you need to do:
var $iscroll = $('#iscroll');

document.addEventListener('touchstart', function(e) {

if ($iscroll.find('iframe').length > 0){

    $.each($iscroll.find('iframe'), function(k,v){

        var $parent = $(v).parent().first();

        if ($parent.find('.preventTouch').length == 0){

            $('

')
                .prependTo($parent);

        };

        $parent
            .css('position', 'relative').css('z-index', 1);

    });

    $iscroll.find('.preventTouch').on('click', function(e){
        e.preventDefault();
        e.stopPropagation();
        return false;
    });

};

};

document.addEventListener('touchend', function(e) {

if ($iscroll.find('iframe').length > 0){

    setTimeout(function(){

        var $iscroll = $('#iscroll');

        $iscroll.find('.preventTouch').remove();
        $iscroll.find('iframe').css('z-index', '');
        $iscroll.find('.preventTouch').off('click');

    }, 400);

};

};

Thanks for looking!


text:
Q: Sendgrid - Trigger email via webhook from non-zapier I've done quite a bit of research but can't seem to find an answer on this. Sendgrid has great documentation on event webhooks that send information after an email send, but very little on inbound webhooks that point towards sendgrid to send an email.
This is the only article I could find - but it's uniquely centered around Zapier which I'd rather not use.
Does anyone have any resources on how I could use webhooks that point towards Sendgrid to trigger emails without using Zapier?
Thanks!

A: Twilio SendGrid developer evangelist here.
When you want to trigger something on a third party service like SendGrid, it is described as an API request rather than as a webhook. To send an email using SendGrid you need to make an API request to the SendGrid API.
I see your username is Python Learner, here is a tutorial for how to send an email with Python using the SendGrid API.
The resultant code from the tutorial looks like this, but I recommend you take a look through the whole tutorial as there is lots to learn:
import sendgrid
import os
from sendgrid.helpers.mail import Mail, Email, To, Content

sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("test@example.com")  # Change to your verified sender
to_email = To("test@example.com")  # Change to your recipient
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, to_email, subject, content)

# Get a JSON-ready representation of the Mail object
mail_json = mail.get()

# Send an HTTP POST request to /mail/send
response = sg.client.mail.send.post(request_body=mail_json)
print(response.status_code)
print(response.headers)


text:
Q: Convert Login from Windows Authentication to SQL Server authentication? I have an account that is setup for Windows authentication. The account is used by SSRS for running reports and has various permissions in multiple databases. I need to convert this account to use SQL Server authentication.
I don't see a way to change it in SSMS. Is there a way to "flip a switch" and make it use SQL Server authentication?
For details as to why I want do this, see this question.

A: I think your best bet would be to script out the server level permissions granted to the Windows Login and save the SID, delete the Windows Login and recreate it as a SQL Login with the same SID, and finally grant the permissions back on the Login.
This way the login will have it's server level permissions recreated and retains it's database level permissions since the login will match the database user via SID.
    CREATE LOGIN [LoginName] WITH PASSWORD=N'PASSWORD'
            ,DEFAULT_DATABASE=[master]
            ,CHECK_EXPIRATION=OFF
            ,CHECK_POLICY=OFF
            ,SID=[SID]

A: There is no way to convert a windows login to sql server.
You can create a login with password and assign appropriate rights.


text:
Q: Adding new Registry entry throws permission error
I am sorry If I am repeating the same question found in many places on
  the net. Please do not tell "Google", I did many google search and
  stackoverflow search, found many solution. Nothing could help.

I am creating a Kiosk like Application in which I want to block user access to task manager. Through my reaserch on win32 api and googling I have come up with the following code.
        string user = Environment.UserDomainName + "\\" + Environment.UserName;
        RegistrySecurity rs = new RegistrySecurity();

        rs.AddAccessRule(new RegistryAccessRule(user,
            RegistryRights.FullControl,
            InheritanceFlags.None,
            PropagationFlags.None,
            AccessControlType.Allow));

        RegistryKey rk = null;

        try
        {
            rk = Registry.CurrentUser.CreateSubKey(
                @"Software\Microsoft\Windows\CurrentVersion\Policies\System",
                RegistryKeyPermissionCheck.Default, rs);

            rk.SetValue("DisableTaskMgr", 1);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        if (rk != null) rk.Close();

Still I am getting permission error.. I am on Windows 8 system. My Antivirus is also disabled. If I do registry edit by manually, it gives proper result.

Please help me to solve this.

A: That's a part of the registry that has restricted access. The access denied error that you see is reasonable and as expected.
Take a look at the permissions under regedit. Right click on the Policies node and select permissions. Note that standard users only have read access. You'd need to elevate to gain write access to that part of the registry.


text:
Q: What happens if void type function returns nothing? Let's say we have function like this
void test() {return;}

Is is it correct C code? I just tested it in mingw and compiler says nothing, the same for
void test() {return 1;}

So I guess I have really outdated compiler.
What should happen in given cases in both C/C++?
EDIT:
The return 1; gives me a warning. Does this mean return; is correct?

A: C++11(ISO/IEC 14882:2011) §6.6.3 The return statement

A return statement without an expression can be used only in functions that do not return a value, that is, a function with the return type void, a constructor, or a destructor. A return statement with an expression of non-void type can be used only in functions returning a value

C11(ISO/IEC 9899:201x) §6.8.6.4 The return statement

A return statement with an expression shall not appear in a function whose return type is void. A return statement without an expression shall only appear in a function whose return type is void.

However, C89/C90 only constraints on half of it:
C89/C90(ISO/IEC 9899:1990) §3.6.6.4 The return statement

A return statement with an expression shall not appear in a function whose return type is void .

In the C11 Forward section, it lists all the major changes in the third(i.e, C11) and second edition(i.e, C99). The last one of them is:

Major changes in the second edition included:
...
— return without expression not permitted in function that returns a value (and vice
versa)

This means that the constraint change of function return type is changed since C99.

A: Void returns nothing so its obvious compiler won't do anything. If you want to return a value you must define the type whether int ,pointer node etc. etc.

A: The return statement without an expression is the correct way to return from a function that returns void.
But, if you want to provide an expression in the return statement, then you should consider:
return (void)(expr);

Here, the expr is any expression that you want to include to have side-effects. As a suggestion, if you want to place a statement for its side-effect, then you should place it before the return statement as :
expr;
return;


text:
Q: How to let the user set a username during registration with Django social-auth? I use Django social-auth (omab version just to avoid any confusion with the other similarly named project) and right now I am trying it with Facebook. It is possible to register a new user and to login/logout without any issue. The only thing that I would like to add is a form during registration to let the user enter the desired username to be used on site because at the moment the username is either a facebook username (I do not want to force the user to use the same username) or a uuid if there is no facebook username (and that is ugly).
I am reading the docs, the pipelines and all that stuff but I'm not sure to understand, any hint or explanation would be welcome.

A: I found it in the example app that comes with social-auth https://github.com/omab/django-social-auth/tree/master/example/app. There is an example of the pipeline to use and even the form and views you need to implement. Very few to no changes are necessary to have a working implementation. At least some work needs to be done on the form at the time I write this because you can enter a username already taken.

A: The accepted answer links to an entire GitHub project without explaining anything about what parts of it are relevant, and some of it is outdated, so I'll try to share what I've learned.
django-social-auth is deprecated and the replacement is social-app-django, which integrates Django with the python-social-auth project.
The documentation on python-social-auth Pipelines is relevant. In the default pipeline, this is the stage that generates the username:
# Make up a username for this person, appends a random string at the end if
# there's any collision.
'social_core.pipeline.user.get_username',

The implementation of get_username shows the default behavior. We will have to copy these aspects:

*

*It ensures that the username it comes up with is unique, by checking storage.user.user_exists(username=...) and modifying the username until it is unique.

*It returns the dictionary {'username': '...'}, which is passed to the next stages in the pipeline.

To prompt the user, we need a custom "partial" pipeline stage. This lets us pause the pipeline to wait for the user to submit the username form and then resume it once we have the username.


text:
Q: Doctrine 2, serialization returning proxy class I'm using Silex and Doctrine to create an API, which makes use of Doctrine Associations. I'm using JMSSerializer to serialize entities.
All entities are returned as nice JSON objects except one, which has a ManyToOne association.
I find when this particular entity is serialized, it is actually the serialized Proxy class, including properties such as:
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true,

Why am I getting the proxy class in this case instead of the Entity? I've tried calling methods on the Objects in the application before serialization in an attempt to load the complete Entities, but I always seem to get the Proxy class.

A: My interim solution was to change the ManyToOne association to a ManyToMany and implement a ManyToOne constraint in the Model.
This is not elegant but it does seem to prevent the ORM from providing a proxy class and provide useful entities for both sides of the association when one is fetched.


text:
Q: react-redux connect with Formik - Maximum call stack size exceeded I get an infinite loop when i try to connect my form component to redux.
Would be funny if it wasn't frustrating because the code worked earlier today and now it doesn't after i reverted 1 commit.
Code was the same pretty much the same and connect()() worked and i had signUserUp function available as prop to work with. I removed node_modules and package-lock just in case and install all again and it's the same.
Signup.js
import { connect } from "react-redux";
import signupActions from "../modules/signup";

function Signup() {
  return <BasicForm />
}

const BasicForm = () => (
  <Formik
    initialValues={{ email: "", password: "", confirmPassword: "" }}
    validationSchema={signupSchema}
    onSubmit={(values, actions) => {
      console.log("form data: ", values);
    }}
    render={({ values, errors, touched, isSubmitting, handleChange, handleBlur, handleSubmit }) => (
      <Container>
        <Form onSubmit={handleSubmit}>
          <Form.Input
            type="text"
            placeholder="Email"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.email}
            name="email"
          />
          {errors.email && touched.email &&
{errors.email}
}

          <Form.Input
            type="password"
            placeholder="Password"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.password}
            name="password"
          />
          {errors.password && touched.password &&
{errors.password}
}

          <Form.Input
            type="password"
            placeholder="Confirm Password"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.confirmPassword}
            name="confirmPassword"
          />
          {errors.confirmPassword && touched.confirmPassword &&
{errors.confirmPassword}
}

          <Button primary type="submit" onSubmit={handleSubmit} disabled={isSubmitting}>
            Submit
          </Button>
        </Form>
      </Container>
    )}
  />
);

export default connect(
  null,
  signupActions
)(Signup);

i get the error here obviously when i add connect...
This is the single file module with redux stuff
signup.js
import api from '../utils/api';

const SIGN_UP = 'signup/SIGN_UP';

const initialState = {
  isAuthenticated: false,
  jwt: '',
  authError: '',
  formErrors: [],
};

export default (state = initialState, action = {}) => {
  switch (action.type) {
    case SIGN_UP:
      return { ...state, isAuthenticated: true, jwt: action.payload, authError: '', formErrors: [] };
    default:
      return state;
  }
};

export const signup = token => ({
  type: SIGN_UP,
  payload: token,
});

export const signUserUp = credentials => {
  return dispatch => api.post('auth/signup', credentials).then(token => dispatch(signup(token)));
};

In rootReducer.js i import that signupReducer like this
import signupReducer from './modules/signup';

export default combineReducers({
  signup: signupReducer,
});

here is the codesandbox example to see the errors at least when i try to visit sign up page.

A: The problem was how you were applying signupActions (which was default exported as the reducer and not an action creator) to connect.
Working example (which includes the notes below): https://codesandbox.io/s/4rook7ryv4

Notes:
Separate your containers from your components: https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
Separate your actions, reducers and types.
I've restructured your application to be easier to understand/read. I'd highly recommend that you use this flow and structure listed below (or, if you want to be more modular with your components/views, bundle everything related to that component/view together into a single folder -- this would be better if you're working within a large team).
├── build
|   ├── css
|   |   ├── main.[contenthash:8].css
|   |   └── main.[contenthash:8].css.map
|   ├── js
|   |   ├── main.[hash].js
|   |   └── main.[hash].js.map
|   ├── media
|   |   └── [hash].[ext]
|   └── favicon.ico
|   └── index.html
|
├── public
|   ├── favicon.ico
|   └── index.html
|
├── src
|   ├── actions
|   ├── components
|   ├── containers
|   ├── images
|   ├── reducers
|   ├── routes
|   ├── store
|   ├── styles
|   ├── tests
|   ├── types
|   ├── utils
|   ├── views
|   ├── index.js
|   ├── serviceWorker.js
|   └── setupTests.js
|
├── .eslintrc
├── .gitignore
├── README.md
├── package.lock.json
└── package.json