text:
Q: Getting different output with printf and cout - C++ I have a string I am trying to print. when I used cout, it outputs perfectly but using printf leaves it mangled.
Here is the code:
int main ( int argc, char *argv[] )
{
    // Check to make sure there is a single argument
    if ( argc != 2 )
    {
        cout<<"usage: "<< argv[0] <<" <filename>\n";
        return 1;
    }

    // Grab the filename and remove the extension
    std::string filename(argv[1]);
    int lastindex = filename.find_last_of(".");
    std::string rawname = filename.substr(0, lastindex);

    cout << "rawname:" << rawname << endl;
    printf("rawname: %s", rawname);

}

The cout gives me "rawname: file"
The printf gives me "rawname: " and then a bunch of squiggly characters

A: You need to print the internal char* of the std::string:
printf("rawname: %s", rawname.c_str());

A: Try this
cout << "rawname:" << rawname << endl;
printf("rawname: %s", rawname.c_str());

rawname is not a char array, but an instance of the std::string class. To get the actual char array, you should call the c_str() function

A: it's because rawname is defined as a std::string.  You need to use
printf("rawname: %s", rawname.c_str());
The reason is that printf with the %s is expecting a null terminated C string in memory.  Whereas a std::string stl string isn't exactly raw - it eventually null terminates in your situation, not sure if that's even a guarantee, since the length is internally managed by stl container class.
Edit:
As pointed out in a comment, internally it's guaranteed to be null terminated.  So what you're seeing as 'squiggly lines' is an output of all the allocated but not utilized (or initialized) memory in that string up until the null terminator character.

A: Have you tried rawname.c_str() in the printf?

A: What works
printf("%s", my_string.c_str());

What was wrong - synopsis
Short illustration (assumptions explained later):
std::string s {
   // members in unknown order
   size_type member:    13 00 00 00                       HEAP
   const char* member:  pointer C to ................ "this and that"
};

You print characters here ^^^^^^       not          here ^^^^^.

You can't pass non-POD data to functions - such as printf() - that accept arbitrary numbers of arguments using ....  ("..." parameters is a feature C++ inherits from C, and it's inherently unsuitable for use with complicated C++ objects).
You can even compile that?
My GCC compilers don't like this:
printf("rawname: %s", rawname);

GCC 4.5.2 error:
cannot pass objects of non-trivially-copyable
type 'struct std::string' through '...'

GCC 4.1.2 warning + runtime behaviour:
cannot pass objects of non-POD type 'struct std::string'
through '...'; call will abort at runtime

# ./printf_string
zsh: illegal hardware instruction  ./printf_string

They won't compile it, because there is no standard way to pass objects using ....  The compiler can't work out from simply ... whether they're needed by value or by reference/pointer, so won't know what code to generate.
But your compiler bravely did something.  Let's consider what the std::string object looks like for a moment, then return to how your compiler might have received and accessed it.
The gizzards of a std::string object
The internals of a std::string aren't specified, but typically contain any of:

*

*a member recording the current size OR a pointer past the end of the string (ala end())

*

*either allows simple calculation of the other, but the couple Standard Library implementations I've checked optimise for a pointer/end() member and calculated size() - works better with idiomatic iterator loops

*a pointer to a character buffer on the heap (in practice it's likely kept NUL terminated and c_str() returns it directly, but this pointer - available via the data() member function, is allowed by the Standard to address non-NUL terminated text, so theoretically it could have a NUL terminator appended only when c_str() is called, or c_str() might copy the text elsewhere then append the NUL and return a pointer to that new buffer)

*a "short string optimisation" data buffer so strings of only a few characters need not use the heap

and/or

*

*a pointer to some reference-counted object elsewhere (that has the members above + a reference counter, a mutex, ...?)

Example: a simple string implementation storing text
These could be in any order.  So, the simplest possibility is something like:
std::string s = "this and that";

Now,

*

*"this and that" is a string literal, let's say at address "A"; this data is copied into the string; the string does not remember where it got it from

*s is the actual std::string object, let's say at address "B"; let's imagine it's the simplest possible:

*

*size_type size_; (will hold the value 13, being strlen("this and that"))

*const char* p_data_; will point to some newly allocated heap memory - let's say at address "C" - into which "this and that\0" has been copied

Crucially, address "A", address "B" and address "C" are different!
How printf() sees the std::string
If we had a bad compiler that would attempt to pass our std::string object to printf(), then there are two things printf() might receive instead of the const char* that "%s" tells it to expect:
1) a pointer to the std::string object, i.e. address "B"
2) sizeof(std::string) bytes of data copied from address "A" to some stack address "B" and/or registers where printf() would expect it if it could handle these things ;-P
printf() then starts printing the bytes from that address as if they're characters until it finds a 0/NUL byte:

*

*for scenario 1 above, it prints the bytes in the object, for example:

*

*say size_type is 4 bytes and at the start of the object; with size 13 it might be 13, 0, 0, 0 or 0, 0, 0, 13 depending on whether the machine uses the big-endian or little-endian storage convention... given it stops at the first NUL, it would print character 13 (which happens to be an ASCII carriage-return/CR value, returning the cursor to the start of line) then stop, or it might print absolutely nothing.  In your own case your string content were different, so it would have printed some other garbage, but probably only a character or two before hitting a 0/NUL.

*say a const char* to the heap-allocated buffer at "C" happens to be at the start of the object, then the individual characters in that address would be printed: for 32-bit pointers that's probably 4 garbage characters (assuming none of them happen to be 0/NUL), for 64-bit it'll be 8, then it'll continue with the next field in the std::string (likely a end()-tracking pointer, but if it's a size_type field that's much more likely to have a 0/NUL).

*printf() might interpret the first four bytes of the std::string object's data as a pointer to further textual data... this is a different from 1): say the size_type member was first and the value was 13, printf() could mis-interpret that as a const char* to address 13, then attempt to read characters from there.  This is practically guaranteed to crash before printing anything (on modern OSes), so it's very unlikely that this behaviour actually happened, which leaves us with "1".


text:
Q: Is there a way to have an outlook 2007 email template automatically update the subject with the current date? I send out an email every morning in a specific format.
To = The same group every day
Subject = "Scrum 25-SEP-09" (replace the date with the current date)
Body =
Yesterday:
     - <what I did yesterday>
Today:
     - <what I did today>
Roadblocks:
     - <stuff in my way of getting things done>

I would like to save this as an email template that I can quickly edit every day and send it out.
My question:
Is there a way to have an outlook 2007 email template automatically update the subject with the current date?

A: Select Design a Form. from the Tools\Forms menu
In the Standard Forms Library Open the Message form.  This will open a standard mail form.
Right-click on the Subject text input box and select Properties.
From the Properties dialogue box click on the Value tab.
Edit the initial value and enter:
'Scrum ' & Date()

You can then make any other changes you want to the form and test it with the Run this Form option.
If you are happy with the result you are ready to Publish.  Select the Publish option and select Publish Form As.. and save it in your Personal Forms Library.
When you want to use it you can select it from File\New\Choose Form and open it from your 'Personal Forms Library' (there may be a quicker way to do this)

redpajama_set_name: RedPajamaStackExchange


text:
Q: how do i set value of a Jaxb XMLelement? my question is: from the xml scheme :
<topnode>
    topNodeValue
   <bottomnode/>
</topnode>

generated class with Jaxb looks like
class topnode {
    List<bottomnode> bottomnodeList;
}

Which does not generate the value field to set value for topnode.
How can I acheive this? Thanks.

A: When the contents of an element contain both character and element data it is called mixed content.  In JAXB (JSR-222) this is mapped with the @XmlMixed annotation like:
class topnode {
    @XmlMixed
    String text;

    List<bottomnode> bottomnodeList;
}

The use of mixed content can be tricky, since you may get unexpected results due to text nodes used for formatting.  For a more detailed explanation see the following answer to a similar question.

*

*https://stackoverflow.com/a/11099303/383861

A: For text nodes, use @XmlValue annotation. Something like this:
class topnode {

    @XmlValue
    String topNodeValue;

    List<bottomnode> bottomnodeList;

}

As a suggestion, try to respect java naming standards and if it doesn't match the xml elements use the name attribute of the @Xml... annotations.


text:
Q: Gettign the error :Failed to load Main-Class manifest attribute from jaxb I am trying to do
java -jar jaxb-api-1.5.jar

I am getting the following error :

Failed to load Main-Class manifest
  attribute from jaxb-api-1.5.jar

I am running it in jdk1.4 env.
Why this is happening and how can it be recitified ?
What i am trying to do is generate the classes from xsd using jaxb xjc command in jdk1.4 env. If there is other way then please let me know
Any pointer will help
Thank

A: I downloaded this jaxb-api-1.5.jar and its MANIFEST.MF does not contain any Main-Class attribute in deed. I think this jar is not intended to be executed via java -jar call.
There are some resouces on the JAXB site. You can download the latest stable version from here. It contains shell scripts / batch programs to do what you need.


text:
Q: Searching through a list of child subjects So my issue is trying to use the getName() and getPhone() methods (in class Contact) in the main method.
I don't know how to use them in this context with all 3 classes.
Here is what the program is supposed to be doing
Apologies if this is not too concise, I just started programming recently.
public class LookupPhonebook{
    public static void main(String[] args) {
        Phonebook phonebook = new Phonebook("Sam Johnson");
        phonebook.addContact(new Contact("Kelly Wong", "(02) 12345678"));
        phonebook.addContact(new Contact("Richard Jackson", "(02) 87654321"));
        phonebook.show();

        String searchName = Input.askString("Enter a contact name: ");
        phonebook.findContactByName(searchName);
        if (searchName.equals(phonebook.getName())) {
            System.out.println("Phone number is " + phonebook.getPhone());
        }
        else {
            System.out.println(searchName + " not found");
        }
    }
}

import java.util.*;
public class Phonebook {
    private String owner;
    private ArrayList<Contact> contacts = new ArrayList<Contact>();

    public Phonebook(String owner) {
        this.owner = owner;
    }

    public void addContact(Contact contact) {
        contacts.add(contact);
    }

    public void show(){
        System.out.println(owner + "'s phonebook");
        for (Contact contact : contacts) {
            System.out.println(contact);
        }
    }

