text:
Q: Package Errors. What Am I doing wrong? I'm trying to create a package that works out the number of days between two dates, I'm aware I have probably got this miles wrong, I am really struggling to troubleshoot this. My knownledge is low on oracle, I'm still quite new to this. The package I've written is below, but I am getting the error shown at the bottom.
How do I resolve this?
CREATE OR REPLACE PACKAGE PACKNAME
   AS
   FUNCTION TIME_SCALE RETURN NUMBER;
   END;
/
    CREATE OR REPLACE PACKAGE BODY PACKNAME
   AS   closed_date := '28-APR-14'
   FUNCTION TIME_SCALE RETURN NUMBER;
   IS BEGIN
   TRUNC(mrc.closed_date - mrc.open_date) AS days_difference FROM     TASKS mrc;
   END;

Error at line 2: PLS-00103: Encountered the symbol "=" when expecting one of the     following: constant exception <an identifier> <a double-quoted delimited-identifier> table     long double ref char time timestamp interval date binary national character nchar

I have substituted some of the names to make them clearer for you to read.
The function is to output the number of days it has taken for a task to be completed. The columns basically include the date_opened and date_closed in simple terms as well as a few others and a unique ID which I believe is a sequence.

A: Try this:
CREATE OR REPLACE PACKAGE PACKNAME
AS
  FUNCTION TIME_SCALE
    RETURN NUMBER;
END;
/
CREATE OR REPLACE PACKAGE BODY PACKNAME
AS
  closed_date VARCHAR2(50):= '28-APR-14';
  days_difference NUMBER;
FUNCTION TIME_SCALE
  RETURN NUMBER
IS
BEGIN
  SELECT TRUNC(mrc.closed_date - mrc.open_date) INTO days_difference
  FROM TASKS mrc;
  RETURN days_difference;
END;
END;

What was wrong:
1) You have missed the type for closed_date
2) You had an ';' after RETURN NUMBER in function declaration
3) You have missed SELECT clause inside function
4) You have missed END for the package


text:
Q: C++ API Wrapper in C for Java/JNA Object references I'm writing a C API wrapper for my own C++ library. I want to use the C-API with JNA in Java.
For each class in the C++ library I wrapped the constructors in C function calls, returning a handle. With this handle I can call C functions, which are wrapping the object's member functions (casting the handle to it's class and calling its member function).
This works fine.
To simplify the use of my API in Java, I wrote classes for all C++ classes. These Java classes only contain a JNA-Pointer (storing my objects handle) and the public member function of the C++ call. Each member function of the Java class calls the C function which is wrapping the C++ object's member function.
Now I'm facing a Problem:
When a C++ member function returns a reference to another C++ object, then my C-API returns the pointer. But how do I construct my Java objects out of this pointer? Is it legit to create a new Java Object and set its pointer value to the returned value. Although in Java are now 2 Objects, which holding the same pointer value.
Or should I have a List in Java, keeping track of all C++ objects, so I can get the returned reference from C++ out of this list.
When does the the Garbage Collector remove the JNA-Pointer objects from heap? And when gets my C++ object deleted?
(Some code to specify my answer)
In my C-API I have the following Function to create an Object
    int C_API_createFoo(void **handle) {
        try {
            *handle = reinterpret_cast<void*>(new Foo());
            return SUCCESS;
        } catch (std::exception &err) {
            std::cout << err.what() << std::endl;
            return ERROR;
        }
    }

In Java/JNA I load my C-lib and call the function with the following code:
    public Pointer createFoo(){
        PointerByReference pRef = new PointerByReference();
        int eC = MyClib.INSTANCE.C_API_createFoo(pRef);
        CHECK(eC);
        return pRef.getValue();
    }

Where Foo is:
    public class Foo{
    private Pointer handle;
    public Foo(){
            this.handle = createFoo();
        }
    public Foo(Pointer handle){
            this.handle = handle;
        }
    }

So now the class Foo stores the Object handle and can be used as a normal Java Object.
But suggest I have a C++ class for example FooWorker which has a member variable of Type Foo and has a getter Function for Foo:
    int C_API_FooWorker_getFoo(void* FooWorkerHandle, void** fooHandle) {
        try {
            FooWorker* fW= reinterpret_cast<FooWorker*>(FooWorkerHandle);
            Foo *foo = fW.getFoo();
            *fooHandle = reinterpret_cast<void*>(foo);
            return SUCCESS;
        } catch (std::exception &err) {
            std::cout << err.what() << std::endl;
            return ERROR;
        }
    }

Which is mapped in JNA like:
    public Foo FooWorker_getFoo(Pointer fooWorkerHandle){
        PointerByReference pRef = new PointerByReference();
        int eC = MyClib.INSTANCE.C_API_FooWorker_getFoo(fooWorkerHandle, pRef);
        CHECK(eC);
        return new Foo(pRef.getValue());
    }

So when I call the function FooWorker_getFoo(Pointer fooWorkerHandle) multiple times with the same value for fooWorkerHandle, than I will get multiple Java Objects of type Foo, but all containing the same value for their handle (i.e. the same C++ object reference).
Question
My Question is now: Is this save or will it cause any pain? And will all these Foo Objects (and in the end the one and only C++ Object, all the handles pointing to) be collected by the garbage collection?

A: The code as you've written it will not cause any problems, assuming that you have a native method for releasing the Foo object in C.
What your description seems to be missing is the difference between Java side memory and Native memory.  They are separately allocated and handled.  Some key points:

*

*calling new Foo() inside the C_API_createFoo() function allocates native side memory for that object.  You have not shown the code where that memory is released; or any guarantees on how long that object will last.  This is not something that happens automatically with Java, and you need to make sure the native API allows you to both persist and dispose of the object when you're done with it.

*

*You should probably have C methods corresponding to JNA mappings like dispose(PointerByReference pRef) (or similar) where you can pass the pointer to Foo to release that memory.  Some APIs auto-dispose based on a counter when the pointer is accessed and you may need something like keep(PointerByReference pRef) to increment that counter on the native side and make sure it doesn't release that memory too early.

*The objects you are creating on the Java side are just plain Java objects that will be garbage collected whenever there are no more references to them.

*

*In particular, if that object is a PointerByReference or Pointer inside your Java Foo object, it has the value of the native Pointer address, but it doesn't do anything special with that native address when it's GC'd, you have to intentionally do it.

*To "intentionally" release it (as with any native handle) and avoid handle leaks, I prefer try-with-resources or try-finally blocks.

You don't need to create a Java class just to encapsulate a Pointer.  You might prefer to extend the PointerType class (which does exactly that) which gives you a decorated Pointer, e.g.,
class FooHandle extends PointerType() {
}

Then you could change your createFoo() method to:
public FooHandle createFoo(){
    PointerByReference pRef = new PointerByReference();
    int eC = MyClib.INSTANCE.C_API_createFoo(pRef);
    CHECK(eC);
    // call code to make sure the native object is persisted
    return new FooHandle(pRef.getValue());
}

And as I mentioned you'd need a disposeFoo() method when you're done, to release the native side memory.
For the second example where you are just using a worker, you are not creating a new Foo() object on the native side, you're just calling a "get" method.  This implies you're just retrieving a copy of a pointer address, and you can get (pun intended) as many of them as you want, without any problems.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I prove that the cross product follows the right hand rule for vectors in the xz plane? Thanks to this wonderful article I have been able to prove that the cross product follows the right hand rule when the cross product has a non-zero z component. In this case we show that the z component is the same for the vectors and their projections onto the xy plane, and that this component is positive for positivily oriented vectors and negative for negatively oriented ones.
The article (in less detail) describes how to deal with cases where the vectors $u$ and  $v$ have the same ratio of $y$ to $x$. In this case the z component of the cross product would be equal to zero, and so we project the vectors onto the zy-plane instead, and calculate the x-component of the cross product in the same manner as above.
There is however one more case where the cross product has a z-component equal to zero - when the vectors $u$ and $v$ lack an y-component, and span the $xz$ plane. In this case the cross product will be limited to only a y component.
This time we won't have to project anything onto the $xz$ plane (the vectors are already there).
I try to apply the same reasoning as the article. If $u=(a_1, b_1, c_1)$ and $v=(a_2, b_2, c_2)$ then this would mean that
$v \times u=\begin{bmatrix}0c_2-c_1 0\\-(a_1 c_2-c_1 a_2)\\a_1 0-0a_2 \end{bmatrix}$
If we measure our angles from the positive x axis, and if we let $\alpha$ denote the angle for $u$ and $\beta$ the angle for $v$, we should be able to write this as:
$$c_1a_2-a_1c_2=|u|sin\alpha |v|cos \beta-|u|cos \alpha |v|sin \beta$$
According to the sine subtraction identity, we can write this as:
$$|u|sin\alpha |v|cos \beta-|u|cos \alpha |v|sin \beta = |u||v|sin(\alpha-\beta)$$
This is where things get confusing. In the other two cases we had to make the component of the cross product equal to $sin (\beta-\alpha)$, the minus sign switches things around I guess.
If $(u,v)$ are positively oriented there are two options, either $\alpha$ is smaller than $\beta$ (figure to the left) or vice versa (figure to the right). In both cases the $v$ must be less than 180 degrees conterclockwise from $u$.

(picture from article, all credit to Eric Thurschwell)
In the first case, $\alpha-\beta$ would give us the negative difference between $\beta$ and $\alpha$, which by definition must be less than 180 degrees. The sine of something a value between 0 and -180 must be negative, which gives us a negative y component.
In the second case, $\alpha-\beta$ would give us the positive difference between $\alpha$ and $\beta$, but since the vectors are positively oriented, it means this value must be greater that 180 degrees (and smaller than 360 degrees) by definition, making the sine of that value negative.
...Which would mean the cross product doesn't follow the right hand rule at all, or at least not for these kinds of vectors.
Would someone mind helping me out? I've been working on this for two weeks. This is the last thing I need to straighten out before I can move on to other topics...

A: To start with, you have transcribed the rule incorrectly.
In your source, the formula is given this way:
if $\mathbf a = \langle a_1,a_2,a_3\rangle$
and $\mathbf b = \langle b_1,b_2,b_3\rangle$,
their cross product is denoted $\mathbf a\times \mathbf b$
and defined analytically as the vector
$\langle a_2b_3 − a_3b_2, a_3b_1 − a_1b_3, a_1b_2 − a_2b_1\rangle.$
Transcribing this into your notation, that is,
$\mathbf a \to v,$ $\mathbf b \to u,$
$a_1 \to a_2,$ $a_2 \to b_2,$ $a_3 \to c_2,$
$b_1 \to a_1,$ $b_2 \to b_1,$ and $b_3 \to c_1$:
If $v=(a_2, b_2, c_2)$ and $u=(a_1, b_1, c_1),$ then
$$
v \times u
 = \begin{bmatrix} b_2 c_1 - c_2 b_1 \\
                   c_2 a_1 - a_2 c_1 \\
                   a_2 b_1 - b_2 a_1 \end{bmatrix} .
$$
You set the second coordinate to $a_2 c_1 - c_2 a_1,$ opposite the correct sign.
On the other hand I'm not sure you actually meant to write $v \times u$;
if you change the left-hand side of your equation to $u \times v$ then the right-hand side you wrote will be correct as it is.
The next thing that is problematic in your analysis is that if you look "down" at the $xz$ plane from a place far along the positive $y$ axis, the positive $z$ axis should be on the right and the positive $x$ axis on the left, that is, what you see should be this:

The convention I would expect to follow is that angles are measured counterclockwise from the $z$ axis in this view, as the figure above illustrates for the vector $u.$
By saying that $c_1 = \lvert u\vert \sin \alpha,$
in effect you have decided to measure your angles clockwise from the positive $x$ axis. Reversing rotation direction from counterclockwise to clockwise is equivalent to flipping the direction of the normal vector.
Note that
$\langle 1,0,0\rangle \times \langle 0,0,1\rangle = \langle 0,-1,0\rangle,$
that is, $\hat x \times \hat z = -\hat y.$
There are so many inadvertent sign changes in your analysis that I find it hard to count them. But there are apparently an odd number of them, because they don't all cancel out to give you the expected answer.

Now for a personal opinion about the linked article,
https://www.researchgate.net/publication/305759205_An_Even_Simpler_Proof_of_the_Right-Hand_Rule.
I find this article unsatisfying.
Setting aside the failure to give any guidance about handling two vectors in the $x,z$ plane, where is the argument that projecting both vectors onto a coordinate plane will preserve the right-hand rule?
Such an argument possibly could be made, but it would make this "proof" not nearly as simple as it claims to be.
If you want a proof that is as simple as the one claimed in the linked paper,
I think you will have to accept as given that the cross-product formula is correct up to possible reversals of the signs of the three resulting coordinates.
That is, we assume that the magnitude of each coordinate of the cross-product is correct in the given formula, and we merely need to show that the sign is correct for the right-hand rule rather than for the left-hand rule.
In order to show this for the $y$ axis, it is sufficient to take any two vectors such that these two vectors and the $y$ axis do not all lie in one plane and show that the resulting $y$ coordinate has the correct sign.
In particular, we can take the vectors $\hat x = \langle 1,0,0\rangle$
and $\hat z = \langle 0,0,1\rangle.$
The right-hand rule requires that $\hat z \times \hat x = \hat y.$
We see that the formula satisfies this requirement, so it is correct for the $y$ component of the cross product.


text:
Q: Job scheduler does not work on program exit My code is a kind of sloppy but I have this problem. I developed a time/day scheduler but the problem is when I close the window of the program and then I reopen it, it works only for the next two scheduled tasks and for the third it  does no longer work.
I mean if I choose to run code every one minute and the time is 9:11 and then I will close the window for some seconds and then I reopen it it will run at 9:12 and 9:13 but not in 9:14.

public partial class MainForm : Form
{
    public MainForm()
    {
        IFormatter formatter = new BinaryFormatter();
        Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
        Test t1 = (Test)formatter.Deserialize(stream);
        stream.Close();

        hourArray[0] = Convert.ToInt32(t1.hr);
        minutesArray[0] = Convert.ToInt32(t1.min);
        radioBoxArray[0] = Convert.ToBoolean(t1.radioBox1);
        radioBoxArray[1] = Convert.ToBoolean(t1.radioBox2);
        radioBoxArray[2] = Convert.ToBoolean(t1.radioBox3);
        radioBoxArray[3] = Convert.ToBoolean(t1.radioBox4);
        radioBoxArray[4] = Convert.ToBoolean(t1.radioBox5);
        radioBoxArray[5] = Convert.ToBoolean(t1.radioBox6);
        timeToCall = t1.StoreNextDate;

        InitializeComponent();

       button01_Click();
        // create reader & open file

        // TODO: Add constructor code after the InitializeComponent() call.
        //
    }//end constru

    CancellationTokenSource m_ctSource;

    private void button01_Click(object sender, EventArgs e)
    {

        hour = (int)numHours.Value;

        int minutes = (int)numMins.Value;

        //create next date which we need in order to run the code
        var dateNow = DateTime.Now;
        var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, hour, minutes, 0);

        var curDateValue = getCurrentDate(date, getScheduler());
        runCodeOnce(curDateValue, getScheduler());

        var nextDateValue = getNextDate(date, getScheduler());
        runCodeAt(nextDateValue, getScheduler());
        timeToCall = getNextDate(date, getScheduler());

        Test t2 = new Test();

        t2.hr = numHours.Value.ToString();
        t2.min = numMins.Value.ToString();
        t2.radioBox1 = radioButton1.Checked.ToString();
        t2.radioBox2 = radioButton2.Checked.ToString();
        t2.radioBox3 = radioButton3.Checked.ToString();
        t2.radioBox4 = radioButton4.Checked.ToString();
        t2.radioBox5 = radioButton5.Checked.ToString();
        t2.radioBox6 = radioButton6.Checked.ToString();
        t2.StoreNextDate = timeToCall;

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
        formatter.Serialize(stream, t2);
        stream.Close();

    }

    private void button01_Click()
    {

        hour = (int)numHours.Value;

        int minutes = (int)numMins.Value;

           //create next date which we need in order to run the code
        var dateNow = DateTime.Now;
        var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, hour, minutes, 0);

        var curDateValue = getCurrentDate(date, getScheduler());
        runCodeOnce(curDateValue, getScheduler());

        var nextDateValue = getNextDate(date, getScheduler());
        runCodeAt(nextDateValue, getScheduler());
        timeToCall = getNextDate(date, getScheduler());

        Test t2 = new Test();

        t2.hr = numHours.Value.ToString();
        t2.min = numMins.Value.ToString();
        t2.radioBox1 = radioButton1.Checked.ToString();
        t2.radioBox2 = radioButton2.Checked.ToString();
        t2.radioBox3 = radioButton3.Checked.ToString();
        t2.radioBox4 = radioButton4.Checked.ToString();
        t2.radioBox5 = radioButton5.Checked.ToString();
        t2.radioBox6 = radioButton6.Checked.ToString();
        t2.StoreNextDate = timeToCall;

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
        formatter.Serialize(stream, t2);
        stream.Close();

    }

 //   CancellationTokenSource m_ctSource;

    private void runCodeAt(DateTime date, Scheduler scheduler)
    {

        m_ctSource = new CancellationTokenSource();

        var dateNow = DateTime.Now;
        TimeSpan ts;

        if (date > dateNow)
            ts = date - dateNow;

        else
        {
            date = getNextDate(date, scheduler);
            ts = date - dateNow;
        }

        //enable the progressbar
        prepareControlForStart();

            try
            {
                TaskEx.Delay(ts).ContinueWith((x) =>
                {
                    //run the code at the time
                    methodToCall(date);
                    runCodeAt(getNextDate(date, scheduler), scheduler);
                }
                  , m_ctSource.Token);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }
    }

    private void methodToCall(DateTime time)
    {
        System.Diagnostics.Process.Start("cmd.exe", @"/c C:\Doit.bat");

        //setup next call
        var nextTimeToCall = getNextDate(time, getScheduler());
        timeToCall = nextTimeToCall;
        this.BeginInvoke((Action)(() =>
        {

                   Test t31 = new Test();

        t31.StoreNextDate = timeToCall;

        t31.hr = numHours.Value.ToString();
        t31.min = numMins.Value.ToString();
        t31.radioBox1 = radioButton1.Checked.ToString();
        t31.radioBox2 = radioButton2.Checked.ToString();
        t31.radioBox3 = radioButton3.Checked.ToString();
        t31.radioBox4 = radioButton4.Checked.ToString();
        t31.radioBox5 = radioButton5.Checked.ToString();
        t31.radioBox6 = radioButton6.Checked.ToString();
        t31.StoreNextDate = timeToCall;

        IFormatter formatter31 = new BinaryFormatter();
        Stream stream31 = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
        formatter31.Serialize(stream31, t31);
        stream31.Close();

        //MessageBox.Show(strText);
        }));

        //  System.Diagnostics.Process.Start("cmd.exe", @"/c C:\Doit.bat");
    }
}


text:
Q: Split intervals I have two tables. Each holds some attributes for a business entity and the date range for which those attributes were valid. I want to combine these tables into one, matching rows on the common business key and splitting the time ranges.
The real-world example is two source temporal tables feeding a type-2 dimension table in the data warehouse.
The entity can be present in neither, one or both of the source systems at any point in time. Once an entity is recorded in a source system the intervals are well-behaved - no gaps, duplicates or other monkey business. Membership in the sources can end at different dates.
The business rules state we only want to return intervals where the entity is present in both sources simultaneously.
What query will give this result?
This illustrates the situation:
Month          J     F     M     A     M     J     J
Source A:  <--><----------><----------><---->
Source B:            <----><----><----------------><-->

Result:              <----><----><----><---->

Sample Data
For simplicity I've used closed date intervals; likely any solution could be extended to half-open intervals with a little typing.
drop table if exists dbo.SourceA;
drop table if exists dbo.SourceB;
go

create table dbo.SourceA
(
    BusinessKey int,
    StartDate   date,
    EndDate     date,
    Attribute   char(9)
);

create table dbo.SourceB
(
    BusinessKey int,
    StartDate   date,
    EndDate     date,
    Attribute   char(9)
);
GO

insert dbo.SourceA(BusinessKey, StartDate, EndDate, Attribute)
values
    (1, '19990101', '19990113', 'black'),
    (1, '19990114', '19990313', 'red'),
    (1, '19990314', '19990513', 'blue'),
    (1, '19990514', '19990613', 'green'),
    (2, '20110714', '20110913', 'pink'),
    (2, '20110914', '20111113', 'white'),
    (2, '20111114', '20111213', 'gray');

insert dbo.SourceB(BusinessKey, StartDate, EndDate, Attribute)
values
    (1, '19990214', '19990313', 'left'),
    (1, '19990314', '19990413', 'right'),
    (1, '19990414', '19990713', 'centre'),
    (1, '19990714', '19990730', 'back'),
    (2, '20110814', '20110913', 'top'),
    (2, '20110914', '20111013', 'middle'),
    (2, '20111014', '20120113', 'bottom');

Desired output
BusinessKey StartDate   EndDate     a_Colour  b_Placement
----------- ----------  ----------  --------- -----------
1           1999-02-14  1999-03-13  red       left
1           1999-03-14  1999-04-13  blue      right
1           1999-04-14  1999-05-13  blue      centre
1           1999-05-14  1999-06-13  green     centre
2           2011-08-14  2011-09-13  pink      top
2           2011-09-14  2011-10-13  white     middle
2           2011-10-14  2011-11-13  white     bottom
2           2011-11-14  2011-12-13  gray      bottom

A: I may have misunderstood your question, but the results seem to be according to your question:
select a.businesskey
     -- greatest(a.startdate, b.startdate)
     , case when a.startdate > b.startdate
            then a.startdate
            else b.startdate
       end as startdate
     -- least(a.enddate, b.enddate)
     , case when a.enddate < b.enddate
            then a.enddate
            else b.enddate
       end as enddate
     , a.attribute as a_color
     , b.attribute as b_placement
from dbo.SourceA a
join dbo.SourceB b
        on a.businesskey = b.businesskey
       and (a.startdate between b.startdate and b.enddate
          or b.startdate between a.startdate and a.enddate)
order by 1,2

Since intervals need to overlap most of the work can be done with a join with that as the predicate. Then it's just a matter of choosing the intersection of the intervals.
LEAST and GREATEST seem to be missing as functions, so I used a case expression instead.
Fiddle