    public Contact findContactByName(String name) {
        for (Contact contact : contacts) {
            if (contact.getName().equals(name)) {
                return contact;
            }
            else {
                continue;
            }
        }
        return null;
    }
}

public class Contact {
    private String name;
    private String phone;

    public Contact(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String toString() {
        return name + ": " + phone;
    }
}

This method is the only one used in a class provided to help with the exercise.
/**
 * Asks the user the given question, waits for the user to enter a
 * single character at the keyboard, and then returns this character.
 *
 * @param question the question to be printed
 * @return the character that the user entered as an answer to the question
 */
public static char askChar(String question) {
    System.out.print(question + " ");
    return scanner.nextLine().charAt(0);
}

A: You need to store the result from findContactByName to a local variable following the instruction. The original program just throw away the result.
public static void main(String[] args) {
    Phonebook phonebook = new Phonebook("Sam Johnson");
    phonebook.addContact(new Contact("Kelly Wong", "(02) 12345678"));
    phonebook.addContact(new Contact("Richard Jackson", "(02) 87654321"));
    phonebook.show();

    String searchName = Input.askString("Enter a contact name: ");
    // 2. Search contact and store is local variable
    Contact result = phonebook.findContactByName(searchName);
    // 3. If we found contact
    if (result != null) {
        System.out.println("Phone number is " + result.getPhone());
    } else {
    // 4. No contact is found
        System.out.println(searchName + " not found");
    }
}


text:
Q: Elliptic, parabolic and hyperbolic Riemann surfaces: classification? In the book of Kra and Farkas on Riemann surfaces the following (slightly unusual) definition is given:
Definition IV.3.2 (Section IV.3). Let $M$ be a Riemann surface. We will call $M$ elliptic if and only if $M$ is compact. We will call $M$ parabolic if and only if $M$ is not compact and $M$ doesn't carry a non-negative subharmonic function. We will call $M$ hyperbolic if and only if $M$ does carry a negative non-constant subharmonic function.
Question. Is there some geometric way to characterise parabolic and hyperbolic surfaces? For example, suppose $M$ is a compact Riemann surface and $x_1,\ldots, x_n$ are points on it. Is the surface $M\setminus \{x_1,\ldots, x_n\}$ parabolic?

A: This is somewhat unusual terminology, but it is common in the theory of classification of open Riemann surfaces. The more standard notation
is $P_G$ for "parabolic", and $O_G$ for "hyperbolic".
The surface $M\backslash\{ x_1,\ldots,x_n\}$ is parabolic in this sense,
by the "removable singularity theorem" (a subharmonic function which is bounded from above in a punctured neighborhood of the point extends to a subharmonic function in the full neighborhood).
There are some criteria, especially, for surfaces of the form $M\backslash E$, where $M$ is compact and $E$ is a closed subset. But these criteria are not very geometric: they use capacity. Some results can be given in terms of Hausdorff measures of $E$ but they are not "necessary and sufficient".
Classical results can be found in the books
M. Tsuji, Potential theory in modern function theory, Maruzen, Tokyo, 1959 (there is an AMS reprint).
Ahlfors, Sario, Riemann surfaces, Princeton UP, 1960.


text:
Q: GitHub Collaboration Using the Shared Repository Model Can someone provide me with the cheat sheet for GitHub collaboration for a team of two who want equal access/rights to the repo. I am confused as to the need to use forking which appears to make sense for a large open source project with dispersed devs but seeems like overkill when I and my partner sit 10 feet from each other.
Thanks,
Doug

A: If you have a small team and want everyone to have access to the repo, you can just grant them collaborator permission in the repo's admin settings. Forking isn't required if your scenario doesn't require it. (Although forking can be useful, you're also partly right: if you have a small team and know all the other team members and don't mind giving them read/write access, there's no need to fork.)

A: the difference between the fork and pull model and the shared repository model could be explained by the Github.com:
(https://help.github.com/articles/about-collaborative-development-models/)

About collaborative development models
The way you use pull requests depends on the type of development model you use in your project.
There are two main types of development models with which you'd use pull requests. In the fork and pull model, anyone can fork an existing repository and push changes to their personal fork without needing access to the source repository. The changes can be pulled into the source repository by the project maintainer. When you open a pull request proposing changes from your fork's branch to a branch in the source (upstream) repository, you can allow anyone with push access to the upstream repository to make changes to your pull request. This model is popular with open source projects as it reduces the amount of friction for new contributors and allows people to work independently without upfront coordination.
In the shared repository model, collaborators are granted push access to a single shared repository and topic branches are created when changes need to be made. Pull requests are useful in this model as they initiate code review and general discussion about a set of changes before the changes are merged into the main development branch. This model is more prevalent with small teams and organizations collaborating on private projects.


text:
Q: MVVM WPF Command not firing I have MVVM WPF application. I create Menu via a separate service and set to load time.
My shell view which contains the menu is as follows:
<ItemsControl x:Name="MainToolbar" cal:RegionManager.RegionName="{x:Static inf:RegionNames.MainToolBarRegion}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="1,1,1,1" RenderTransformOrigin="-0.133,-5.917" Height="28" >
    <ItemsControl.RenderTransform>
        <TransformGroup>
            <ScaleTransform/>
            <SkewTransform/>
            <RotateTransform/>
            <TranslateTransform/>
        </TransformGroup>
    </ItemsControl.RenderTransform>

    <Menu IsMainMenu="True" Margin="0,0,0,0" Height="28" ItemsSource="{Binding Path=Menu}" Width="400">
        <Menu.Resources>
            <Style x:Key="ThemeMenuItemStyle" TargetType="MenuItem" BasedOn="{StaticResource KV_MenuItem}">
                <Setter Property="Header" Value="{Binding Path=Text}"></Setter>
                <Setter Property="Command" Value="{Binding Path=Command}"/>
                <Setter Property="CommandParameter" Value="{Binding Path=Text}"/>
                <Setter Property="IsCheckable" Value="True"/>
                <Setter Property="MinWidth" Value="80"/>
            </Style>
        </Menu.Resources>
    </Menu>
</ItemsControl>

MenuItem has a view model behind:
    public class MenuItemViewModel : NotificationObject
    {

        private string text;
        private ICommand command;
        private IList<MenuItemViewModel> menuItems;

        public MenuItemViewModel()
        {
            this.menuItems = new List<MenuItemViewModel>();
        }

        public string Text
        {
            get
            {
                return text;
            }
            set
            {
                if (text != value)
                {
                    text = value;
                    RaisePropertyChanged(() => this.Text);
                }
            }
        }

        public ICommand Command
        {
            get
            {
                return command;
            }
            set
            {
                if (command != value)
                {
                    command = value;
                    RaisePropertyChanged(() => this.Command);
                }
            }
        }

        public IList<MenuItemViewModel> MenuItems
        {
            get { return menuItems; }
            set
            {
                if (menuItems != value)
                {
                    menuItems = value;
                    RaisePropertyChanged(() => this.MenuItems);
                }
            }
        }
    }

My Relay command:
    public class RelayCommand : ICommand
    {
        #region Fields

        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;

        #endregion // Fields

        #region Constructors

        /// <summary>
        /// Creates a new command that can always execute.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion // Constructors

        #region ICommand Members

        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        #endregion // ICommand Members
    }

In menu  service, I assign the command object like follows:
...
            MenuItemViewModel app = new MenuItemViewModel();
            app.Text = "APP";
            app.Command = new RelayCommand(
                param => this.App(""),
                        param => true);

            MenuItemViewModel exit = new MenuItemViewModel();
            exit.Text = "Exit";
            exit.Command = new RelayCommand(
                        param => this.Exit(""),
                        param => this.CanExit
                        );
            app.MenuItems.Add(exit);
            mService.AddMenu(app);
...

My MenuItem is loading fine with assigned header text, but when I click a menu item it is not firing the relevant delegate methods such App("") or Exit("")
What I am doing wrong?


text:
Q: Swapping fragments of matrices Matlab I wrote a program implementing Gaussian Elimination with Complete Pivoting:
function x = gecp(A,b)

x = b;
n = length(A);
p = 1:n;
l = b;

for k = 1:n
    [i,j] = find(A(k:n,k:n)==max(abs(A(k:n,k:n)),[],'all'));

    i = i+k-1;
    j = j+k-1;

    [A(k,:),A(i,:)] = deal(A(i,:),A(k,:));
    [A(:,j),A(:,k)] = deal(A(:,k),A(:,j));
    [b(i),b(k)] = deal(b(k),b(i));

    [p(k),p(j)] = deal(p(j),p(k));

    temp = (k+1):n;
    l(temp) = A(temp,k)/A(k,k);
    b(temp) = b(temp)-l(temp).*b(k);

    A(temp,temp) = A(temp,temp)-l(temp).*A(k,temp);
end

x(n) = b(n)/A(n,n);
for k = (n-1):-1:1
    s = 0;
    for h = (k+1):n
        s = s+A(k,h)*x(h);
    end
    x(k) = (b(k)-s)/A(k,k);
end

x(p) = x;

And it is called like this:
N = 5; A = randn(N); b = randn(N,1); x = gecp(A,b)

Unfortunately all lines containing deal function (used for swapping rows of columns of matrices), give me following (or similar) error: "Unable to perform assignment because the size of the left side is 1-by-5 and the size of the right side is 0-by-5."
Unfortunately I have no idead why would the width of these vectors be changed to 0 as I wrote excatly the same thing on both sides.


text:
Q: NameError in UsersController#show I am currently working on the Ruby on Rails tutorial by Michael Hartl. I am trying to add a page for each user in my database by creating an HTML with embedded ruby page in the views directory. The code for show.html.erb is below:
    <%= @user.name %>, <%= @user.email %>

When I add the user to the user_controller.rb file, it looks like this:
class UsersController < ApplicationController
    def show
       @user = User.find(params[:id])
    end

    def new
    end
  end

When I run the rails server and click on open up the users/1 URL, I get a NameError complaining about an uninitialized constant. The error and trace is below:
NameError in UsersController#show
uninitialized constant UsersController::User

Rails.root: /usr/sample_app
Application Trace | Framework Trace | Full Trace

app/controllers/users_controller.rb:3:in `show'
actionpack (3.2.12) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.2.12) lib/abstract_controller/base.rb:167:in `process_action'
actionpack (3.2.12) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (3.2.12) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
activesupport (3.2.12) lib/active_support/callbacks.rb:414:in
.
.
.
.

Please let me know how to go about this because I cannot pass my spec tests with this error.  If anyone has any suggestions or insight I would greatly appreciate them.Thank you.

A: Controller file name should be users_controller.rb
As you mentioned in comment you don't have any User model defined. To create model run rails g model user name:string email:string. This will create User model with attributes name and email.
Try Rails scaffolding and see what files it creates(in controller, model and views ignore other files for now) and see the contents of those files. To use scaffold for creating User is as below:
     rails g scaffold user name:string email:string
     rake db:migrate


text:
Q: MS Access VBA - system crashing during do until loop I'm trying to calculate the number of days between two dates on a form, excluding weekends. However, the system keeps crashing every time it runs the do until loop. Can you spot where I might be going wrong within the code below?
Thanks for your help!
Private Sub total_text_Click()
Dim v_weekendcount As Integer
Dim v_date As Date
Dim dateone As Date
Dim datetwo As Date

v_date = Me.startdate_text.Value
v_weekendcount = 0

Do Until v_date = Me.enddate_text.Value
If Day(v_date) = vbSaturday Or Day(v_date) = vbSunday Then
v_weekendcount = v_weekendcount + 1
v_date = v_date + 1
End If
Loop

dateone = Me.startdate_text.Value
datetwo = Me.enddate_text.Value

Me.total_text.Value = DateDiff("d", dateone, datetwo) - v_weekendcount

End Sub

A: You probably had this in mind:
Do Until v_date = DateValue(Me.enddate_text.Value)
    If Weekday(v_date) = vbSaturday Or Weekday(v_date) = vbSunday Then
        v_weekendcount = v_weekendcount + 1
    End If
    v_date = v_date + 1
Loop

A: Just to exclude the possibility change the following line accordingly:
If (Day(v_date) = vbSaturday) Or (Day(v_date) = vbSunday) Then

A: You have the v_date = v_date + 1 call within the check for weekend. Doesn't this mean when it's not a weekend day it won't increment the date?


text:
Q: How to tell the GCC compiler that code should be generated serial, i.e., without jumps
How to tell the GCC compiler that code should be generated serial, i.e., without jumps.

I'm working on a project that embeds inline assembly into a C source code (or LLVM IR).
My implementation depends on code between the inline assembly to be written into  the executable as-is.
More formally, suppose I have the soure code (C or LLVM IR):
.label_start: (inserted as inline assembly)
inline_assembly0
source_code0
source_code1
inline_assembly1
...
.label_end: (inserted as inline assembly)
...

Now, this should not be compiled as:
.jmp_target:
source_code1
inline_assembly1
...
.label_end: (inserted as inline assembly)
...

.label_start: (inserted as inline assembly)
inline_assembly0
source_code0
jmp jmp_target

I.e. code should stay between labels without jumps reordering .label_start and .label_end.
Is there any way of telling GCC that everything between two inline assembly labels should stay "intact" without being reordered? My implementation depends on this.

A: If I understand your question, the GCC manual has a few words on this (emphasis added).

Note that the compiler can move even volatile asm instructions relative to other code, including across jump instructions. For example, on many targets there is a system register that controls the rounding mode of floating-point operations. Setting it with a volatile asm, as in the following PowerPC example, does not work reliably.
asm volatile("mtfsf 255, %0" : : "f" (fpenv));
sum = x + y;

The compiler may move the addition back before the volatile asm. To make it work as expected, add an artificial dependency to the asm by referencing a variable in the subsequent code, for example:
asm volatile("mtfsf 255,%1" : "=X" (sum) : "f" (fpenv));
sum = x + y;

Basically, you need a "dummy use" to prevent reordering.
We also use this sort of thing in Mono to extend the liveness of a reference in low-level GC code, ensuring it won't be prematurely freed if the GC interrupts a routine:
static inline void dummy_use (void *v)
    __asm__ volatile ("" : "=r"(v) : "r"(v));
}

A: try to disable optimization, gcc -O0 source.c


text:
Q: How to apply gradient color for an image using createjs? How to apply gradient fill using createjs? Below is the code for creating loading the image and i have changed the color using color filter but i want to apply the gradient color
 let rightContainer = new createjs.Container();
                let rightMain = new window.createjs.Bitmap(rightImage);
                // leftMain.scaleX = 800 / leftMain.image.width;
                rightMain.scaleY = 800 / rightMain.image.height;
                rightContainer.addChild(rightMain);
                rightMain.x = 300;
                rightMain.y = 0;
                this.layerImage = rightMain.clone();
                this.layerImage.alpha = 0.15;
                rightContainer.addChild(this.layerImage);
                rightMain.filters = [new window.createjs.ColorFilter(0, 0, 0, 1, 117, 111, 115, 0)];
                rightContainer.main = rightMain;
                rightMain.cache(0, 0, rightMain.image.width, rightMain.image.height);
                rightContainer.visible = false;
                this.stage.addChild(rightContainer);

A: What exactly are you trying to do? Apply a gradient on the color filtered image?
An approach you could use is:

*

*Draw a box with a gradient in it

*Cache it so it can be used as an AlphaMaskFilter

*Apply it to the bitmap as a filter

*Cache the bitmap to apply the filter.

I made an demo to show how it would work:
https://jsfiddle.net/lannymcnie/uog3hkpd/2/
// Draw a gradient in a shape:
s.graphics.lf(["#000", "rgba(0,0,0,0)"], [0, 0], 0,0,960,0);

// Cache the shape
s.cache(0,0,960,400);

// Add the alphamaskfilter + a color adjustment for fun
var col = new createjs.ColorMatrix().adjustHue(180);
bmp.filters = [
    new createjs.AlphaMaskFilter(s.cacheCanvas),
    new createjs.ColorMatrixFilter(col)
];

// Cache it to apply filters
bmp.cache(0,0,960,400);

The demo does a few other things, such as

*

*Adding a second bmp underneath that is not filtered

*Animating the ratio of the gradient (requires a re-cache)

I hope that helps you with your question. If you have any specific code or examples you need help with, please feel free to clarify.
Cheers,


text:
Q: React Native - modals overlay Modal 1 -- Component 1
              |
           Component 2
              |
Modal 2 -- Component 3

I have a scenario like the 'drawing' above, where component 3 is initialized in component 2 which is initialized in component 1.
Component 1 and 3 each holds a component with a modal.
If component 3's modal is open. The modal from component 1 is hidden behind it if it's opened.
I however want it to be on top of the stack and in the front view.
I tried with ordering things in the code, and i tried with zIndex with position either absolute or relative.
{position: 'relative/absolute', overlay: {zIndex: 99}};
but neither seems to work.
I've looked into similar posts but was unable to find an answer that work's.
How can i force modal 1 to always be visible if other modals are opened from a 'higher' component in the stack

A: You could use Modal component or some other module.
But if you want to create your own modal you can follow this pattern.
in your main component App, have 2 child components
<App>
  <Home /> //All components/navigation are here
  {
    isModalOpen && <Modal />
  }
</App>

Set Modal style to something like position:absolute, left: 0, right: 0, top: 0, bottom: 0


text:
Q: Having trouble launching a JavaFx Gui Program Im having trouble launching a simple GUI i javafx and its giving me all sorts of errors. Can anyone help me to know whats going wrong
This is the error that im getting

Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
    at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NoClassDefFoundError: javafx/css/StyleableObjectProperty
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2413)
    at java.lang.Class.getConstructor0(Class.java:2723)
    at java.lang.Class.getConstructor(Class.java:1676)
    at sun.reflect.misc.ConstructorUtil.getConstructor(ConstructorUtil.java:38)
    at javafx.fxml.JavaFXBuilderFactory.getBuilder(JavaFXBuilderFactory.java:121)
    at javafx.fxml.FXMLLoader$InstanceDeclarationElement.constructValue(FXMLLoader.java:805)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:565)
    at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2314)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2131)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2028)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2744)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2723)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2709)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2696)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2685)
    at oasis.estock.OasisEstock.start(OasisEstock.java:27)


text:
Q: Laravel Livewire Detect Overlapping Time I am currently trying to build a conflict detection feature for Schedule Manager. Schedules with conflicts will have red background.
The problem is with overlapping time intervals which I would also like to be flag as conflict.
Based on the table below the two schedules should be mark red since 7:00-8:30 is between 7:00-10:30.
This is how I constructed the table with sample data. Restructuring the table for now is not an option.
room|  day |  c_time|
105 | M-W   | 7:00-8:30|
105 |W  |   7:00-10:30  |
Controller
        foreach($sched->get() as $keyG=>$pG)
        {
          $pGx=explode("-",$pG->day);

          foreach($pGx as $xKey=>$xx)
          {
              $classDayTime[]=array('s_id'=>$pG->id,'s_day_time'=>$pGx[$xKey].$pG->c_time.$pG->room);
          }
        }                $conflictRoom=array_count_values(array_column($classDayTime,'s_day_time'));