A: This solution deconstructs the source intervals to just their starting dates. By combining these two list a set of output interval start dates are obtained. From these the corresponding output end dates are calculated by a window function. As the final output interval must end when either of the two input intervals end there is special processing to determine this value.
;with Dates as
(
    select BusinessKey, StartDate
    from dbo.SourceA

    union

    select BusinessKey, StartDate
    from dbo.SourceB

    union

    select x.BusinessKey, DATEADD(DAY, 1, MIN(x.EndDate))
    from
    (
        select BusinessKey, EndDate = MAX(EndDate)
        from dbo.SourceA
        group by BusinessKey

        union all

        select BusinessKey, EndDate = MAX(EndDate)
        from dbo.SourceB
        group by BusinessKey
    ) as x
    group by x.BusinessKey
),
Intervals as
(
    select
        dt.BusinessKey,
        dt.StartDate,
        EndDate = lead (DATEADD(DAY, -1, dt.StartDate), 1)
                  over (partition by dt.BusinessKey order by dt.StartDate)
    from Dates as dt
)
select
    i.BusinessKey,
    i.StartDate,
    i.EndDate,
    a_Colour = a.Attribute,
    b_Placement = b.Attribute
from Intervals as i
inner join dbo.SourceA as a
    on i.BusinessKey = a.BusinessKey
    and i.StartDate between a.StartDate and a.EndDate
inner join dbo.SourceB as b
    on i.BusinessKey = b.BusinessKey
    and i.StartDate between b.StartDate and b.EndDate
where i.EndDate is not NULL
order by
    i.BusinessKey,
    i.StartDate;

The "Dates" CTE uses UNION rather than UNION ALL to eliminate duplicates. If both sources change on the same date we want only one corresponding output row.
As we want to close output when either source closes the third query in "Dates" adds the earliest end date i.e. the MIN of the MAX of EndDates. As it is an EndDate masquerading as a StartDate it must have another day added to it. It's purpose is to allow the window function to calculate the end of the preceding interval. It will be eliminated in the final predicate.
Using inner joins for the final query eliminates those source intervals for which there is no corresponding value in the other source.

A: There are a lot of interesting solutions to this problem (stated in different terms) here and its preceding pages. There it is presented as matching supply and demand in an auction. The units supplied/demanded is directly analogous to the days in an interval from this question so the solution translates. I've left it in the terms used in the linked site, though.
Sample data.
DROP TABLE IF EXISTS dbo.Auctions;

CREATE TABLE dbo.Auctions
(
  ID INT NOT NULL IDENTITY(1, 1)
    CONSTRAINT pk_Auctions PRIMARY KEY CLUSTERED,
  Code CHAR(1) NOT NULL
    CONSTRAINT ck_Auctions_Code CHECK (Code = 'D' OR Code = 'S'),
  Quantity DECIMAL(19, 6) NOT NULL
    CONSTRAINT ck_Auctions_Quantity CHECK (Quantity > 0)
);

SET NOCOUNT ON;

DELETE FROM dbo.Auctions;

SET IDENTITY_INSERT dbo.Auctions ON;

INSERT INTO dbo.Auctions(ID, Code, Quantity) VALUES
  (1, 'D', 5.0),
  (2, 'D', 3.0),
  (3, 'D', 8.0),
  (5, 'D', 2.0),
  (6, 'D', 8.0),
  (7, 'D', 4.0),
  (8, 'D', 2.0),
  (1000, 'S', 8.0),
  (2000, 'S', 6.0),
  (3000, 'S', 2.0),
  (4000, 'S', 2.0),
  (5000, 'S', 4.0),
  (6000, 'S', 3.0),
  (7000, 'S', 2.0);

The solutions expounded reduce the elapsed time for his 400k row sample data from a naive 11 seconds to 0.4s. The fastest is by Paul White (of this parish), shown here.
DROP TABLE IF EXISTS #MyPairings;

CREATE TABLE #MyPairings
(
  DemandID integer NOT NULL,
  SupplyID integer NOT NULL,
  TradeQuantity decimal(19, 6) NOT NULL
);
GO

INSERT #MyPairings
    WITH (TABLOCK)
(
    DemandID,
    SupplyID,
    TradeQuantity
)
SELECT
    Q3.DemandID,
    Q3.SupplyID,
    Q3.TradeQuantity
FROM
(
    SELECT
        Q2.DemandID,
        Q2.SupplyID,
        TradeQuantity =
            -- Interval overlap
            CASE
                WHEN Q2.Code = 'S' THEN
                    CASE
                        WHEN Q2.CumDemand >= Q2.IntEnd THEN Q2.IntLength
                        WHEN Q2.CumDemand > Q2.IntStart THEN Q2.CumDemand - Q2.IntStart
                        ELSE 0.0
                    END
                WHEN Q2.Code = 'D' THEN
                    CASE
                        WHEN Q2.CumSupply >= Q2.IntEnd THEN Q2.IntLength
                        WHEN Q2.CumSupply > Q2.IntStart THEN Q2.CumSupply - Q2.IntStart
                        ELSE 0.0
                    END
            END
    FROM
    (
        SELECT
            Q1.Code,
            Q1.IntStart,
            Q1.IntEnd,
            Q1.IntLength,
            DemandID = MAX(IIF(Q1.Code = 'D', Q1.ID, 0)) OVER (
                    ORDER BY Q1.IntStart, Q1.ID
                    ROWS UNBOUNDED PRECEDING),
            SupplyID = MAX(IIF(Q1.Code = 'S', Q1.ID, 0)) OVER (
                    ORDER BY Q1.IntStart, Q1.ID
                    ROWS UNBOUNDED PRECEDING),
            CumSupply = SUM(IIF(Q1.Code = 'S', Q1.IntLength, 0)) OVER (
                    ORDER BY Q1.IntStart, Q1.ID
                    ROWS UNBOUNDED PRECEDING),
            CumDemand = SUM(IIF(Q1.Code = 'D', Q1.IntLength, 0)) OVER (
                    ORDER BY Q1.IntStart, Q1.ID
                    ROWS UNBOUNDED PRECEDING)
        FROM
        (
            -- Demand intervals
            SELECT
                A.ID,
                A.Code,
                IntStart = SUM(A.Quantity) OVER (
                    ORDER BY A.ID
                    ROWS UNBOUNDED PRECEDING) - A.Quantity,
                IntEnd = SUM(A.Quantity) OVER (
                    ORDER BY A.ID
                    ROWS UNBOUNDED PRECEDING),
                IntLength = A.Quantity
            FROM dbo.Auctions AS A
            WHERE
                A.Code = 'D'

            UNION ALL

            -- Supply intervals
            SELECT
                A.ID,
                A.Code,
                IntStart = SUM(A.Quantity) OVER (
                    ORDER BY A.ID
                    ROWS UNBOUNDED PRECEDING) - A.Quantity,
                IntEnd = SUM(A.Quantity) OVER (
                    ORDER BY A.ID
                    ROWS UNBOUNDED PRECEDING),
                IntLength = A.Quantity
            FROM dbo.Auctions AS A
            WHERE
                A.Code = 'S'
        ) AS Q1
    ) AS Q2
) AS Q3
WHERE
    Q3.TradeQuantity > 0;


text:
Q: How to fix XSS vulnerabilities on javascript? 1) I get response with html tags, for instance: This is Test
2) sometimes response may containt script (or iframe, canvas and etc.) tags (XSS), for instance: This  is Test
3) how can remove all of XSS tags (script, iframe, canvas...) except of other html tags?
PS: I can't use escape because it's remove ,  and other tags.

A:
how can remove all of XSS tags (script, iframe, canvas...) except of other html tags?

All tags can harbour XSS risks. For example ,  or .
To render HTML 'safe' you need to filter it to only allow a minimal set of known-safe elements and attributes. All URL attributes need further checking for known-good protocols. This is known as 'whitelisting'.
It's not a simple task, as you will typically have to parse the HTML properly to detect which elements and attributes are present. A simple regex will not be enough to pick up the range of potentially-troublesome content, especially in JavaScript which has a relatively limited regex engine (no lookbehind, unreliable lookahead, etc).
There are tools for server-side languages that will do this for you, for example PHP's HTML Purifier. I would recommend using one of those at the server-side before returning the content, as I'm currently unaware of a good library of this kind for JavaScript.

A: Below function could be used to encode input data to fix XSS vulnerabilities on javascript
/*Using jQuery : the script to escape HTML/JS characters*/
function htmlEncode(value) {
     if (value) {
         return $('
').text(value).html();
     } else {
         return '';
     }
 }

A: You don't need to remove the tags, just do the translations.
For example, turn < to <, > to > etc..
If you are using php, some function are for this:
htmlspecialchars
htmlentities


text:
Q: Book recommendation - Parallel programming for C# .NET 4.0 I'm looking for a book which contains information about the following topics:

*

*Thread synchronization methods

*Parallel Extension

*Asynchronouse programming (Invoke, BeginInvoke, BackgroundWorker, Threads, ...)

I've already knowledge about these topics but I'll refresh all these in deep and with focus on C#.
The book recommendations should be for C# / .NET 4.0 (not Java) and in English or German.
Thank you guys.
Danny

A: I think Parallel Programming wiht .NET is exactly what you're looking for.

*

*You can read it online in the MSDN library but it is also available as hardcopy.

*It has a plenty of samples (that can be reused easily) in C#, VB and F#.

*To read more about the F# versions, you can read my blog post series

A: Even though it is not specific to parallel programming, C# in a nutshell 4 is a decent reference to understand these concepts

A: Another nice document comes from Microsoft:

*

*Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4

A: C# 4.0 in a nutshell by o reilly publications
http://www.amazon.com/C-4-0-Nutshell-Definitive-Reference/dp/0596800959/ref=sr_1_1?ie=UTF8&qid=1298027628&sr=8-1


text:
Q: Fire fbq event with user_data In FB doc, it is explained how to bind user_data to fbq while initializing fbq. However it is not explained how to bind user_data later on.
Let's say I have a form where users put their email. When the user hit "send" I call fbq("trackCustom", "my_event"), is there a way to make FB know customer's email so it can performed advanced matching?
I was thinking of maybe this:
fbq("trackCustom", "my_event", {user_data: {em: hash256("email")}})

Or this
fbq("setUserData", {em: hash256("email")});
fbq("trackCustom", "my_event");

But no way to find the right answer on Google.


text:
Q: Why am I receiving ReferrenceError: BinaryFile is not Defined I'm following the result in this answer exactly but I am receiving the following error:

ReferenceError: BinaryFile is not defined

Here's the code where that is used:
fr.onloadend = function() {
            console.log(this);
            exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));
        }

The console.log shows that there is data there, I just don't understand this error I'm receiving.
Thank you for your help.

A: I used the following which worked very well
EXIF.getData(img, function() {
    orientation = EXIF.getTag(this, "Orientation");
});

where img is my image object.
Also EXIF.pretty(this) was helpful to see what data is in each image.

A: Removing BinaryFile and changing how FileReader read the file (readAsArrayBuffer) worked for me.
fileReader.onload = function (event) {

    var exif = fileReader.readFromBinaryFile(this.result);

    console.log(exif);

};

fileReader.readAsArrayBuffer(file);


text:
Q: Keeping track of the last time a user took an action I have an app which allows users to redeem voucher codes, however I want to limit it so they can only claim one every 30 minutes.
So I somehow need to store the time they last redeemed a voucher, and if they try to redeem another, the app would check the last time and only give them a new voucher if the last one was over half an hour ago.
Would I store data in user prefs or is there a better way?