Blade
foreach($sched->paginate(20) as $key=>$p)
        {

          $res = explode("-",str_replace([")","("],"",$p->c_time));
                ?>

                <tr class="
                     <?php
                $e=explode("-",$p->day);

                              foreach($e as $dKey=>$d)
                              {

                                  $dt=$d.$p->c_time.$p->room;

                              foreach($$conflictRoom as $ky=>$k)

                              {

                                  if($dt==$ky)
                                  {
                                    if($dt==$ky)

                                          if($k != 1)
                                          {

                                            echo "divide-y dark:divide-white text-black text-s text-center bg-red-400";
                                          }

                                          else

                                          echo " ";

                                  }

                              }
                              }

                            ?>
                ">

A: If you take the values like init_time and end_time after explode the string provided
$explode_first = explode("-", "7:00-8:30");
$first_init_time = $explode_first[0]; // "7:00"
$first_end_time = $explode_first[1]; // "8:30"

$explode_eval = explode("-", "7:00-10:30");
$eval_init_time = $explode_eval[0]; // "7:00"
$eval_end_time = $explode_eval[1]; // "10:30"

if($eval_init_time < $first_end_time && $eval_end_time > $first_init_time)
   // it's overlaping

And for sure you must cast the values to time objects before comparing them.


text:
Q: Decompose Point-Spread Function into Seidel Aberration/Zernike Polynomials I have measured the point spread function (PSF of a microscope) and I want to quantify it. For that purpose I want to fit my PSF data to the primary Seidel optical aberrations (or Zernike Polynomials, if it makes it easier). Something similar already exists on the Mathematica Demonstration center, but it is the opposite of what I want.
The PSF data is stored in TIFF files, and consists of images of sub-resolution dots taken at various focal distances.


text:
Q: Hybris convert Product to VariantProduct I extract from an WebService several Products which I convert to ProductModel, however, some of these products are "variants".
I need to manually convert a ProductModel to VariantProductModel, is there any OOTB way to achieve this ?

A: You cannot change an object from Type. This is partly because the datatype is tied into the PK of your object.
If you want to change the type, you will need to create a new instance of the variantProductModel, copy all  the fields and remove the original product


text:
Q: Multi line string in Django 'include' statement I'm trying to be DRY with my Django templates, and have some code that I mix with CSS for a simple hover-over popup. I'd like to reuse the code, but the contents of my popup will be HTML that may well span over multiple lines. Is it possible to stuff multi-line strings into a template variable?
I tried doing something funky with blocks and block.super but that only seems to work when extending (not include)
Here's an example of what I'd like to do. Is it possible?
index.html

My Popup

 {% include "snippets/popup.html" with class="p" spantext="Hover me" popupdiv="""

This is a popup!

Something

Something else

 """
%}

snippets/popup.html

     {{ spantext }}

         {{ popupdiv }}

I know it's not possible to have multi-line template tags in Django, but is there any way round this, other than squashing all my div html onto one line, and escaping any quotes?
Cheers

A: It turns out "Parsing until another template tag" is what I was after. http://www.djangobook.com/en/2.0/chapter09.html
Here's my code:
tags.py (in the templatetags folder)
from django import template
from django.template.loader import get_template
from django.template.base import Node, TemplateSyntaxError

register = template.Library()

class PopupNode(Node):
    def __init__(self, nodelist, class_name, spantext):
        self.nodelist = nodelist
        self.class_name = class_name
        self.spantext = spantext

    def render(self, context):
        popup_html = get_template("ordersystem/snippets/popup.html")
        context.update({
            'class' : self.class_name,
            'spantext' : self.spantext,
            'popupdiv' : self.nodelist.render(context)
        })
        return popup_html.render(context)

@register.tag('popup')
def show_popup(parser, token):
    nodelist = parser.parse(('endpopup',))
    tokens = token.split_contents()
    if len(tokens) != 4:
        raise TemplateSyntaxError("show_popup is in the format 'popup with class=X spantext=Y")
    try:
        context_extras = [t.split("=")[1].strip('"') for t in tokens[2:]]
    except IndexError:
        raise TemplateSyntaxError("show_popup is in the format 'popup with class=X spantext=Y")
    parser.delete_first_token()
    return PopupNode(nodelist, *context_extras)

Then within my html file I can just do:
{% popup with class_name=management spantext=Manage %}

This is a popup!

Something

Something else

{% endpoup %}

A: The best way should be to create a templatetags in your module with an inclusion tag.
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
So imagine your are YourModule yourModule with a folder templatetags and the file popup_tag.py
yourModule/
---- views.py
---- models.py
---- templates/
     ---- snippet/
          ---- popup.html
---- templatetags/
     ---- __init__.py
     ---- popup_tag.py

Your popup_tag.py could look like the following lines :
from django import template

register = template.Library()

def show_pop_up(class, span_text, popupdiv):
    return {'class': class,
            'span_text': span_text,
            'pop_up_div': pop_up_div}

register.inclusion_tag('snippet/popup.html')(show_popup)

Then, you just have to call your tag in your template index.html.
{% load popup_tag %}

{% show_popup "class" "span_text" "popupdiv" %}


text:
Q: How to enable offline data in firestore for web I want to enable offline data in my project.
I found the right code for this but I don't know where to implement the code
I implement the code inside the firebaseConfig.js file:
import firebase from 'firebase'
import 'firebase/firestore'

// firebase init
// init code goes here
var config = {
 apiKey: '',
 authDomain: '',
 databaseURL: '',
 projectId: '',
 storageBucket: '',
 messagingSenderId: ''
}
firebase.initializeApp(config)

firebase.firestore().enablePersistence()
 .then(function () {
   // Initialize Cloud Firestore through firebase
   var db = firebase.firestore();
 })
 .catch(function (err) {
   console.log(err)
 })

 // firebase utils
 const db = firebase.firestore()
 const oldRealTimeDb = firebase.database()
 const auth = firebase.auth()
 const currentUser = auth.currentUser

 // date issue fix according to firebase
 const settings = {
   timestampsInSnapshots: true
 }
 db.settings(settings)

 // firebase collections
 const usersCollection = db.collection('users')
 const postsCollection = db.collection('posts')

export {
 db,
 auth,
 currentUser,
 postsCollection,
 usersCollection

}
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import {store} from './store'
import './registerServiceWorker'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css' // Ensure you are using css-loader
const fb = require('./firebaseConfig.js')

Vue.config.productionTip = false

export const bus = new Vue()

Vue.use(Vuetify)

let app
fb.auth.onAuthStateChanged(user => {
 if (!app) {
  app = new Vue({
   el: '#app',
   store,
   router,
   template: '<App/>',
   components: {
     App
   },
   render: h => h(App)
 }).$mount('#app')
}
})

I got this error:

A: The sample code provided in the documentation suggests that you should call enablePersistence() and possibly make note if it fails for some given reason:
firebase.initializeApp({
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
  projectId: '### CLOUD FIRESTORE PROJECT ID ###',
});

firebase.firestore().enablePersistence()
  .catch(function(err) {
      if (err.code == 'failed-precondition') {
          // Multiple tabs open, persistence can only be enabled
          // in one tab at a a time.
          // ...
      } else if (err.code == 'unimplemented') {
          // The current browser does not support all of the
          // features required to enable persistence
          // ...
      }
  });

Subsequent queries after calling enablePersistence() will be internally queued until it fully completes, which means that the query may or may not be using locally cached data, depending on the result of enablePersistence().  If it's important to your app to be able to use local persistence, you may wish to wait on its result (triggering on the returned promise) before performing the query.

A: Just remove the second firebase.firestore() and call the enablePersistence as follows:
import firebase from 'firebase'
import 'firebase/firestore'

// firebase init
// init code goes here
var config = {
 apiKey: '',
 authDomain: '',
 databaseURL: '',
 projectId: '',
 storageBucket: '',
 messagingSenderId: ''
}
firebase.initializeApp(config)

const db = firebase.firestore();
const auth = firebase.auth();
const currentUser = auth.currentUser;

// date issue fix according to firebase
const settings = {
  timestampsInSnapshots: true
};
db.settings(settings);
db.enablePersistence();

// firebase utils
//const db = firebase.firestore() // <---- Remove this line
const oldRealTimeDb = firebase.database()
const auth = firebase.auth()
const currentUser = auth.currentUser


text:
Q: Track changes in column paste to new sheet with date it changed Can you please help me make a VBA Script that will track Column A:B in sheet1
If there is a change in existing values (Either A, B or Borth), or if a whole new value is added it will take the changes and posts it in sheet 2 A:B
Sheet2 need lastrow so i always have "Log" of the changes and it need to paste time when the change happened.
Thank you so much


text:
Q: Add class using Jquery without prepending '.' Adding class in jquery is pretty straight forward. You just have to do this:
$('#id').addClass('class_name')

Problem is it puts a . before the class name in the div. Any way to avoid that. I want to put the class name without .


text:
Q: interactive plot with cursor hovering to show coordinates (python, pdf) First timer here :)
I would like to create an interactive plot using matplotlib such that when the mouse hovers over a certain point in the plot the coordinates are shown.
Ideally, I would like to save this plot as a pdf file or other format that can be opened by people with no python installed on their computers, and still keep the interactive behavior of the plot.
I have tried to use mplcursors.cursor(hover = True) but was not able to keep the 'interactive behavior' of the plot when saved to pdf or png.
What would be the best way to go about this?
Cheers!


text:
Q: Conditional Subtraction of rows in Python Pandas Dataframe I am trying to solve a problem at hand as explained. I have a Dataframe as shown below:
Date    Item    Type    Qty Price
1/1/18  Orange  Add     100 25
5/1/18  Orange  Add     20  40
8/1/18  Orange  Add     40  20
18/1/18 Orange  Add     10  35
27/2/18 Orange  Sub     100 55
15/4/18 Orange  Sub     30  45

and I want to get the intermediate Dataframe like below:
Date    Item    Type    Qty Price   Diff
1/1/18  Orange  Add     0   25      30
5/1/18  Orange  Add     0   40      5
8/1/18  Orange  Add     30  20      25
18/1/18 Orange  Add     10  35

and then the final Dataframe I want it like this below:
Date    Item    Type    Qty Price
8/1/18  Orange  Add     30  20
18/1/18 Orange  Add     10  35

NOTE: Diff is a difference of Sub and Add Price. And Qty is also updated with Qty of Sub subtracted from Qty of Add.
Could anyone of you please help with the way it can be achieved. I was trying with groupby, apply and transform but till now I have not got this.
I have below code, still in development and not complete:
def FruitSummary():
    df = pd.DataFrame([
               ['01/1/18',   'Orange',   'Add',  100,    25],
               ['05/1/18',   'Orange',   'Add',   20,    40],
               ['08/1/18',   'Orange',   'Add',   40,    20],
               ['18/1/18',   'Orange',   'Add',   10,    35],
               ['27/2/18',   'Orange',   'Sub',  100,    55],
               ['15/4/18',   'Orange',   'Sub',   30,    45],
               ['02/1/18',   'Banana',   'Add',  110,     7],
               ['04/1/18',   'Banana',   'Add',   20,     9],
               ['11/1/18',   'Banana',   'Add',   40,     4],
               ['10/2/18',   'Banana',   'Add',   10,     3],
               ['15/3/18',   'Banana',   'Sub',  100,     9],
               ['15/4/18',   'Banana',   'Sub',   50,     8],
               ['10/3/18',   'Kiwi',     'Add',   80,    29],
               ['12/3/18',   'Berry',    'Add',   25,     5],
               ['18/4/18',   'Berry',    'Add',   15,     8]],
       columns=['Date',      'Item',     'Type', 'Qty',  'Price'])

    print(df)

    def fruit_stat(dfIN):
        print(dfIN)
        print((dfIN['Type'] == 'Sub').unique(), (dfIN['Type'] == 'ODD').unique())

        if len(dfIN) > 1 and (True in (dfIN['Type'] == 'Sub').unique()):
            print(dfIN['Item'].iloc[1], "'len > 1'", "'Sub True'")

dfFS = df.groupby(['Item']).apply(fruit_stat)
print(dfFS)

A: I am able to find some solution, not sure if it is optimal or there might be better solution for the same.
df = pd.DataFrame([['01/1/18',   'Orange',   'Add',  100,    25],
                   ['05/1/18',   'Orange',   'Add',   20,    40],
                   ['08/1/18',   'Orange',   'Add',   40,    20],
                   ['18/1/18',   'Orange',   'Add',   10,    35],
                   ['27/2/18',   'Orange',   'Sub',  100,    55],
                   ['15/4/18',   'Orange',   'Sub',   30,    45],
                   ['02/1/18',   'Banana',   'Add',  110,     7],
                   ['04/1/18',   'Banana',   'Add',   20,     9],
                   ['11/1/18',   'Banana',   'Add',   40,     4],
                   ['10/2/18',   'Banana',   'Add',   10,     3],
                   ['15/3/18',   'Banana',   'Sub',  100,     9],
                   ['15/4/18',   'Banana',   'Sub',   50,     8],
                   ['10/3/18',   'Kiwi',     'Add',   80,    29],
                   ['12/3/18',   'Berry',    'Add',   25,     5],
                   ['18/4/18',   'Berry',    'Add',   15,     8],
                   ['16/3/18',   'Cherry',   'Add',   25,     5],
                   ['21/4/18',   'Cherry',   'Sub',   25,     8],
                   ['19/3/18',   'Grapes',   'Add',   25,     5],
                   ['23/4/18',   'Grapes',   'Sub',   15,     8]],
          columns=['Date',      'Item',     'Type', 'Qty',  'Price'])

def FruitSummary(df):
    df['CumSum'] = df.groupby(['Item', 'Type'])['Qty'].cumsum()
    print(df)

    def fruit_stat(dfg):
        if dfg[dfg['Type'] == 'Sub']['Qty'].count():
            subT = dfg[dfg['Type'] == 'Sub']['CumSum'].iloc[-1]
            dfg['Qty'] = np.where((dfg['CumSum'] - subT) <= 0, 0, dfg['Qty'])
            dfg = dfg[dfg['Qty'] > 0]
            if(len(dfg) > 0):
                dfg['Qty'].iloc[0] = dfg['CumSum'].iloc[0] - subT

        return dfg

    dfFS = df.groupby(['Item'], as_index=False).apply(fruit_stat).drop(['CumSum'], axis=1).reset_index(drop=True)
    print(dfFS)

And the above code produces the answer like this below:
      Date    Item Type  Qty  Price
0  11/1/18  Banana  Add   20      4
1  10/2/18  Banana  Add   10      3
2  12/3/18   Berry  Add   25      5
3  18/4/18   Berry  Add   15      8
4  19/3/18  Grapes  Add   10      5
5  10/3/18    Kiwi  Add   80     29
6  08/1/18  Orange  Add   30     20
7  18/1/18  Orange  Add   10     35


text:
Q: Is it possible to write tests for mobile native apps using appium and nightwatchjs? Is it possible to write tests for mobile native apps using appium and nightwatchjs?
I found a lot of resources for web automation but not a single one for Native mobile apps. Official docs also not saying anything about it.

A: There is lot of mobile native app automation tools and documents available in market,
Please find below tools, supported platforms and its documentation
1.Appium
Native : Android & iOS
Mobile web app : Android chrome & iOS safari

Documentation link :http://appium.io/documentation.html?lang=en
2.Calabash
Native only : Android & iOS

Website : http://calaba.sh/
Setup Video : https://www.youtube.com/watch?v=ykZ3HIYOOnQ
3.Robotium
Native only : Android only

Github wiki Documenation : https://github.com/RobotiumTech/robotium/wiki/Getting-Started
4.Espresso
Native only : Android only

Documentation link : https://google.github.io/android-testing-support-library/docs/
5.Webdriver.io
Native : Android & iOS
Mobile web app : Android chrome & iOS

Note : Internally it's pointing to appium only
Documentation link : http://webdriver.io/
6.Selendroid
Native : Android only
Mobile web app : Android only

Documentation link : http://selendroid.io/
7.Python uiautomator
Native : Android only

Github link : https://github.com/xiaocong/uiautomator
Above tools are widely used in mobile app automation currently.

A: I recommend Selendroid or Appium for testing Native apps, If you are good with the Selenium Webdriver go for this. because Selendroid and Appium are using similar Selenium codes.
Using Appium you can test both ios and Android native apps.
https://www.youtube.com/watch?v=eRddxh-4u5k
Selendroid is mainly for Android Apps
follow this tutorial
http://www.guru99.com/introduction-to-selendroid.html
These are two links i found most suitable for learning these technologies. hope this will help you :-)

A: For native app testing, you must change launch_url to http://127.0.0.1:4723/wd/hub, port to 4723 and keep browserName empty.
You may follow the following tutorial to get an idea about native app testing using Nightwatchjs:
https://www.utest.com/articles/android-native-app-testing-by-nightwatchjs


text:
Q: md5 check on inputstream without saving as file I am developing a page to upload files. I am using spring framework 3 multipartFile. I only want to save this uploaded file if it has been changed form its original version in the server.  Is there a way I can do MD5 check without saving this uploaded file in a temporary location?
Thanks,
Vasanta

A: You can use MultipartFile's getBytes() method to read the contents as byte array, and then:
byte[] uploadBytes = upload.getBytes();
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] digest = md5.digest(uploadBytes);
String hashString = new BigInteger(1, digest).toString(16);
System.out.println("File hash: " + hashString);

However, according to the documentation the file can potentially still be saved to a temporary folder (but Spring would clean it up afterwards):

The file contents are either stored in memory or temporarily on disk.


text:
Q: Use the definition of a limit to prove that the limit is equal to zero?
All I can think of to start is to state that:
$$|n-∞| < \delta \Rightarrow |(c/n^2)-0| < \epsilon$$
But I don't know where to go from there

A: You want to prove that $(C/n^2)\to 0$ as $n\to\infty$.
You are required to use the definition that: $$
\lim_{n\to\infty}a_n = l \quad\iff\quad \forall \epsilon>0:\exists N:\forall n>N: \big(\lvert a_n-l\lvert < \epsilon \big)
$$
Since $a_n=C/n^2$ and $l=0$ you must show that $$
\lim_{n\to\infty}\frac C{n^2} = 0 \quad\iff\quad \forall \epsilon>0:\exists N:\forall n>N: \big(\Big\lvert \frac C{n^2}\color{silver}{-0}\Big\rvert < \epsilon \big)$$

A: Look at the definition they have given. You want $\ell=0$ in this case. Given any $\epsilon>0$, you have to find some $N$ such that for any $n>N,\; \left|\frac C{n^2} - \ell\right|<\epsilon$. See if you can work from there.

A: Danielle,
First, the presence of the constant $C$ is immaterial to the limit. You can factor is out and reduce the question to $C \lim_{n \to \infty} \dfrac{1}{n^2} = 0 \implies \lim_{n \to \infty} \dfrac{1}{n^2} = 0$.Then your $|a_n - \ell|$ is fairly straightforward, as $\ell = 0$ means that $|a_n - 0| = a_n$. Choose such an $\epsilon = \dfrac{1}{N} > 0$. Now, just solve for $n$; so that for sufficiently large $n$ we have $| \dfrac{1}{n^2} | < \dfrac{1}{N^2} < \epsilon^2 < \epsilon \space \forall n > N$.

A: $lim_{n \to \infty}$ $C/n^2=0$ <=> $C*lim_{n\to\infty}1/n^2=0$
<=> $lim_{n\to\infty} 1/n^2=0$
Given any $\epsilon \gt 0$, there is some N such that for any $n \gt N$,∣∣$1/n^2−0$∣∣$\lt\epsilon$.
$∣∣1/n^2−0∣∣\lt\epsilon
<=> ∣∣1/n^2∣∣\lt\epsilon
<=> 1/n^2\lt\epsilon
<=> n^2 > 1/\epsilon
<=> n \gt \sqrt{1/\epsilon}
$
Let $N = \sqrt{1/\epsilon}$. Then whenever $n\gt N$, $∣∣1/n^2−0∣∣\lt\epsilon$


text:
Q: Is there a name for the testing technique I use? In case of things that are hard to test using traditional xUnit-style methods, such as various converters, XSLT, etc. I often employ technique based on output comparison. The test program produces some output when it's run for the first time. I make sure it's correct and save it for the later use. On the following runs the program compares the new output with the previously saved output and shows any differences. After that I may either fix the program to make the output match again or (and this is important!) I may accept the changes so that the data used for comparison are updated.
Of course, there are other aspects, such as using different preprocessing for comparison and for diffs, e.g. XML is compared using canonical representation, JSON is parsed first, s-expressions are read using lisp reader etc. while pretty-printed represention is used for diffs. The comparison can be re-run using some specified transformations such as removing parts of the output.
I use such techniques both for python where the driver program calls WSGI application using requests defined in a test script and for some Common Lisp programs including a converter from random/broken HTML to a proprietary XML format and a linear accelerator control system where control algorithms produce s-expr based output as they execute using device simulators that produce some output too.
The problem is, I don't know what is exact name for such technique. I know it's used in other places and there is even a testing framework called izh-test that uses something similar. But I've never heard of any specific name for it, including the 'accept changes' part. Data-driven testing? Seems like not quite. Any suggestions?

A: ABT, or Adaptive Baseline Testing. You establish a baseline, but have a provision for adapting that baseline depending on test results.
The problem with ABT, is that I completely made it up. I'm not sure if there's a name in wider use for this, but look forward to reading other answers to see if anyone else knows.

A: What you do is Black Box Test.
If you have a Golden Copy which you have validated ("I make sure it's correct and save it for the later use.") and at some point you decide to replace it, you are to validate it again.

*

*If you replace it because the new golden copy is better or has more information, then its just an update.

*If you replace it because the old golden copy was faulty, then your previous validation was no good, you have a SW Test Issue and you may need to rerun other tests that may use this golden copy.