A: Storing a timestamp of when the last voucher was redeemed in NSUserDefaults is probably fine for a simple solution.
But how secure do you need this to be? As a general rule, and especially if this needs to be strictly enforced for financial reasons, never trust the client.  Meaning that you should have a server to verify the codes, and enforce usage restrictions.


text:
Q: Error ORA-01841: when passing date of birth in a file I am passing "19851003" as date of birth in a file but i am getting the following error in the log file.
ORA-01841: (full) year must be between -4713 and +9999, and not be 0

Any idea why is the error coming as i am passing it as a string only
Error in Log File :
error processing column DATE_OF_BIRTH in row 2 for datafile /xfer/x/directory/filename.csv
ORA-01841: (full) year must be between -4713 and +9999, and not be 0

My table code:
CREATE TABLE table_name
(
  ID                  VARCHAR2(10 BYTE),
  FIRST_NAME          VARCHAR2(150 BYTE),
  LAST_NAME           VARCHAR2(150 BYTE),
  MIDDLE_NAME         VARCHAR2(150 BYTE),
  DATE_OF_BIRTH       DATE
)

ORGANIZATION EXTERNAL
( TYPE ORACLE_LOADER
  DEFAULT DIRECTORY DIRECTORY_TABLES
  ACCESS PARAMETERS
  (RECORDS  DELIMITED BY '\n'
   SKIP 1
   BADFILE  DIRECTORY_TABLES:'filelist.bad'
   LOGFILE  DIRECTORY_TABLES:'filelist.log'
   DISCARDFILE   DIRECTORY_TABLES:'filelist.dsc'
   FIELDS TERMINATED BY ','
   OPTIONALLY ENCLOSED BY '"'
   MISSING FIELD VALUES ARE NULL
   REJECT ROWS WITH ALL NULL FIELDS
   (ID                  ,
    FIRST_NAME          ,
    LAST_NAME           ,
    MIDDLE_NAME         ,
    DATE_OF_BIRTH       DATE "YYYYMMDD"
   )
)
LOCATION (DIRECTORY_TABLES:'filename.csv')
)
REJECT LIMIT 0
NOPARALLEL
NOMONITORING;

MY CSV File :
"id","First Name","Last Name","MI","DOB"
"2","Felicia","Brown","M","19810209"
"3","Jose","Romero","M","19890706"
"4","Valerie","Moore","","19621112"

A: In the spec for DATE_OF_BIRTH a date-format-spec is required. Try:
DATE_OF_BIRTH  CHAR DATE_FORMAT DATE MASK "YYYYMMDD"

Reference here and then search for "date_format_spec"
Share and enjoy.

A: 19851003 is not between -4713 and 9999 just like the error says.
I suspect you want to pass 1985 as the year and you are accidentally passing a full date (yyyyMmdd)


text:
Q: copy assets to documents directory I am using the ctAssetPickerController for Picking videos and images. After the user has finished picking videos and images I want to copy them to another folder. I am using the export session and requestAvAssetForVideo method but the problem is it copies only one file at a time and I am not able to get the name of the file that the user is selecting, and it is copying videos only. How do I copy the images also? Below is my code.
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{

        PHImageManager *manager = [PHImageManager defaultManager];

    [manager requestAVAssetForVideo:obj options:PHVideoRequestOptionsDeliveryModeAutomatic resultHandler:^(AVAsset * asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
        NSString *imageName = @"img_o462.mp4";
        NSString *selectedFilesCopyPath = [[self getRootFolderPath] stringByAppendingString:@"/Photos"];

        if (![[NSFileManager defaultManager]fileExistsAtPath:selectedFilesCopyPath]) {
            [[NSFileManager defaultManager]createDirectoryAtPath:selectedFilesCopyPath withIntermediateDirectories:NO attributes:nil error:nil];
        }

        NSString *copyPath = [selectedFilesCopyPath stringByAppendingString:[NSString stringWithFormat:@"/%@",imageName]];
        //            NSError *copyError= nil;

        exporter.outputURL = [NSURL fileURLWithPath:copyPath];
        exporter.outputFileType = AVFileTypeMPEG4;

        [exporter exportAsynchronouslyWithCompletionHandler:^{
            // here your file will be saved into file system at specified exportUrl
            NSLog(@"file copied");

            if (exporter.status == AVAssetExportSessionStatusCompleted) {
                NSLog(@"success");
                [self showErrorAlert:@"Success"];
            } else {
                NSLog(@"error: %@", [exporter error]);
                [self showErrorAlert:exporter.error];
            }
        }];

    }];
}


text:
Q: Using of typedef struct I want to know if there is any difference in performance, declaration, etc.
I have a file that called features.h,
and it has a struct definition:
typedef struct feat_record
{
 ...
 ...
} Feature;

i want to use it in another file in a method, in the other file .h file I include features.h.
And my question is, if there is a difference between declaring the method in the other file .h like this:
void myMethod(Feature *f);

or like this:
void myMethod (struct feat_record *f);

Thanks

A: This is only coding style and there is no other difference than subjective, personal preference.
The typedef version is often encouraged for programs that are in the borderland between C and C++, since it makes the style consistent with C++ types (in C++ the struct keyword is superfluous when declaring objects of a struct).
The struct tag version is mainly encouraged by the Linux camp and enforced by the Linux kernel code style guide (which does not provide much of a rationale beyond subjective opinions).
There is no obvious right or wrong, just pick the style you like and stick to it consistently.

A: The difference is that the typedef declaration of Feature (which may or may not include the definition of feat_record) must precede the function declaration using it, whereas
void myMethod (struct feat_record *f);

stands on its own as an interface declaration; it does not depend on a preceding typedef or other declaration.
Nevertheless, it is better to declare struct feat_record; first, if only to silence an inevitable compiler warning. And such a declaration is required before the function declaration in the file that implements myMethod.
Ultimately, the difference is style, namely verboseness: you should decide whether you want to refer to all structs as struct in your program. It means more typing, but serves as a reminder to initialize things. (Or, if you prefer, a metadata tag for things that must be handled as a struct.)
As for the compiled program, there is no conceivable difference.


text:
Q: What's the meaning of this error message "insertId: Error: INVALID_ACCESS_ERR: DOM Exception 15"? I'm developing an app using jquery mobile, phonegap and openDatabase. When the app is executed, I can see in the console of Safari browser the SQLResultSet with this message:
insertId: Error: INVALID_ACCESS_ERR: DOM Exception 15.

However, my app is working ok. But I don't understand why that message is shown.
Please, help me.