*If you replace it because the data in the old copy is not good anymore, then something has changed in your program, which means you have a change or fix or something that invalidates your old golden copy and requires you to validate the new one.

In any case, what you should do is validate the new golden copy ("I may accept the changes so that the data used for comparison are updated").
Whatever situation you are in, it still is Black Box Test. You have an input, you get an output, you compare the output against expected results.


text:
Q: What's the difference between a nested path and fileset? I have been googling for the "Differences between fileset and path" article for some time, but have found nothing useful.
For example, what is the difference between the following (say, there is a someDir directory, which contains .jar files and has no subdirectories):
<path id="somePathId">
    <pathelement path="someDir"/>
</path>

<path id="someId">
  <path refid="somePathId" />
</path>

and
<path id="someId">
  <fileset dir="someDir">
     <include name="*.*">
  </fileset>
</path>

?

A: The major difference between a <path> and a <fileset> is that in <fileset> you can specify if you want to include or exclude certain type of files (Basically, its a group of files within a path... not necessary all the files), for eg:
<path id="someId">
  <fileset dir="someDir">
     <include name="*.java">
     <include name="*.properties">
  </fileset>
</path>

A: They are used in different situations.
fileset is used to specify a group of files. You can use selectors and patternsets to get only the files you want.
classpath is used to specify classpath references. classpath can be specified with a single jar (location="..."), a ; or : separated list of jars (path="...") or with nested resource collections (like fileset).
Also if you want to debug them, it is different:
<echo message="Build-path: ${toString:build-path}" />

vs
<property name="debug.classpath" refid="classpath"/>
<echo message="Classpath = ${debug.classpath}"/>

As for your scripts,
<path id="somePathId">
    <pathelement location="someDir"/>
</path>

I did not test it but according to the documentation path= expects a ; or : separated list of jars. This is not the same as your second example.


text:
Q: Automate Retrieval and Storing Kubeconfig File After Creating a Cluster with Terraform/GKE When I use Terraform to create a cluster in GKE everything works fine and as expected.
After the cluster is created, I want to then use Terraform to deploy a workload.
My issue is, how to be able to point at the correct cluster, but I'm not sure I understand the best way of achieving this.
I want to automate the retrieval of the clusters kubeconfig file- the file which is generally stored at ~/.kube/config. This file is updated when users run this command manually to authenticate to the correct cluster.
I am aware if this file is stored on the host machine (the one I have Terraform running on) that it's possible to point at this file to authenticate to the cluster like so:
provider kubernetes {
  # leave blank to pickup config from kubectl config of local system
  config_path = "~/.kube/config"
}

However, running this  command to generate the kubeconfig requires Cloud SDK to be installed on the same machine that Terraform is running on, and its manual execution doesn't exactly seem very elegant.
I am sure I must be missing something in how to achieve this.
Is there a better way to retrieve the kubeconfig file via Terraform from a cluster created by Terraform?

A: Actually, there is another way to access to fresh created gke.
data "google_client_config" "client" {}

provider "kubernetes" {
  load_config_file = false
  host = google_container_cluster.main.endpoint
  cluster_ca_certificate = base64decode(google_container_cluster.main.master_auth.0.cluster_ca_certificate)
  token = data.google_client_config.client.access_token
}

A: Basically in one step create you cluster. Export the kube config file to S3 for example.
In another step retrieve the file and move to the default folder. Terraform should work following this steps. Then you can apply your obejcts to cluster created previuoly.
I am deplyoing using gitlabCi pipeline, I have one repository code for k8s cluster (infra) and another with the k8s objects. The first pipeline triggers the second.


text:
Q: EMR cluster is not terminating while deleting the associated cloudformation stack using lambda function Resources:
  LFTULJ:
    Type: 'AWS::Lambda::Function'
    Properties:
      Runtime: python3.6
      Code:
        ZipFile: |
          import boto3
          import os
          import json

          stack_name = os.environ['stackName']

          def delete_cfn(stack_name):
              try:
                  cfn = boto3.resource('cloudformation')
                  stack = cfn.Stack(stack_name)
                  stack.delete()
                  return "SUCCESS"
              except:
                  return "ERROR"

          def handler(event,context):
              print("Received event:")
              print(json.dumps(event))
              return delete_cfn(stack_name)

      Handler: index.handler
      Environment:
        Variables:
          stackName: shubham
      Role: 'arn:aws:iam::261598744157:role/terminate'
      Timeout: '60'
    Metadata:
      'AWS::CloudFormation::Designer':
        id: 20d06512-220b-4ef6-b56a-f65d2a0c49d4

I am deleting the stack using lambda function. Everything is getting deleted but EMR cluster is not terminating. The error shown is Cluster id 'j-AQ1M94XKWDDJP' is not valid. (Service: AmazonElasticMapReduce; Status Code: 400; Error Code: InvalidRequestException; Request ID: 0283892f-c5aa-440d-968a-8cfb4585fe23)
while a cluster with that ID exists.

A: i got the answer to problem.
There is one property associated with EMR cluster VisibleToAllUsers. When we spin our EMR cluster using CLoudformation script it's default value is set which is false. So that's why EMR id was not valid. SO the solution for it is to make the VisibleToAllUsers property to true than other IAM can also view the EMR cluster and than the script and lambda function works correctly.

A: I set VisibleToAllUsers property value True but still facing the issue.
Throwing error message: Cluster id 'j-2NTFNCJLFN87I' is not valid. (Service: AmazonElasticMapReduce; Status Code: 400; Error Code: InvalidRequestException; Request ID: 6b7e5c5b-fffa-457f-8897-9417846452e0; Proxy: null)


text:
Q: improper training result dlib
i'm trying to train train_shape_predictor_ex for detecting following image in indian bill. i'm using 34 different images both clicked and scanned.
model is trained succesfully with
taining error = 0
testing error = 0.35468-6

i have tried changing oversampling parameter from 300 to 12000
but still same results.
what am i doing wrong?
drawing code - from image loading to drawing step:
    image_window win;

    frontal_face_detector detector = get_frontal_face_detector();
    shape_predictor pose_model;
    deserialize("sp.dat") >> pose_model;

    while (!win.is_closed())
    {
        cv::Mat temp;
        cap >> temp;

        cv_image<bgr_pixel> cimg(temp);

        std::vector<rectangle> faces = detector(cimg);

        std::vector<full_object_detection> shapes;
        for (unsigned long i = 0; i < faces.size(); ++i)
        {
            full_object_detection shape = pose_model(cimg, faces[i]);
            std::vector<rectangle> dets = detector(cimg);

            shapes.push_back(pose_model(cimg, faces[i]));

            win.clear_overlay();
            win.set_image(cimg);
            win.add_overlay(dets, rgb_pixel(255, 0, 0));
            win.add_overlay(render_face_detections(shapes));
       }
    }

A: As I see now - you are trying to train custom shape_predictor that will only have 14 points while using Dlib's render_face_detections function that require Dlib's face shape that has 68 points. render_face_detections will not draw your shape correctly and should throw an exception.
To make your shape prediction work, please ensure that you follow this conditions:

*

*The meaning of each point should be the same on each image. Do not put point #0 on ear on first image and #0 on the tip of nose on the second image

*Object bounding box should not be hand-drawn if you have small dataset. If you use face detector for testing shape predictor - ensure that your training/testing images bounding boxes are made by detecting face with the same face detector. Yes, you can hand-draw whis bounding boxes, but please make sure that they have the same size and position as if they will be detected. The way how you put box on the training set should be identical the way how you will get it in a future.

*There is no requirement to fit all points inside face bounding box. Really it can have any size and position, even static 10x10 box for each face on the tip of nose (or full bill rect) will work - but you should have enough training samples.  And follow previous condition

*Use as many images as possible. 34 images is not enough for training shape predictor - if will simply remember them in its internal memory and will not work in a future. Dlib's shape predictor is trained with about 2-3k images.

*You can generate new images by distorting original ones - scale, resize, add noise...

*Do not use Dlib's testing and drawing functions if your shape predictor does not have 68 points with the same meaning as dlib's face shape predictor. You can use its source code and make your functions as you need


text:
Q: verbatiminput and fontsize Is there a way to set an option of fontsize that would affect the command \verbatiminput ?
MWE:
\documentclass{article}
\usepackage{verbatim}

% NOT WORKING
%\makeatletter
%\newcommand{\verbatimfont}[1]{\renewcommand{\verbatim@font}{\ttfamily#1}}
%\makeatother

\begin{document}
        \verbatiminput{test.txt}
\end{document}

A: You can patch \verbatim@input:
\documentclass{article}
\usepackage{verbatim}
\usepackage{etoolbox}

\makeatletter
\patchcmd{\verbatim@input}{\@verbatim}{\scriptsize\@verbatim}{}{}
\makeatother

\begin{document}

Some text before to check the size

\verbatiminput{\jobname.tex}

Some text after to check the size

\end{document}

A: verbatimbox package as an alternative uses an optional argument.
\documentclass{article}
\usepackage{filecontents}
\begin{filecontents*}{test.tex}
This is my file
&*!@#$%^
&*()
and other \verbatim stuff
\end{filecontents*}
\usepackage{verbatimbox}
\begin{document}
\verbfilenobox[\LARGE]{test.tex}
\verbfilenobox[\tiny]{test.tex}
\verbfilenobox[\itshape]{test.tex}
\verbfilenobox[\mbox{\scriptsize\theVerbboxLineNo:} ]{test.tex}
\end{document}

A: You could also use the listings package wich offers the basicstyle option.
See here for more information on the package settings.
\documentclass{article}
\usepackage{filecontents}
\usepackage{listings}
\begin{filecontents*}{test.tex}
This is my file
&*!@#%^
&*()
and other stuff
\end{filecontents*}
\begin{document}
\lstinputlisting[basicstyle=\footnotesize]{test.tex}
\lstinputlisting[basicstyle=\tiny]{test.tex}
\lstinputlisting[basicstyle=\Huge]{test.tex}

\end{document}

A: I somehow figured out an ugly way of doing it, not very satisfying ...
\documentclass{article}
\usepackage{verbatim}

\begin{document}
        {\tiny
        \verbatiminput{test.txt}
        }
\end{document}


text:
Q: Delete column data from database In my database, I have username,password,address,city...etc.
With this code it delete the whole row from database :
SqlCommand cmd = new SqlCommand("Delete from customer_registration where username='"+ Session["username"] +"'",del);

My database with data :
Db
How to delete certain column data, or set it back to NULL?
Db

A: You can update your record like that
update your_table
set some_column = NULL
where id = 123


text:
Q: C#: How to access array methods from parent object? My ctor return an object which is multidimentional array. Depends on constructor argument, the object returned by ctor can be different rank array, but always int.
object arr = new int[2,2,2];

or
object arr = new int[2,2,2,2,2];

or
object arr = new int[0,0];

Having arr object  constructed, and knowing what it is (GetType()), I'd like to access array methods like Rank, GetLength, GetValue etc. How I can access child specific methods from the object level? For now I have only  four methods for arr object accessible: Equals, GetHashCode, GetType, and ToString

A: Cast the object into an array, like this:
((int[])arr).Rank
((int[])arr).GetLength()

or
(arr as int[]).Rank

A: You could just declare your variable as Array:
Array arr = new int[2,2,2,2,2];
int rank = arr.Rank;

Or cast to Array:
object arr = new int[2,2,2,2,2];
Array array = (Array)arr;

A: You have to cast it back to an Array object and then these methods will be available!


text:
Q: How to find all triplet values with 5 digits like 28575 * 3 = 85725 I can't figure out how to get a list of all triplets from 5 digits
A triplet, in this case, is a number where if you multiply the value with 3, the same digit will come out only with digits in a different order. So if there was one '3' in the first diget, the other digit can only have one '3' too.
I tried many different things with double for loops but I can't figure it out. This is was my last try:
def istrip(n):
    one = str(n)
    tri = str(n*3)

    for i in one:

        if tri.find(i) == -1:
            return False
    xl = 0
    yl = 0
    for x,y in zip(one, tri):
        xl += int(x)
        yl += int(y)
        if xl == yl:
            return True
    return False

for i in range(10000,33335):
    if istrip(i):
        print(i,i*3)

A: A fast and effective way of determining if two numbers are "anagrams" will be to break them into digits, then sort the digits. If the results are the same, then the numbers are made of the same digits. For example:
>>> n1 = 28575
>>> sorted(str(n1))
['2', '5', '5', '7', '8']

>>> n2 = 85725
>>> sorted(str(n2))
['2', '5', '5', '7', '8']

>>> sorted(str(n1)) == sorted(str(n2))
True

As such:
def istrip(n):
    return sorted(str(n)) == sorted(str(n * 3))


text:
Q: How in laravel 5.7 to run several urls on the same control action? Which is valid way in laravel 5.7 to run several urls on the same control action, like
Route::get('about', array(
    'as'      => 'page-about',
    'uses'    => 'PageController@page_content'
))->AdditiveParameter('about');

Route::get('security', array(
    'as'      => 'page-security',
    'uses'    => 'PageController@page_content'
))->AdditiveParameter('security');

and In PageController page_content action have 1 required parameter ?
Thanks!

A: I am not sure if you are looking for this only, but hope it will give some idea.
Route::group(['prefix' => '{prefix?}', 'where' => ['prefix' => 'content']],function (){
Route::get('{route_name}/{req_param}', array(
'as'      => 'page-security',
'uses'    => 'PageController@page_content'
))->where('route_name', '(about|security)');
});

And Controller action will be something like this
public function page_content($route_name,$req_param)
{
}

Let me know if this is working for you.


text:
Q: The argument type 'Future Function()' can't be assigned to the parameter type 'Future Function()?' I'm new to Flutter and I can't solve this error, if someone could help me to solve it I would be grateful.
I declare this function and the compiler shows me that the error is in the function declaration.
Future _onWillPop() {
    //return _Pop(); //???
    return showDialog(
        context: context,
        builder: (context) =>
        AlertDialog(
          title: const Text('Are you sure?'),
          content: const Text('Do you want to disconnect device and go back?'),
          actions: <Widget>[
            TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: new Text('No')),
            TextButton(
                onPressed: () {
                  disconnectFromDevice();
                  Navigator.of(context).pop(true);
                },
                child: new Text('Yes')),
          ],
        )
    );
  }

This is where I declare the function and where the error appears.
@override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,                //Declaration highlighted as error
      child: Scaffold(
        appBar: AppBar(
          title: Text('Sensor'),
        ),
        body: Container(
            child: !isReady
                ? Center(
              child: Text(
                "Waiting...",
                style: TextStyle(fontSize: 24, color: Colors.red),
              ),
            )

                : Container(
              child: StreamBuilder<List<int>>(
                stream: stream,
                builder: (BuildContext context,
                    AsyncSnapshot<List<int>> snapshot) {
                  if (snapshot.hasError)
                    return Text('Error: ${snapshot.error}');

                  if (snapshot.connectionState ==
                      ConnectionState.active) {
                    var currentValue = _dataParser(snapshot.data!);
                    return Center(
                        child: Stack(
                          children: <Widget>[
                            Container(
                              child: Center(
                                child: new Object3D(
                                  size: const Size(300, 300),
                                  path: "assets/3d.obj",
                                  asset: true,
                                  angleX: currentValue.x,
                                  angleY: currentValue.y,
                                  angleZ: currentValue.z,
                                  zoom: 50,
                                ),
                              ),
                              color: Colors.blueGrey,
                            ),
                            Column(children: <Widget>[
                              Text('Current value from Sensor',
                                  style: TextStyle(fontSize: 14)),
                              Text('${currentValue.x}',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16)),
                              Text('${currentValue.y}',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16)),
                              Text('${currentValue.z}',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16))
                            ]),
                          ],
                        ));
                  } else {
                    return Text('Check the stream');
                  }
                },
              ),
            )),
      ),
    );
  }
}

Error: Cannot run with sound null safety, because the following dependencies
don't support null safety:

*

*package:flutter_3d_obj

For solutions, see https://dart.dev/go/unsound-null-safety
lib/mpu6050_page.dart:129:18: Error: The argument type 'Future Function()' can't be assigned to the parameter type 'Future Function()?'.

*

*'Future' is from 'dart:async'.
onWillPop: _onWillPop,
^

FAILURE: Build failed with an exception.

*

*Where:
Script 'C:\Users\adria\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1156

*What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\Users\adria\flutter\bin\flutter.bat'' finished with non-zero exit value 1


text:
Q: Using MusicKit JS from Nodejs MusicKit JS is a javascript library that allows third-party developers to build web clients for apple music. This allows access to the otherwise fully-closed apple music ecosystem.
I am wondering if there is a way to use this library from nodejs to build a command-line application that can play songs from apple music, theoretically on any operating system.

A: I have tried this and unfortunately this is not possible with MusicKitJs right now. The library depends pretty heavily on browser APIs so it just breaks in the Node JS environment


text:
Q: Sequelize limit and offset incorrect placement in query I am using sequelize in nodeJs and I have this code:
Time_Sheet_Details.findAll({
include: [
    {
        model: timesheetNotesSubcon,
        required: false,
        attributes:["note","file_name", "id", "working_hrs", "timestamp", "has_screenshot", "notes_category"]
    },
    {
        model: Timesheet,
        attributes:["id","leads_id","userid"],
        include:[
            {
                model: Lead_Info, attributes:["id","fname","lname","email","hiring_coordinator_id","status"],
                where: { hiring_coordinator_id : 326},
                include:[{
                    model: adminInfoSchema,
                    required: false,
                    attributes:["admin_id","admin_fname", "admin_lname", "admin_email", "signature_contact_nos", "signature_company"],
                }]

            },
            {model:Personal_Info,attributes:["userid","fname","lname","email"]}
        ],
    }],
where: {
    reference_date: filters.reference_date
},
order:[
    ["id","DESC"]
],
offset:((1-1)*30),
limit : 30,

}).then(function(foundObject){
    willFulfillDeferred.resolve(foundObject);
});

And the result query is:
 SELECT `timesheet_details`.*, `timesheet_notes_subcons`.`note` AS
 `timesheet_notes_subcons.note`, `timesheet_notes_subcons`.`file_name` AS
 `timesheet_notes_subcons.file_name`, `timesheet_notes_subcons`.`id` AS
 `timesheet_notes_subcons.id`, `timesheet_notes_subcons`.`working_hrs` AS
 `timesheet_notes_subcons.working_hrs`, `timesheet_notes_subcons`.`timestamp` AS
`timesheet_notes_subcons.timestamp`, `timesheet_notes_subcons`.`has_screenshot` AS
`timesheet_notes_subcons.has_screenshot`,
`timesheet_notes_subcons`.`notes_category` AS
 `timesheet_notes_subcons.notes_category`, `timesheet.lead`.`id` AS
 `timesheet.lead.id`, `timesheet.lead`.`fname` AS `timesheet.lead.fname`,
 `timesheet.lead`.`lname` AS `timesheet.lead.lname`,
`timesheet.lead`.`email` AS `timesheet.lead.email`,
 `timesheet.lead`.`hiring_coordinator_id` AS
 `timesheet.lead.hiring_coordinator_id`, `timesheet.lead`.`status` AS
 `timesheet.lead.status`, `timesheet.lead.admin`.`admin_id` AS
 `timesheet.lead.admin.admin_id`, `timesheet.lead.admin`.`admin_fname` AS
`timesheet.lead.admin.admin_fname`, `timesheet.lead.admin`.`admin_lname` AS
 `timesheet.lead.admin.admin_lname`, `timesheet.lead.admin`.`admin_email` AS
 `timesheet.lead.admin.admin_email`,