A: I had this and it was driving me completely crazy.
What happens is that, if the operation is not an INSERT statement, the insertId is nullified, since no rows have been inserted, but instead of just showing 0 it gives a cryptic DOM error.
You simply have to ignore it and concentrate on the rows.
The big question is why the hell have it in the first place, why not just have a sqlInsertResultSet and a sqlRetrieveResultSet and stop messing with our minds :(

A: On my side following gave the mentioned error:
results.rows[0].x

and this worked:
results.rows.item(0).x

A: It means that no row was inserted by a transaction, by that it's more  an information than an error.
If an INSERT-statement wasn't successfull or an transaction wasn't an INSERT at all, the insertId-property of the resultSet contains this message instead of the ID of the last inserted row.
http://docs.phonegap.com/phonegap_storage_storage.md.html#SQLResultSet


text:
Q: Why doesn't PHP read this array and show an error? maybe someone can explain to me what's wrong here? Why doesn't PHP read this array, and shows an error instead?

Warning: Undefined array key "ref" in ... on line 70

Line 70 is:
$ref = $_GET["ref"];

I want to take a variable from this input
<input type="text" name="ref" id="log"/>


text:
Q: How to get 2 data sources to merge in SSIS? I am fairly new to SSIS. I came across a situation where i have to use a data flow task. The data source is MS- SQL server 2008 and destination is Sharepoint list. I gave an SQl query for Data source object as
SELECT     Customer_ID, Project_ID, Project_Name, Project_Manager_ID, Project_Manager_Name, DeliveryManager1_ID, DM1NAME FROM dbo.LifeScience_Project
WHERE (Customer_ID IN ('1200532', '1200632', '1207916', '1212121', '1217793', '1219351', '1219417', '1219776'))

Now, this is the problem. The customer ids in where clause need to come from a different data source. That would make it look like something as
SELECT     Customer_ID, Project_ID, Project_Name, Project_Manager_ID, Project_Manager_Name, DeliveryManager1_ID, DM1NAME FROM dbo.LifeScience_Project
WHERE Customer_ID IN (select customer_id from [Database2].Customer_Master)

Please guide me to implement this.

A: I would run one query in an execute sql task in which build you a list of customer Id's and store the result in a variable:-
Declare @s varchar(max)
Set @s =''
SELECT @s = @s + '''' + Cast(customer_id as varchar(20)) + ''','
FROM (select customer_id from [Database2].Customer_Master ) As T
Select @s
Then in your dataflow task, the source query would be parameterized, using the variable from the first part.
SELECT     Customer_ID, Project_ID, Project_Name, Project_Manager_ID, Project_Manager_Name, DeliveryManager1_ID, DM1NAME FROM dbo.LifeScience_Project
WHERE (Customer_ID IN (?))

A: You would have to use a Lookup Component within your data flow task. So for example, write your first query within an OLEDB Component by chosing SQL Command from the Data Access Mode just pulling everything, i.e.,
SELECT     Customer_ID, Project_ID, Project_Name, Project_Manager_ID, Project_Manager_Name, DeliveryManager1_ID, DM1NAME
FROM dbo.LifeScience_Project
Then connect this source to a Lookup Component and within the Lookup component, instead of choosing a lookup table, select the SQL option and type your second query in there:
select customer_id
from [Database2].Customer_Master
Now do a lookup matching the two Customer_ID fields and only direct output on successful matches. If there are specific ID's you want you can add that to the second query like so:
select customer_id
from [Database2].Customer_Master
WHERE customer_id IN('someid', 'someid2',...)
That's how I would do it.
EDIT:
In response to Sushant's additional questions for clarification.
(1) You want to use the MATCH output when directing your rows NOT NO MATCH.
(2) Yes that is correct, make sure for your data source it points to the other database (Non-SQL2008 one).
(3) In columns Tab you simply match Customer_ID to Customer_ID;
(4) In Advanced tab you don't need to do anything. In the Error tab you can choose to Ignore errors since you don;t care about the non-matches.
(5) Yes that is the correct flow - the prompt when connecting to Sharepoint is asking if you want to redirect the MATCHED output from the Lookup or the UNMATCHED output. You want to choose the MATCHED output as I mentioned in point (1).


text:
Q: Curves of genus 0 over a DVR determined by fibers? Closely related is this question.
Suppose $R$ is a DVR with fraction field $K$ and residue field $k$ (say finite), and $S = \mathrm{Spec}(R)$.
I am interested in regular, proper, flat schemes $X \to S$ where the generic fiber $X_K$ is a curve of genus zero. In many ways these are simple objects, but I've been unable to find good answers or references, one reason being that positive genus is often assumed.
My main questions are: given such $X, X'$

*

*Does isomorphic special fibers $X_k \cong X_k'$ imply $S$-isomorphism $X \cong X'$?

*Is there always some $Y$ with maps to each ($X\leftarrow Y \to X'$), or is the category connected?

I'm interested in the answers in general, but especially when one or more of these conditions hold:

*

*$X_K \cong \mathbb{P}^1_K$ (there is a rational point)

*$R = \mathbb{Z}_p \text{  or  } \mathbb{F}_p[[t]]$

*$X_k$ is a normal crossings divisor

*$X \to S$ is smooth

Any references would be very much appreciated as well. My first though was Qing Liu's book, but I haven't found my answers there.
Thank you.
[Edit: added regularity assumption]


text:
Q: Flask login without database I need to implement a simple login functionality to one of the applications that I a working on using flask-login. The authentication checking is hardcoded if condition and it is validating whether username password equals to a string given. The code is like the following:
@auth_bp.route('/login', methods=["POST"])
def loginHandler():
    username = request.form.get('username')
    password = request.form.get('password')

    if username != 'admin' and password != 'Admin@123':
        flash('Please check your login details and try again.')
        return redirect(url_for('auth_bp.show_login'))

    login_user(username, False)
    # if the above check passes, then we know the user has the right credentials
    return redirect(url_for('migration_bp.list'))

and in app.py file, I have the following code:
from flask import Flask
from flask_login import LoginManager, login_manager
from auth.auth import auth_bp
from environments.environments import environments_bp
from migration.migration import migration_bp
from logs.logs import logs_bp

UPLOAD_FOLDER = 'static/uploads'

@login_manager.user_loader
def user_loader():
    # since the user_id is just the primary key of our user table, use it in the query for the user
    return 1

def create_app():

    app = Flask(__name__)

    login_manager_copy = LoginManager()
    login_manager_copy.login_view = 'auth.login'
    login_manager_copy.init_app(app)

    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(environments_bp, url_prefix='/environments')
    app.register_blueprint(migration_bp, url_prefix='/migration')
    app.register_blueprint(logs_bp, url_prefix='/logs')

    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

    return app

if __name__ == '__main__':
    create_app().run(debug=True)

But this is showing an error as follows:
AttributeError: module 'flask_login.login_manager' has no attribute 'user_loader'

As I don't need database, I think the User modal given in the examples are not needed. But it is giving errors without it. How can I fix this ?
EDIT:
As per the suggestion below, I have added a User class as shown below:
from flask_login import UserMixin, LoginManager, login_manager

class User(UserMixin):

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return int(self.id)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.powerlevel}')"

and added following code to app.py file:
@login_manager.user_loader
    def load_user(user_id):
        # since the user_id is just the primary key of our user table, use it in the query for the user
        return User.query.get(int(user_id))

But it is still showing the same error.

A: app.py you will have this:
from flask_login import UserMixin, login_user, LoginManager, login_required, current_user, logout_user

app = Flask(__name__)

login_manager = LoginManager()
login_manager.init_app(app) #defined above app=Flask(__name__)
login_manager.login_view = 'login' #logged out users will be redirected to this route if attempting to view a route that requires login

@login_manager.user_loader
def load_user(id):
# This sets the callback for reloading a user from the session.
# The function you set should take a user ID and return a user object, or None if the user does not exist.
# id is str or int if the keys in data.USERS are str or int
# "123123" or 123123 (see next section)
try:
    return data.USERS.get(str(id))
except:
    return None

@app.route("/", methods=["GET","POST"])
def login():
   if request.method == "POST":
       if request.form["login"]:
           id = request.form["id"]
           password = request.form["password"]
           response = data.confirmUserLogin(id, password)
           if response["status"] == True:
               # login the user
               # Login user, You should pass the actual user object to this.
               # If the user's is_active property is False, they will not be logged in unless force is True
               login_user(data.USERS[id])
               flash(response["message"])
               return redirect(url_for('index'))
           else:
               flash(response["message"])
               return redirect(url_for('login'))

    elif request.method == "GET":
        return render_template("login.html")

data.py:
#you can use: class User(Usermixin)
"""
UserMixin pre-defines these attributes for your User class:
def is_authenticated():
    ...
def is_active():
    ...
def is_anonymous():
    ...
def get_id():
    ...
"""
# or you can just define these attributes yourself
class User():
    def __init__(self, id, username, active=True):
        self.id = id
        self.username = username
        self.active = active

    def is_active(self):
        # Here you should write whatever the code is
        # that checks the database if your user is active
        # return self.active
        # for demo i just return True
        return True

    def is_authenticated(self):
        # for demo i just return True
        return True

    def get_id(self):
        # if you do not use Usermixin, this is important
        # user_loader load_user(id) uses this get_id attribute to load the id
        return self.id

# create local database of sample users
# Key are user id's : Value are User objects
USERS = {
    "123123": User("123123", "user1"),
    "456456": User("456456", "user2"),
    "789789": User("789789", "user3", False),
}

def confirmUserLogin(id, password):
    # check local db USERS for the id
    if USERS.get(sso):
        # get the user object (key's value)
        user = USERS.get(id)
        # check password
        if user.password == password:
            # entered password matches database password
            response = {"status":True, "message":"Login Successfull!"}
            return response
        else:
            # entered password DOES NOT match database password
            response = {"status":False, "message":"Wrong password, please try again."}
            return response
    else:
        # user does not exist
        response = {"status":False, "message":"User does not exist, please try again."}
        return response

A: I am quite sure that Flask-Login will not work without a class representing the data storage, because at some point it needs to access the database to know if a user has logged in already and other auth requirements.
Clearly as it does not impose a storage restriction, I think you can cheat the system without a database.
First create the User class as specified in the docs, https://flask-login.readthedocs.io/en/latest/
Define a class as so - all these methods are necessary.
class User:
    def is_authenticated():
        ...
    def is_active():
        ...
    def is_anonymous():
        ...
    def get_id():
        ...

Create a global variable that is of this user type and log users in and do whatever else. You do not necessarily need a database in which this class represents information in.
Let me know if you understood in the comments. Happy to help :)


text:
Q: Чтение данных из файла в С Не получается вывести в программе данные, считанные из файла input.txt. Файл находится в директории проекта и содержит строчку чисел - 5  100   95   5    10   45   50. Сама программа выводит какой-то мусор. В чем может быть ошибка?
Файл main.c
#include "function.h"

int main() {

    double N, U1, U2, tn, t1, t2, tk;
    int x;

    sposob_vvoda(&x, &N, &U1, &U2, &tn, &t1, &t2, &tk);

    return 0;
}

Файл function.h
#include < stdio.h >
#include < stdlib.h >
#include < math.h >

void sposob_vvoda(int *x, double *N, double *U1, double *U2, double *tn, double *t1, double *t2, double *tk);

Файл function.c
#include "function.h"

void sposob_vvoda(int *x, double *N, double *U1, double *U2, double *tn, double *t1, double *t2, double *tk) {
    printf("Выберите способ ввода данных:\n 1.С клавиатуры \n 2.Из файла\n");
    scanf("%d", x);
    switch(*x)
    {
        case 1:
            klav(&N, &U1, &U2, &tn, &t1, &t2, &tk);
            break;
        case 2:
            vvod_iz_faila(&N, &U1, &U2, &tn, &t1, &t2, &tk);
            break;
    }
}

Файл vvod_iz_faila.c
#include "function.h"
void vvod_iz_faila(double *N, double *U1, double *U2, double *tn, double *t1, double *t2, double *tk) {
    FILE *input;
    if( (input=fopen("input.txt","r")) == 0 ) {
        printf("Ошибка открытия файла");
    }
    fscanf(input, "%d%d%d%d%d%d%d", N, U1, U2, tn, t1, t2, tk);
    printf("vy vveli %d %d %d %d %d %d %d", N, U1, U2, tn, t1, t2, tk);
    fclose(input);
}

Программа выводит следующее:
Выберите способ ввода данных:
 1.С клавиатуры
 2.Из файла
2
vy vveli 2337384 2337392 2337400 2337408 2337416 2337424 2337432
ВЫПОЛНЕНИЕ SUCCESSFUL (общее время: 5s)

A: Посмотрите внимательно на числа, которые напечатались - они подозрительно отличаются на 8. А все потому, что печатаете Вы адреса.
Поэтому, первое, что нужно исправить, это печатать значения, а не адреса.
printf("vy vveli %d %d %d %d %d %d %d", *N, *U1, *U2, *tn, *t1, *t2, *tk);

Но есть ещё одна штука.
vvod_iz_faila(&N, &U1, &U2, &tn, &t1, &t2, &tk);

Здесь N, U1 и подобное - это уже адреса. И вы передаете адрес адреса. Это точно то, что нужно?
A: @Иван Кущёв, раз решилась, значит Вы еще и %d на %lf в fscanf()  заменили?
Обновление
Тогда поменяйте.
Правильно:
double d;

scanf("%lf", &d); printf("%f\n", d);

или с функцией
void f(double *d) {
  scanf("%lf", d);
}
int main () {
  double d;
  f(&d); printf("%f\n", d);
}

Обновление
Если честно, то я сомневаюсь, что она (как Вы описали изменения, я же не вижу всего действующего сейчас кода) действительно правильно работает. По идее ввод по адресу double в формате %d никак не может дать правильного значения.

Вкратце, что касается %f и %lf:

*

*
При передачи в функцию float преобразуется в double. Поэтому для печати обоих типов используется %f (%lf тоже подойдет).

*
А вот при вводе scanf как-то же должен отличать 4-х байтный float (формат %f) от 8-ми байтного double (формат %lf).
Подробнее см. man 3 scanf и man 3 printf.


text:
Q: Error Logging for C# I was previously using Sentry for maintaining error logs on my C# application.
I want to switch to something that is downloadable since I have some sensitive data. Is there any error logging software like sentry but can be hosted by me?
Thanks in advance!

A: If you are already familiar with using sentry then you can install it on you own server: https://github.com/getsentry

A: for C# use sentry client: https://github.com/getsentry/raven-csharp
also today I fix ssl problem for it: https://github.com/getsentry/raven-csharp/pull/52

A: Elmah (Error Logging Modules and Handlers) is good for this.
It is very easy to set up. There are various Nuget packages for different storage options. The most basic is to store the files in XML in the application's App_Data folder. Then you can configure access to the pretty web interface via the web.config.
Scott Hanselman has an old but good write-up on it too.


text:
Q: Logic of interaction among models in Ruby on Rails? I'm studying Rails and am now trying to organize interaction among models. What I've written works, but I think that the code smells bad.
For example, I have two models with database tables Parcel and Warehouse. When I create a new Parcel, I want to increase the :current_weight of the Warehouse instance which is related to this new Parcel.
Again, everything works, but this type of code, interaction between two different objects, will be used frequently and something deep in my mind says: "Dude, this code sucks and will cause problems in the future!".
Maybe there are some good practices to organize or refactor it? Maybe it's
better to create a universal module for such interactions, or even create
method_missing logic to use methods with universal put_, remove_,
check_, like warehouse.put_parcel and warehouse.remove_parcel.
In ruby console:
parcel = Parcel.new
parcel.weight = 10
parcel.warehouse_id = 1
parcel.save

# Create parcel and increase :current_weight of related warehouse by 10 after save

warehouse.rb:
class Warehouse < ActiveRecord::Base
    has_many :parcels
  attr_accessible :name, :current_weight
end

parcel.rb:
class Parcel < ActiveRecord::Base
    belongs_to :warehouse
    belongs_to :vehicle
  attr_accessible :name, :weight, :warehouse_id, :vehicle_id

  after_save :set_current_weight

  #Bad code:
  def set_current_weight
    @wh = self.warehouse
    @wh.current_weight = @wh.current_weight + self.weight
    @wh.save
  end
end

A: How about
warehouse.parcels.sum(:weight)

That way you are running a 'live' query based on the current data, rather the incrementing.
Slightly more terse version of your current model too:
  def set_current_weight
    @wh = self.warehouse
    @wh.current_weight += self.weight
    @wh.save
  end

A: The current_weight of the warehouse is really not part of a Parcel object mandate. You have also given it more than one reason to change. Thus, this breaks the single responsibility principle.
I would suggest removing :current_weight and set_current_weight altogether. Get the total weight inside warehouse like this:
def Warehouse < ActiveRecord::Base
  has_many :parcels
  # ...

  def current_weight
    parcels.sum(:weight)
  end
end

As suggested by @muttonlamb in his post.


text:
Q: eval returning variable name instead of undefined. (javascript) Update
The code for the function / class is stored in a string which is why I cannot call it directly. The idea is to do introspection on the object and enumerate its data members which works when it is a function but doesn't work when a variable like the one below is eval'ed.
I am trying to evaluate an object in javascript. Something like this.
var myObj {
   greet: "Greeting",

   myPrint: function() {
      alert("hello");
   }
};

The idea is to be able to run this in eval and get the variable name somehow (myObj) or an object created. I have experimented with various methods using eval but cannot figure this out. This works when I have something like this.
function myObj() {
   this.greet  = "Greeting";

   this.myPrint = function() {
      alert("hello");
   }
};

Running eval("(" + code + ")"); where code is a string containing the above function returns myObj() to me.
Update 2
So basically I want to evaluate something like this.
eval("var x = 5"); and I am trying to get x. Since its a string being evaluated, even though it gets added to the window namespace, there is no way to decipher it apart from parsing the string. Now this is just a simple example but as I said, it's a little difficult with the 1st piece of code. As I said...
eval("function test() { return 'hello'; }"); return test() which is similar to what I am expecting for the "var x = 5" statement.
Is there a way to do this similarly for the 1st case which I am missing ?
Thanks

A: You eval the object without executing the myPrint function.
You would need to do something like
  myObj.myPrint()

To get it to throw the alert.
[edit] To immediately run the myPrint function change your code to this:
  var myObj = {
    greet: "Greeting",

    myPrint: (function() {
      alert("hello");
    })();
  };

A: Are you trying to dynamically call a callback?
var myObj = { // fixed this line of code as it was missing the =
   greet: "Greeting", // replaced ; with ,

   myPrint: function() {
      alert("hello");
   }
};
console.log(eval(myObj)); // returns obj as expected.

If I am correct in my assumption you would need to use bracket notation and EVAL is not needed
So if you were passing a String it would look like:
var str = 'myPrint';

var strTwo = 'greet'

myObj[str](); // to execute the function

myObj[strTwo]; // now contains "Greeting"

Which would execute that function.
Hope that helps!
Tim
EDIT:
var myObj = 'var myObj = { greet: "Greeting", myPrint: function() { alert("hello"); } }'

console.log(eval(myObj));
myObj.myPrint();

Then this is what you want if this does not work it means you are not escaping your string correctly:
http://jsfiddle.net/XtyHh/

A: A code:
var sCode = '{ great: "Greating", myPrint: function() { alert("hello!"); } }',
    oObj = eval("(" + sCode + ")");

oObj.myPrint(); // alert "hello"
console.log(oObj.great); // prints "Greating"


text:
Q: LINQ Grouping: Select row instead of key? I probably won't be able to explain this well enough, but here it goes...
I have a table similar to this:
Id | Foreign_Key_Id | A_Number | Some_Other_Info
1      1                100          Red
2      1                200          Blue
3      1                300          Orange
4      2                100          Green
5      2                200          Yellow
6      3                100          Brown

I want to get the max "A_Number" for a particular "Foreign_Key_Id" in this table, but also return the rest of the record so I have info from the "Some_Other_Info" column.
I've found I can accomplish this via a query like this:
from x in This_Table
group x by x.Foreign_Key_Id into g
orderby g.Max(x => x.A_Number) descending
select g.Where (x => x.Foreign_Key_Id == g.Key).OrderByDescending (x => x.A_Number).First()

Edit: Or possibly this more concise query:
from x in This_Table
group x by x.Foreign_Key_Id into g
let maxANumber = g.Max(x => x.A_Number)
orderby maxANumber descending
select g.Where(x => x.A_Number == maxANumber).First()

Although I'm not quite sure which record it would take if one Foreign_Key_Id had two records with the same "A_Number" value (which is possible in the table I am referring to, I would just need to take the most recent one).
Which in my example I believe would return:
Id | Foreign_Key_Id | A_Number | Some_Other_Info
3      1                300          Orange
5      2                200          Yellow
6      3                100          Brown

It seems like there has to be a way to do this in an easier fashion (that makes for a faster query than the one I came up with), I just can't figure out how.
Thanks in advance.

A: The following also works. You can order inside the group:
from x in This_Table
group x by x.Foreign_Key_Id into g
select g.OrderByDescending(y => y.A_Number).First();

Taking the most recent record when A_Numbers are equal is as simple as adding another OrderBy to the query.


text:
Q: How to represent the constraint (A && B) || (C && D) || (E && F) || I'm new to or-tools and I'm trying to represent the constraint:
(!A && !B) || (!C && !D) || (!E && !F) || ...
I tried the following (in my case A is shift_0LM0, B is shift_0LT0, C is shift_0MM0, D is shift_0MT0, ...), expressing !A && !B as A + B == 0, ie. !(A || B):
    for week in range(4):
        for employee in range(5):
            model.AddBoolOr([
                shift[f'{week}{weekday}M{employee}'] + shift[f'{week}{weekday}T{employee}'] == 0
                for weekday in 'LMXJVSD'
            ])

but I get the error:
TypeError: NotSupported: model.GetOrMakeBooleanIndex((shift_0LM0 + shift_0LT0) == 0
is there an easy way to express this constraint?

A: As Laurent said, AddBoolOr expects booleans literals, so you have to create intermediate variables:
from ortools.sat.python import cp_model

model = cp_model.CpModel()
a, b, c, d = [model.NewBoolVar(x) for x in 'abcd']

not_a_not_b = model.NewBoolVar('!A && !B')
model.Add(a+b == 0).OnlyEnforceIf(not_a_not_b)

not_c_not_d = model.NewBoolVar('!C && !D')
model.Add(c+d == 0).OnlyEnforceIf(not_c_not_d)

model.AddBoolOr([not_a_not_b, not_c_not_d])

solver = cp_model.CpSolver()
solver.Solve(model)

for x in [a, b, c, d]:
    print(solver.Value(x))

Edit: for (A && B) || (C && D) just change a+b == 0 into a+b == 2
If you want avoid duplicated solutions when searching for all solutions you have to add the other implication:
model.Add(a+b != 0).OnlyEnforceIf(not_a_not_b.Not())


text:
Q: Adding attachments to email sent by a WordPress plugin I'm using a payment/email delivery plugin for WordPress named CP Contact Form with PayPal and want to attach PDF files to the emails, for this purpose, I am going to write my own plugin. There is a way to do this without accessing the third party plugin code?

A: The plugin has a filter for that purpose, use this code into your own plugin:
add_filter( 'cpcfwpp_email_attachments', 'my_pdf_file_function' ), 10, 3 );
function my_pdf_file_function( $attachments, $params, $form_id)
{
    $attachments[] = WP_CONTENT_DIR . '/uploads/my_pdf_file.pdf';
    return $attachments;
}

This way you can add an attachment to the CP Contact Form with PayPal emails without having to modify the plugin code.
Regarding to the parameters for the 'cpcfwpp_email_attachments' filter:
$attachments is an array of files to be included into the email, each item in this array should contain the complete path to the file to be attached.
$params is an associative array that contains the submitted data, using the field IDs as key (you can check the fields IDs in the form builder). It also contains $params["itemnumber"] to check the submission ID.
$form_id is the ID of the submitted form.
More info can be found in the CP Contact Form with PayPal plugin website.


text:
Q: Is there a better way to Initialize a record array to make it more dynamic? C# Some background about my code, I basically have a record class which has a lot of properties to capture the required data provided in the form of .txt files and each column is divided into their own separate files i.e. Month.txt, Day.txt, containing 600 rows of data in each.
Now, I have a second array which is basically a collection of the aforementioned class and I give it max value of 600 (as there are 600 of data). This class possesses an Initialization method.
This way it Initializes my records each column at the time, but I have to know the fixed size of the rows to not run into index out of range exception. Also, I have a lot of properties so the overall "if else" statements make this code look very redundant and hard on the eye. Flexibility is also an issue as the point resets to 0, so when I want to add extra data, I will just be overriding the original 600.
Is there anyway to improve this?

A: The code is suboptimal, because it checks the file name for each line in that file. It is better to decide what field to set before the loop, and then use that decision throughout the loop.
First, make a look-up table of setters based on the file prefix:
var setters = new Dictionary<string,Action<Record,string>> {
    ["Day"]   = (r,v) => r.Day = v
,   ["Month"] = (r,v) => r.Month = v
,   ...
};

With this look-up in place, the reading code becomes straightforward:
using (StreamReader R = new StreamReader(file.FullName)) {
    var pos = File.Name.IndexOf("_");
    Action<Record,string> fieldSetter;
    if (pos < 0 || !setters.TryGetValue(File.Name.Substring(0, pos), out fieldSetter)) {
        continue; // Go to next file
    }
    string temp;
    while((temp = R.ReadLine()) != null) {
        fieldSetter(records[pointer++], temp);
    }
}

First, we look up the setter using the prefix from the file name up to the first underscore character '_'. Then we go through the lines from the file, and call that setter for each record passing the string that we got.
Adding new fields becomes simple, too, because all you need is to add a new line to the setters initializer.


text:
Q: Loading .npz with Python 3.5 always crashes In this simple tutorial written in Python 2.7, they have a line loading the numpy array.
train_data = np.load(open('../musicnet.npz','rb'))

Then, they get the data by calling different keys
X,Y = train_data['2494']

Everything works well in python 2.7
Data type of train_data is numpy.lib.npyio.NpzFile
My problem
However, whenever I try to do the same in Python 3.5, most of the lines work fine, except when it comes to the line of X,Y = train_data['2494'], it just freezes there forever. I would like to use Python 3.5 because my other projects are written in python 3.5.
How to rewrite this line so that it runs with Python 3.5?
Error Message
I finally managed to get the error message in terminal

It freezes there because there's tons of output right after the error message, my jupyter notebook just cannot handle that much information.

Solution
Change the encoding to 'bytes'
train_data = np.load('../musicnet.npz', encoding='bytes')

Then everything works fine.

A: You first said things crashed, now you say it freezes when trying to access a specific  array.  numpy has the same syntax in 3.5 compared to 2.7.  You shouldn't have to rewrite anything.
np.load does have a couple of parameters that deal with differences between Py2 and Py3.  But I'm not sure these are an issue for you.
fix_imports : bool, optional
    Only useful when loading Python 2 generated pickled files on Python 3,
    which includes npy/npz files containing object arrays. If `fix_imports`
    is True, pickle will try to map the old Python 2 names to the new names
    used in Python 3.
encoding : str, optional
    What encoding to use when reading Python 2 strings. Only useful when
    loading Python 2 generated pickled files in Python 3, which includes
    npy/npz files containing object arrays. Values other than 'latin1',
    'ASCII', and 'bytes' are not allowed, as they can corrupt numerical
    data. Default: 'ASCII'