`timesheet.lead.admin`.`signature_contact_nos` AS
 `timesheet.lead.admin.signature_contact_nos`,
 `timesheet.lead.admin`.`signature_company` AS
 `timesheet.lead.admin.signature_company`, `timesheet.personal`.`userid` AS
 `timesheet.personal.userid`, `timesheet.personal`.`fname` AS
 `timesheet.personal.fname`, `timesheet.personal`.`lname` AS
 `timesheet.personal.lname`, `timesheet.personal`.`email` AS
 `timesheet.personal.email` FROM (SELECT `timesheet_details`.`id`,
 `timesheet_details`.`timesheet_id`, `timesheet_details`.`day`,
 `timesheet_details`.`total_hrs`, `timesheet_details`.`adj_hrs`,
 `timesheet_details`.`regular_rostered`, `timesheet_details`.`hrs_charged_to_client`,
 `timesheet_details`.`diff_charged_to_client`,
 `timesheet_details`.`hrs_to_be_subcon`,
`timesheet_details`.`diff_paid_vs_adj_hrs`, `timesheet_details`.`status`,
 `timesheet_details`.`reference_date`, `timesheet`.`id` AS `timesheet.id`,
 `timesheet`.`leads_id` AS `timesheet.leads_id`, `timesheet`.`userid` AS
 `timesheet.userid` FROM `timesheet_details` AS `timesheet_details`
LEFT OUTER JOIN `timesheet` AS `timesheet`
ON `timesheet_details`.`timesheet_id` = `timesheet`.`id`
WHERE (`timesheet_details`.`reference_date` >= '2016-04-23 16:00:00'
AND `timesheet_details`.`reference_date` < '2017-05-02 15:59:59')
ORDER BY `timesheet_details`.`id` DESC LIMIT 0, 30) AS
 `timesheet_details` LEFT OUTER JOIN `timesheet_notes_subcon` AS
 `timesheet_notes_subcons` ON `timesheet_details`.`id` =
 `timesheet_notes_subcons`.`timesheet_details_id`
INNER JOIN `leads` AS `timesheet.lead` ON `timesheet.leads_id` =
 `timesheet.lead`.`id` AND `timesheet.lead`.`hiring_coordinator_id` = 326
 LEFT OUTER JOIN `admin` AS `timesheet.lead.admin` ON
 `timesheet.lead`.`hiring_coordinator_id` =
 `timesheet.lead.admin`.`admin_id`
LEFT OUTER JOIN `personal` AS `timesheet.personal` ON `timesheet.userid`
 = `timesheet.personal`.`userid` ORDER BY `timesheet_details`.`id` DESC;

As you can see, the LIMIT 0, 30 is not in the end of the query. This an issue for me because that query will return nothing, and the limit and offset should be at the end of query like this:
 SELECT `timesheet_details`.*, `timesheet_notes_subcons`.`note` AS
`timesheet_notes_subcons.note`, `timesheet_notes_subcons`.`file_name` AS
 `timesheet_notes_subcons.file_name`, `timesheet_notes_subcons`.`id` AS
 `timesheet_notes_subcons.id`, `timesheet_notes_subcons`.`working_hrs` AS
 `timesheet_notes_subcons.working_hrs`,
 `timesheet_notes_subcons`.`timestamp` AS
 `timesheet_notes_subcons.timestamp`,
 `timesheet_notes_subcons`.`has_screenshot` AS
 `timesheet_notes_subcons.has_screenshot`,
 `timesheet_notes_subcons`.`notes_category` AS
 `timesheet_notes_subcons.notes_category`, `timesheet.lead`.`id` AS
 `timesheet.lead.id`, `timesheet.lead`.`fname` AS `timesheet.lead.fname`,
 `timesheet.lead`.`lname` AS `timesheet.lead.lname`,
 `timesheet.lead`.`email` AS `timesheet.lead.email`,
 `timesheet.lead`.`hiring_coordinator_id` AS
 `timesheet.lead.hiring_coordinator_id`, `timesheet.lead`.`status` AS
 `timesheet.lead.status`, `timesheet.lead.admin`.`admin_id` AS
 `timesheet.lead.admin.admin_id`, `timesheet.lead.admin`.`admin_fname` AS
 `timesheet.lead.admin.admin_fname`, `timesheet.lead.admin`.`admin_lname`
 AS `timesheet.lead.admin.admin_lname`,
 `timesheet.lead.admin`.`admin_email` AS
 `timesheet.lead.admin.admin_email`,
 `timesheet.lead.admin`.`signature_contact_nos` AS
 `timesheet.lead.admin.signature_contact_nos`,
 `timesheet.lead.admin`.`signature_company` AS
 `timesheet.lead.admin.signature_company`, `timesheet.personal`.`userid`
 AS `timesheet.personal.userid`, `timesheet.personal`.`fname` AS
 `timesheet.personal.fname`, `timesheet.personal`.`lname` AS
 `timesheet.personal.lname`, `timesheet.personal`.`email` AS
 `timesheet.personal.email` FROM (SELECT `timesheet_details`.`id`,
 `timesheet_details`.`timesheet_id`, `timesheet_details`.`day`,
 `timesheet_details`.`total_hrs`, `timesheet_details`.`adj_hrs`,
 `timesheet_details`.`regular_rostered`,
 `timesheet_details`.`hrs_charged_to_client`,
 `timesheet_details`.`diff_charged_to_client`,
 `timesheet_details`.`hrs_to_be_subcon`,
 `timesheet_details`.`diff_paid_vs_adj_hrs`,
 `timesheet_details`.`status`, `timesheet_details`.`reference_date`,
 `timesheet`.`id` AS `timesheet.id`, `timesheet`.`leads_id` AS
 `timesheet.leads_id`, `timesheet`.`userid` AS `timesheet.userid`
FROM `timesheet_details` AS `timesheet_details`
LEFT OUTER JOIN `timesheet` AS `timesheet` ON
 `timesheet_details`.`timesheet_id` = `timesheet`.`id`
WHERE (`timesheet_details`.`reference_date` >= '2016-04-23 16:00:00'
AND `timesheet_details`.`reference_date` < '2017-05-02 15:59:59')
ORDER BY `timesheet_details`.`id` DESC) AS `timesheet_details`
LEFT OUTER JOIN `timesheet_notes_subcon` AS `timesheet_notes_subcons` ON
 `timesheet_details`.`id` =
 `timesheet_notes_subcons`.`timesheet_details_id` INNER JOIN `leads` AS
 `timesheet.lead` ON `timesheet.leads_id` = `timesheet.lead`.`id` AND
`timesheet.lead`.`hiring_coordinator_id` = 326 LEFT OUTER JOIN `admin` AS
 `timesheet.lead.admin` ON `timesheet.lead`.`hiring_coordinator_id` =
 `timesheet.lead.admin`.`admin_id` LEFT OUTER JOIN `personal` AS
 `timesheet.personal` ON `timesheet.userid` =
 `timesheet.personal`.`userid` ORDER BY `timesheet_details`.`id` DESC
 LIMIT 0, 30;

Is there something I am doing wrong in my code? Did I misplaced the order and limit?

A: Found an answer to my question, I just need to add the subQuery = false so that the limit and offset will not be evaluated to sub query. And the offset and limit is also in the end of the query.
offset:((page-1)*limit),
limit : limit,
subQuery:false

A: got the same case, another way of doing it is to pass an array to limit.
{
include: [
    {
        model: timesheetNotesSubcon,
        required: false,
        attributes:["note","file_name", "id", "working_hrs", "timestamp", "has_screenshot", "notes_category"]
    },
    {
        model: Timesheet,
        attributes:["id","leads_id","userid"],
        include:[
            {
                model: Lead_Info, attributes:["id","fname","lname","email","hiring_coordinator_id","status"],
                where: { hiring_coordinator_id : 326},
                include:[{
                    model: adminInfoSchema,
                    required: false,
                    attributes:["admin_id","admin_fname", "admin_lname", "admin_email", "signature_contact_nos", "signature_company"],
                }]

            },
            {model:Personal_Info,attributes:["userid","fname","lname","email"]}
        ],
    }],
where: {
    reference_date: filters.reference_date
},
order:[
    ["id","DESC"]
],
limit : [((page-1)*limit), limit],

}

A: LIMIT,OFFSET,PROJECTION of FIELDS and FULLTEXT SEARCH using sequilize in Node.js

        let msg = await Feedback.findAll({
            where: Sequelize.literal('MATCH (message) AGAINST (:feedback)'), // fulltext search query
            replacements: {
            feedback: req.body.text
            },
            attributes: ['uID', 'message'], // projection of columns
            offset:1, // set the offset according your use case
            limit: 1  // limit the output
        });

A: Need to place an order and where clause before includes.Do something like this
 user.findAll({
             offset: 5, limit: 5,
            order: [
// Will escape full_name and validate DESC against a list of valid direction parameters
['full_name', 'DESC']]
        }).then(function (result) {
})

the resulting query will be

if you want to put ordering in include then you need to place the order in include part
include: [{
                model: taskhelpers, required: true,
                order: {
                    order: '`updatedAt` ASC'
                }
           }]

for more detail check Pagination / Limiting and ordering
updated
nested include and limit and order
var option = {
                offset: 5, limit: 5,
            order: [
// Will escape full_name and validate DESC against a list of valid direction parameters
['id', 'DESC']],
                attributes: [
                    'id', 'title',
                    [sequelize.Sequelize.fn('date_format', sequelize.Sequelize.col('date'), '%d-%b-%Y'), 'date']
                ],

                include: [

                    {
                        model: taskhelpers, required: true,

                        where: {
                            userId: req.params.userid,

                            $or: [
                                {
                                    status: {
                                        $eq: "1"
                                    }
                                },
                                {
                                    status: {
                                        $eq: "3"
                                    }
                                },
                            ]
                        }

                    }]
            };

now pass this option to your model parameter
tasks.findAll(options)
    .then(function (result) {
        res.send({message:result,error:null});
    })
        .catch(function (err) {
            res.send({message:null,error:err});
        })

this will be the generated query

A: try to add $limit parameter on your request and sequelize will use it automatically
ex: "http://localhost:3031/my-service?$limit=23"


text:
Q: Azure SWA: redirect to modified version of requested route? I set up a site using Azure Static Web Apps. I have two use cases I haven't been able to solve nicely for, and I think the same functionality might address both:

*

*When a user is not authenticated, they're redirected to <my-site>/.auth/login/<my-auth-provider>. But, that means when they're brought back after logging in, they go to /index.html, which is not ideal. Most of the traffic to this site will be to specific leaf pages. I'd like to redirect to <my-site>/.auth/login/<my-auth-provider>?fromUrl=<the-requested-url> instead, if possible.

*When a user requests a "pretty" url address e.g. <my-site>/pretty-url, I noticed that Azure SWA doesn't handle that the normal way, rewriting to <my-site>/pretty-url/index.html. I'd like it to at least try to rewrite to <my-site>/pretty-url/index.html.

A: It looks like neither of these are possible at the moment.
Here's a Github issue about redirecting after login, and one about enforcing trailing slashes.