Try
print(list(train_data.keys()))

This should show the array names that were saved to the zip archive.  Do they match the names in the Py2 load?  Do they include the '2494' name?
A couple of things are unusual about:
X,Y = train_data['2494']

Naming an array in the zip archive by a string number, and unpacking the load into two variables.
Do you know anything about how this was savez?  What was saved?
Another question - are you loading this file from the same machine that Py2 worked on?  Or has the file been transferred from another machine, and possibly corrupted?
As those parameters indicate, there are differences in the pickle code between Py2 and Py3.  If the original save included object dtype arrays, or non-array objects, then they will be pickled and there might be incompatibilities in the pickle versions.

A: Try this,
with np.load('../musicnet.npz') as train_data:
    X,Y = train_data['2494']

A: There are 2 ways out in my point of view:

*

*re-edit your code
train_data = np.load(open('../musicnet.npz','rb'))
to
train_data = np.load(open('../musicnet.npz','r'))
Because the mode of r/rb in python2.7 / 3.5 is a difference in your situation.

*Using the default debugger to pointing the significant error. (Usually, work on my experience)


text:
Q: How to use functions trigger on different emulator's firestore? We have two emulators under same firebase project. One with firestore, storage, auth on server PC and one with only functions on laptops. Because we didn't want to throw away all the data when re-run the emulator.
We tried to use functions trigger on another emulator's firestore but it didn't work with the message.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();

export const onSomeEventTrigger = functions.firestore
  .document(`collection/users`)
  .onCreate(async (snap, context) => {
    // do something...
});

functions[us-central1-onSomeEventTrigger]: function ignored because the firestore emulator does not exist or is not running

What we tried:

*

*changed the value of FIRESTORE_EMULATOR_HOST in .env into host of server PC's emulator's firestore

*passed config with database URL to admin.initializeApp()
According to this question and documents, it looks possible to connect 1 functions with the firestores of multiple projects.
We're using the server's emulator in Flutter app, so it doesn't look like server's problem.
How can I use functions trigger on different emulator's firestore?


text:
Q: The model item passed into the dictionary is of type 'System.Tuple'? Here am implementing Tuple for using two models in my view. But am getting the following error :

The model item passed into the dictionary is of type
  System.Tuple'2[WebApplication.Models.log_voyage,System.Collections.Generic.List'1[WebApplication.Models.log_ligne_voyage]]», but this dictionary requires a model item of type «System.Tuple'2[System.Collections.Generic.List'1[WebApplication.Models.log_voyage],System.Collections.Generic.List'1[WebApplication.Models.log_ligne_voyage]]».

Here is my View:
@using WebApplication.Models;
@model Tuple<List<log_voyage>, List<log_ligne_voyage>>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout1.cshtml";
}

Controller:
 public ActionResult Index( int id = 0 )
 {

     var first =  entities.log_voyage.Where(v => v.Num_Voy == lastVoyageID).FirstOrDefault();
     log_voyage voyage1 = entities.log_voyage.Find(lastVoyageID);
     var second = entities.log_ligne_voyage.Where(x => x.NUM_Voy == lastVoyageID).ToList();
     var t = new Tuple<log_voyage, List<log_ligne_voyage>>(first, second);
     return View(t);

}

[HttpPost]
public ActionResult Index(Tuple<log_voyage, List<log_ligne_voyage>> voy)
{
    try
    {
        if (voy.Item1.Dat_Voy == null)
        {
            ModelState.AddModelError("Dat_Voy", "Incorrect Date.");
        }
        //.............Some Code .........//

            entities.Entry(voy.Item1).State = EntityState.Modified;
            entities.SaveChanges();

            return RedirectToAction("Index", "Miss_Voyage");
        }
        else
        {
            GetListcontoller();
            return View(voy);
        }
    }
    catch (DataException /* dex */)
    {
        ModelState.AddModelError("", "Impossible d'executer cette action. contacter le service info SVP.");
        GetListcontoller();
        return View("Index", "Home");
    }
}

Any suggestion Please ?

A: As Mike McCaughan pointed out.
The model you are returning from controller is
Tuple<log_voyage, List<log_ligne_voyage>> voy

But the view is expecting
@model Tuple<List<log_voyage>, List<log_ligne_voyage>>

As you said getting error if you change view to
Tuple<log_voyage, List<log_ligne_voyage>>

try changing the controller to
Tuple<List<log_voyage>, List<log_ligne_voyage>>

Like the below code:
   [HttpPost]
   public ActionResult Index(Tuple<List<log_voyage>, List<log_ligne_voyage>> voy)
   {
     try
     {
      if (voy.Item1.Count() == 0)
      {
          // followed by your code

A: var first =  entities.log_voyage.Where(v => v.Num_Voy == lastVoyageID).FirstOrDefault();

will return a single instance of
 WebApplication.Models.log_voyage

Your view requires
 Tuple<List<log_voyage>, List<log_ligne_voyage>>

To get the List required for the first item in the Tuple, you will need to construct a list from the item you retrieve using "FirstOrDefault" or you'll need to change the model of the view.

A: Try using a view model rather than a Tuple.
Your code would then look something like this:
public class VoyageViewModel
{
    public log_voyage log { get; set; }
    public List<log_ligne_voyage> log_ligne_voyage_list { get; set; }
}

public ActionResult Index(VoyageViewModel voyageViewModel)
{
    ...
}


text:
Q: Detecting mac as iBeacon with iPhone I'm just tinkering with iBeacons for the first time. I'm using MactsAsBeacon (https://github.com/timd/MactsAsBeacon) to broadcast a beacon using my Macbook.
I'm just a bit confused as to the simplest way to view this iBeacon through my iPhone.
I tried downloading some apps that are supposed to locate iBeacons, but they don't seem to work. What is the fastest, simplest way to pick up my iBeacon broadcast from mac to iPhone? Thanks

A: A few tips:

*

*Make sure that the same ProximityUUID that you have configured into your iBeacon transmitter on your MacBook is configured into the iPhone app detecting them.  I'm the author of Locate for iBeacon, which is free in the AppStore, so I can confirm that it can detect any valid iBeacon if it is configured with its ProximityUUID.  Here's what you should see:

*Assuming you have iOS 7.1 on your iPhone, you should know that it has a bug that can prevent it from detecting iBeacons when the phone has been on for awhile.  Cycle power to the phone or turn bluetooth off and back on to correct this.

*Make sure your Mac supports acting as a transmitter.  You must have OSX Mavericks and a computer with Bluetooth 4.0.  To check the latter, go to About this Mac > More Info > System Report > Hardware > Bluetooth then you should see LMP Version in the list.  You need to have a version of 0x6 (Bluetooth Core Specification 4.0, e.g. BTLE), otherwise you will need to get a BTLE USB Stick.

*Make sure you have quit all other apps that use Bluetooth LE.  Knock app, ScanBeacon, other virtual beacon transmitter tools, etc.  And make sure you have Bluetooth turned on before starting MactsAsBeacon.  The app doesn't warn you if you don't have it enabled, and if you turn on bluetooth after the app is started, you'll have to restart it to get it to work again.

*If you try all of the above and they don't work, it's time to try a different transmitter on your Mac.  My company makes a $10 transmitter app called MacBeacon, and we offer a free VirtualBox VM that can also turn your Mac into an iBeacon if you also install the free VirtualBox software.  Both can be detected by Locate for iBeacon or any standard iBeacon detection app.


text:
Q: Spring Boot RandomValuePropertySource nested properties Is it possible in some way to "store" the random value generated by ${random.value} and reference it in other properties as a nested value? I cannot seem to figure how to make this work.
Here is an example of the scenario. I would expect the following test to pass, however, foo and bar are always resolved to different random values.
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by dustin.schultz on 12/14/15.
 */

@SpringApplicationConfiguration(classes = FooBar.TestApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = { "foo=${random.value}", "bar=${foo}" })
public class FooBar
{
    @Value("${foo}")
    private String foo;

    @Value("${bar}")
    private String bar;

    @Test
    public void foo()
    {
        assertThat(foo, is(bar));
    }

    @Configuration
    @EnableAutoConfiguration
    public static class TestApplication
    {

    }
}


text:
Q: Echo TAB is not working I'm using TAB for display a block of code with commnad:
echo -e "192.168.1.103 \t TUNG \t 30:65:ec:1f:77:b7"
echo -e "192.168.1.107 \t LCT3VCLJN2K3MCZ \t 00:1f:c6:53:a5:36"

but it display not correctly in terminal:

But I want it to be display bellow:

I'm using Ubuntu 14.04, please help me !
Thanks in advance !

A: Use the column command:
$ { echo 192.168.1.103 TUNG 30:65:ec:1f:77:b7; echo 192.168.1.107 LCT3VCLJN2K3MCZ 00:1f:c6:53:a5:36;} | column -t
192.168.1.103  TUNG             30:65:ec:1f:77:b7
192.168.1.107  LCT3VCLJN2K3MCZ  00:1f:c6:53:a5:36


text:
Q: How do I scrape "description" of movies in the IMDB website using BeautifulSoup? I am using BeautifulSoup to scrape movies in the IMDB website. I was able to scrape name, genre, duration, rating of movies successfully. But I am not able to scrape description of the movies as when I am looking at the classes, it is "text-muted" and since this class is there multiple times holding other data such as rating, genre, duration. But since these data has inner classes also, so it was easier for me to scrape it but when it is coming to description, it does not have any inner class. So when pulling out data just using "text-muted" is giving other data also. How do I just get the description of the movies?
Attaching the code and screenshot for reference:

The sample code which I used to scrape genre is as follows:
genre_tags=data.select(".text-muted .genre")
genre=[g.get_text() for g in genre_tags]
Genre = [item.strip() for item in genre if str(genre)]
print(Genre)

A: In general, lxml is much better than beautifulsoup.
import requests
from lxml
import html

url = "xxxx"

r = requests.get(url)

tree = html.fromstring(r.text)

rows = tree.xpath('//div[@class="lister-item mode-detail"]')

for row in rows:
    description = row.xpath('.//div[@class="ratings-bar"]/following-sibling::p[@class="text-muted"]/text()')[0].strip()

A: You can use this, :) , if helped you, UP my solution pls.. thks,
from bs4 import BeautifulSoup
from requests_html import HTMLSession

URL = 'https://www.imdb.com/chart/moviemeter/?ref_=nv_mv_mpm' #url of Most Popular Movies in IMDB

PAGE = HTMLSession().get(URL)
PAGE_BS4 = BeautifulSoup(PAGE.html.html,'html.parser')

MoviesObj = PAGE_BS4.find_all("tbody","lister-list") #get table body of Most Popular Movies
for index in range(len(MoviesObj[0].find_all("td","titleColumn"))):
    a = list(MoviesObj[0].find_all("td","titleColumn")[index])[1]
    href = 'https://www.imdb.com'+a.get('href') #get each link for movie page
    moviepage = HTMLSession().get(href) #request each page of movie
    moviepage = BeautifulSoup(moviepage.html.html,'html.parser')
    title = list(moviepage.find_all('h1')[0].stripped_strings)[0] #parse title
    year = list(moviepage.find_all('h1')[0].stripped_strings)[2] #parse year
    try:
        score = list(moviepage.find_all('div','ratingValue')[0].stripped_strings)[0] #parse score if is available
    except IndexError:
        score = '-' #if score is not available '-' is filled
    description = list(moviepage.find_all('div','summary_text')[0].stripped_strings)[0] #parse description
    print(f'TITLE: {title}      YEAR: {year}       SCORE: {score}\nDESCRIPTION:{description}\n')

PRINT
Junior Saldanha
@UmSaldanha


text:
Q: Junior Dev (Starting Out) Guidance : DTO and creating the object I am a junior developer, just starting out :). I have a project where I have made some Data Transfer Objects (DTO) for an API I have created. I am writting some Unit Tests and wanted the unit and integration tests to use these to pass data and verify responses.
The issue I have is i feel the way i am using them is NOT Best practice and I am repeating myself (DRY).  Could i get some guidance on the matter please?
DTO
public class myDTO
{
    public class Request
    {
        public bool enabled{ get; set; }
        public int? age{ get; set; }
        public string name{ get; set; }

    }
}

Then i have a class that uses this in a unit test:
public async Task somethingTest()
{

    var request = new myDTO.Request
    {
        enabled= true,
        age     = 21,
        name    = "bob"
    };

    var returnedResponse = await new client().updatePerson(
            string.Format(PersonUri, users, userId),
            request);

    Assert.Equal(HttpStatusCode.NoContent, returnedResponse.StatusCode);
}

public async Task somethingTest2()
{

    var request = new myDTO.Request
    {
        enabled= true,
        age     = 28,
        name    = "Gill"
    };

    var returnedResponse = await new client().updatePerson(
            string.Format(PersonUri, users, userId),
            request);

    Assert.Equal(HttpStatusCode.NoContent, returnedResponse.StatusCode);
}

public async Task somethingTest3()
{

    var request = new myDTO.Request
    {
        enabled= true,
        age     = 45,
        name    = "tim"
    };

    var returnedResponse = await new client().updatePerson(
            string.Format(PersonUri, users, userId),
            request);

    Assert.Equal(HttpStatusCode.NoContent, returnedResponse.StatusCode);
}

I cannot help but feel there is a better way to be building the DTO than having it over and over.
Any guidance / help would be really appreciated.

A: Since your Assertions are identical in all three tests, these tests are validating very similar scenarii.
Here are some possible changes you could make on these tests to avoid repetition and maybe expand the validations these tests are performing:

*

*use the xunit Theory and InlineData/MemberData attributes. This way, you only need to write your unit test once and can pass your test scenarii (data) as parameters.

*try to be more precise with your Assertions. I.e., also Assert that your client invoked your Repository/DAL's update method with the data from the given Request.

*Finally, if you are worried about the coherence of your DTOs over time, for instance if you know that you'll add new properties to the DTO over time, you could consider making the properties of the DTO get-only and initializing them through the constructor.


text:
Q: Unable to use $.get within WordPress page I'm trying to use an ajax $.get() request to display calculated data within one of my WordPress pages. I haven't decided if I'm going to host the php calculation file on a different server of mine, or the one that WordPress is hosted on (don't think this would make a difference anyway since its a data request). I'm looking to add the following code to either the header.php file, or even better, within the page created in wp-admin:
<script>
  $(document).ready(function(){
      $.get("http://my-other-website.com/parse-list.php",function(data){
          alert(data);
      });
  });
</script>

I know this is a basic function, but I'm just really stumped on how it doesn't work within WordPress, but works when on my other server that doesn't host WordPress. I tested jQuery to make sure it was being loaded properly, with a simple alert("hey");, and the alert works just fine. Has anyone else had this problem? Any help would be greatly appreciated!

A: jQuery in WordPress runs in noConflict mode which means the global $ shortcut for jQuery isn't available. Replace your code with the following:
<script>
  jQuery(document).ready(function($){
      $.get("http://my-other-website.com/parse-list.php",function(data){
          alert(data);
      });
  });
</script>


text:
Q: Android Beacon Library version -- 2.3.5 not detecting TI senor tag Mobile device model and OS version -- Nexus 5, API 23
Android Beacon Library version -- 2.3.5
I have a sensor tag from TI(Texas Instruments), and the firmware is TI provided.  The same 2541 chipset is used in all beacons.  I try to detect it using this library, it comes inside the didRangeBeaconsInRegion() callback but it prints beacons.size to be zero size.
Now, what changes I need to do, to get this chipset detected?
Just for further information, there are free apps in playstore named (iBeacon detector) which detects this chipset.
Any help will be highly appreciated.
Thank You

A: A few points:

*

*The Android Beacon Library is designed to work with Bluetooth LE Beacons, not non-Beacon BLE devices.  A beacon is a specialized BLE device that continually broadcasts a unique identifier.  If you need a more general purpose BLE functionality, the library may not be a good fit.

*The TI Sensor Tag must be loaded with specific firmware to make it broadcast as a beacon.

*There are many beacon formats including AltBeacon, Eddystone and iBeacon.  If your BLE device is transmitting as a beacon you need to know which one it is transmitting.

*By default, the Android Beacon Library only detects beacon transmitters sending the AltBeacon format.  To detect other beacon formats, you must supply a BeaconParser for that format. A Google search will easily find the Parser expression to configure based on the format the beacon is using.


text:
Q: BASS.DLL | Радио | Название песни Не удается получить название песни у второго потока.
Получаю так:
function Meta(URL: String): String;
var
  Media: Cardinal;
begin
  BASS_Init(-1, 44100, BASS_UNICODE, 0, nil);
  Media := BASS_StreamCreateURL(PChar(URL), 0, BASS_UNICODE, nil, nil);
  Result := String(AnsiString(BASS_ChannelGetTags(Media, BASS_TAG_META)));
  BASS_Free;
end;

Результаты трех потоков
Поток #1: https://graalradio.com:8124/space
Результат: StreamTitle=''Zanio - Will (Elevate Raggapop Inc Remix)'';
Поток #2: http://air.radiorecord.ru:805/rus_320
Результат:
Поток #3: http://wargaming.fm/1
Результат: StreamTitle=''Promise Land & GLDN - Blow Ya Mind (Radio Edit)'';
К примеру MPC-HC отображает нормально

Пробовал получать другие теги, но результаты были пустыми.
Как быть?

UPD
Проверил потоки по совету в ответе от t3f
x32

x64

Забьем пока на x64 и проверим другие потоки.

В общем всё печально, легче брать эти данные напрямую из потоков.
Но как это сделать?

A:
Как быть?

Для начала - проверять возвращаемые значения и коды ошибок, чтобы точно знать что происходит. Например так:
function Meta(URL: String): String;
var Media: Cardinal; TagPtr: PAnsiChar;
begin
  if not BASS_Init(-1, 44100, BASS_UNICODE, 0, nil) then
    ShowMessage('Init failed with code: ' + IntToStr(BASS_ErrorGetCode));
  Media := BASS_StreamCreateURL(PAnsiChar(URL), 0, BASS_UNICODE, nil, nil);
  if Media = 0 then
    ShowMessage('StreamCreateURL failed with code: ' + IntToStr(BASS_ErrorGetCode));
  TagPtr := BASS_ChannelGetTags(Media, BASS_TAG_META);
  if TagPtr = nil then
    ShowMessage('ChannelGetTags failed with code: ' + IntToStr(BASS_ErrorGetCode));
  BASS_Free;
  Result := TagPtr;
end;

И только потом, когда будет точно известно где и какая ошибка происходит, уже можно будет судить о причинах.


text:
Q: Error when try to store emoji I'm using sequelize as ORM for node.js to interact with mysql database.
My database charset is utf8mb4, utf8mb4_general_ci
My table charset is utf8mb4, utf8mb4_general_ci
My column TYPE is TEXT and charset is utf8mb4, utf8mb4_general_ci
Before executing any query, i'm executing following code:
Sequelize.query("SET NAMES utf8mb4");
Sequelize.query("SET CHARACTER SET utf8mb4");

After executing Sequelize.query("SHOW VARIABLES LIKE 'character_set_%'"), i've got:
[ [ RowDataPacket { Variable_name: 'character_set_client', Value: 'utf8mb4' },
    RowDataPacket { Variable_name: 'character_set_connection', Value: 'utf8mb4' },
    RowDataPacket { Variable_name: 'character_set_database', Value: 'utf8mb4' },
    RowDataPacket { Variable_name: 'character_set_filesystem', Value: 'binary' },
    RowDataPacket { Variable_name: 'character_set_results', Value: 'utf8mb4' },
    RowDataPacket { Variable_name: 'character_set_server', Value: 'utf8' },
    RowDataPacket { Variable_name: 'character_set_system', Value: 'utf8' },
    RowDataPacket {
      Variable_name: 'character_sets_dir',
      Value: 'c:\\openserver\\modules\\database\\MySQL-5.7-x64\\share\\charsets\\' } ],
  [ RowDataPacket { Variable_name: 'character_set_client', Value: 'utf8mb4' },
    RowDataPacket { Variable_name: 'character_set_connection', Value: 'utf8mb4' },
    RowDataPacket { Variable_name: 'character_set_database', Value: 'utf8mb4' },
    RowDataPacket { Variable_name: 'character_set_filesystem', Value: 'binary' },
    RowDataPacket { Variable_name: 'character_set_results', Value: 'utf8mb4' },
    RowDataPacket { Variable_name: 'character_set_server', Value: 'utf8' },
    RowDataPacket { Variable_name: 'character_set_system', Value: 'utf8' },
    RowDataPacket {
      Variable_name: 'character_sets_dir',
      Value: 'c:\\openserver\\modules\\database\\MySQL-5.7-x64\\share\\charsets\\' } ] ]

But when i'm trying to save string that containing emoji, i ran into an error:
Unhandled rejection SequelizeDatabaseError: ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Incorrect string value: '\xF0\x9F\x91\x8D\xF0\x9F...' for column 'content' at row 1

A: I ran into this issue also and solved it easily, you only need to set your database to utf8_general_ci. And when doing the connection at node.js you need to add the "charset" parameter:
var pool = mysql.createPool({
    host: "host",
    user: "username",
    password: "password",
    database: "database",
    connectionLimit: xxxx,
    charset : 'utf8mb4'
});

This did the trick for me.

A: I had the same problem trying to insert emoji into MySQL with Express and Sequelize. You can confirm your current character set like
SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';

The default connection output from the above looks like this
character_set_client      utf8
character_set_connection  utf8
character_set_database    utf8mb4
character_set_filesystem  binary
character_set_results     utf8
character_set_server      utf8mb4
character_set_system      utf8
collation_connection      utf8_general_ci
collation_database        utf8mb4_unicode_ci
collation_server          utf8mb4_unicode_ci

If your MySQL config file /etc/my.cnf looks like
[client]
default-character-set = utf8mb4

[mysql]
default-character-set = utf8mb4

[mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

But if you run
SET NAMES utf8mb4;

Then the SHOW VARIABLES WHERE... from above again it will update to utf8mb4 across the board.
character_set_client      utf8mb4
character_set_connection  utf8mb4
character_set_database    utf8mb4
character_set_filesystem  binary
character_set_results     utf8mb4
character_set_server      utf8mb4
character_set_system      utf8
collation_connection      utf8mb4_general_ci
collation_database        utf8mb4_unicode_ci
collation_server          utf8mb4_unicode_ci

So, the solution I found is to put the following on the first line of my User model:
// make sure db/client/connection can support emoji
sequelize.query("SET NAMES utf8mb4;");
// confirm settings
sequelize.query("SHOW VARIABLES LIKE 'character_set_%'").then(function(data) {
     console.log(data);
});