Q: Using a delayed variable value to as a length value in a substring I am extracting note sets from a log file.
The line number of the header to a set in the file is found via FIND /V /N
The note set is delimited with a line containing only "@@@"
I use findstr to return this line which returns as 'xxx:@@@', e.g. '14:@@@' or '149:@@@' and so on.
in the snippet of code below, typical data for the variables on entry into the FOR/IN loop would be

*

*_ndelm = "@@@" ~ the delimiter marking the end of the note

*_infil = "notes.log" the file holding the dataset

*_atpos = the line position of the note header

During execution the local variables in the enabledelayedexpansion loop hold the following temporary values requiring !..! in the moment of processing:

*

*strel= the string delimiter line returned by findstr as above

*numel= the extracted line number from strel=='xxx', generally 1-4 chars long

*end  = will become the (integer) line number of the delimiter line

In this code snippet the IF statements are needed to get around my problem: I can't find a way to use !end! in a single SET statement, so the workaround is 4 IFs.:
SET _ndelm=@@@
SET /a _atpos=1
FOR /f "usebackq tokens=1 delims=[]" %%i IN (`FINDSTR /b /l /n /c:%_ndelm% %_infil% `) DO (
SET strel=%%i
CALL stringlen %%i end & rem gets the character length of the delimiter line]
SET /a end-=4
IF [!end!] EQU [1] (SET numel=!strel:~0,1!)
IF [!end!] EQU [2] (SET numel=!strel:~0,2!)
IF [!end!] EQU [3] (SET numel=!strel:~0,3!)
IF [!end!] EQU [4] (SET numel=!strel:~0,4!)
SET /a end=!numel!
IF !end! GEQ %_atpos% GOTO fetchlines
)

Ideally, I would like to code something like this
(SET numel=!strel:~0,!end!!)
SET /a end=!numel!

I've hunted high and low to find a similar use case, but to no avail, and tried any number of  combinations of %'s and !'s empirically.
If anyone has a syntax I could use ~ that would be great :-)
Thanks
file extract from the file:
11/01/2020 16:05:29.87 *** DONE *** All Batches [LEFiles needing /r]
 find all batches that should not be run, apply the /r switch and amend
 accordingly. Start at root and work down the main line before tackling the
 side branches.
  ~ Main *** done ***
  ~ libs *** done ***
  ~ rest *** done ***
  ~
@@@
11/01/2020 15:18:47.02 >>> open >>> LEfiles runit [add a 'don't run!' switch]
 some batches just can't be -or shouldn't be- run from the help system.
 code a don't run switch [/r]=don't run
@@@
09/01/2020 10:12:52.83 *** DONE *** strcharrepl [bug] abend on "*" to " "
 error message '= % was unexpected at this time.' after returning from a call to
 nameFiledatetime which itself crashes on spaces - workaround for that needed
 Suspect it's the same problem - returning a string with spaces is the generic
 issue that needs a solution.
 Maybe always return with quotes and then strip those?
 ~soln [strcharrepl] not much that can be done because redirection chars
  always act in re-dir ways. Added notes to provide guidance in use.
 ~soln [zFN] surround filename with quotes and replace spaces with backslashes
  before call, replace with spaces after.
@@@

A: For %%e in (!end!) Do set numel=!strel:~0,%%e!

The trick is to use a for loop parameter, because the parameter is expanded before the delayed expansion will be executed.

A: Thanks to the various contributors, the code snippet simplified to:
FOR /f "delims=:" %%i IN ('FINDSTR /b /l /n /c:%_ndelm% %_infil%') do (
  set "end=%%i"
  IF !end! GEQ %_atpos% GOTO fetchlines
)

which improved readability and performance.
The answer to the Question posed is the accepted answer from @Jeb.


Q: Download multiple files with gevent I am trying to download a list of files in parallel, making use of [gevent][1]
My code is a slight modification of the code suggested here
monkey.patch_all()

def download_xbrl_files(download_folder, yq, list_of_xbrl_urls):
    def download_and_save_file(url, yr, qtr):
        if url is not None:
            full_url = "http://edgar.sec.gov" + url
            if not os.path.exists(full_url):
                try:
                    content = urllib2.urlopen(full_url).read()
                    filename = download_folder + "/" + str(y) + "/" + q + "/" + url.split('/')[-1]
                    print "Saving: ", filename
                    f_raw = open(filename, "w")
                    f = FileObject(f_raw, "w")
                    try:
                        f.write(content)
                    finally:
                        f.close()
                        return 'Done'
                except:
                    print "Warning: can't save or access for item:", url
                    return None
            else:
                return 'Exists'
        else:
            return None
    (y, q) = yq
    if utls.has_elements(list_of_xbrl_urls):
        filter_for_none = filter(lambda x: x is not None, list_of_xbrl_urls)
        no_duplicates = list(set(filter_for_none))
        download_files = [gevent.spawn(lambda x: download_and_save_file(x, y, q), x) for x in no_duplicates]
        gevent.joinall(download_files)
        return 'completed'
    else:
        return 'empty'

What the code does is:

*

*after some cleaning

*gevent.spawn spawns download_and_save_file which:

*checks if the file has been already downloaded

*if not, downloads the content with urllib2.urlopen(full_url).read()

*saves the file with the help of gevent's FileObject
I have the impression that the download_and_save only works sequentially. Furthermore, my application gets in a stand-by. I could add a timeout but I wanted to handle failures gracefully within my code.
Wondering if I am doing something wrong - it's the first time I write code in python.
EDIT
Here is a version of the code using "Threads"
def download_xbrl_files(download_folder, yq_and_url):
    (yq, url) = yq_and_url
    (yr, qtr) = yq
    if url is not None and url is not '':
        full_url = "http://edgar.sec.gov" + url
        filename = download_folder + "/" + str(yr) + "/" + qtr + "/" + url.split('/')[-1]
        if not os.path.exists(filename):
            try:
                content = urllib2.urlopen(full_url).read()
                print "Saving: ", filename
                f = open(filename, "wb")
                try:
                    f.write(content)
                    print "Writing done: ", filename
                finally:
                    f.close()
                    return 'Done'
            except:
                print "Warning: can't save or access for item:", url
                return None
        else:
            print "Exists: ", filename
            return 'Exists'
    else:
        return None

def download_filings(download_folder, yq_and_filings):
    threads = [threading.Thread(target=download_xbrl_files, args=(download_folder, x,)) for x in yq_and_filings]
    [thread.start() for thread in threads]
    [thread.join() for thread in threads]

A: I looked into this a little deeper the basic problem is that gevent.spawn() creates greenlets not processes (all greenlets run in a single OS thread).
Try a simple:
import gevent
from time import sleep
g = [gevent.spawn(sleep, 1) for x in range(100)]
gevent.joinall(g)

You'll see the time this takes is 100s. Which proves the point above.
You are really looking for multithreading which can be found in the threading module.
Have a look at the the question at: How to use threading in Python?. For a little how to.
---update---
Here is a quick example of how you might do this:
threads = [threading.Thread(target=sleep, args=(1,)) for x in range(10)]
[thread.start() for thread in threads]
[thread.join() for thread in threads]


Q: Is there an alternative to .toggle() that will let me control on/off? I am developing a portfolio website and I want to be able to tag items in the page that displays work so you can toggle visibility. I have it set up with .toggle() right now, which works, except that if I want to use multiple tags, it throws off other tags. You an see this is action on my site - http://nu-creative.com/ourwork.html
On the left, you can toggle both branding and case studies, but the third image is tagged as both, so when you click one after the other it hides it when it should show it and vice versa.
The code is all in the bottom of the page but a snippet of the relevant jQuery is here:
        $("#branding").click(function () {
            $(this).toggleClass("showItem");
            $(".brandingHide").toggle("slow", function () {

            });
        });

        $("#case").click(function () {
            $(this).toggleClass("showItem");
            $(".caseHide").toggle("slow", function () {

            });
        });

Then the <-li> has the appropriate ID and the class is on the div in the grid that hides. I could make it work if I had two buttons - a hide and a show, but that would be weird. I could also hack it by making the grey a seperate layer so that when you click again you are actually clicking a different item which then disappears and exposes the show button again. There must be a better way, though!
Thanks in advance!
Solution
http://jsfiddle.net/ngau3xjL/5/

A: You just have to complete your animation logic. The advantage of this approach is its more verbose but still only one DOM lookup.
   $("#branding").click(function () {
       var $element = $(this);
       var isVisible = $element.hasClass('showItem');
       if(isVisible)
           $element.removeClass("showItem");
       } else {
           $element.addClass("showItem");
       }
    });

http://jsfiddle.net/ngau3xjL/4/


Q: AS3 safe downloaded file directly to specified folder May be some body have FLA file which download file to folder (without dialog of save file).
Just Click to - DOWNLOAD -> file save to folder /update on swf located. (without any confirmation of filename or filder location)
       var fileName:String = "upgrade.zip";
       var request:URLRequest = new URLRequest();
       request.url = DOWNLOAD_URL;
       var params:URLVariables = new URLVariables();
       fr.download(request,fileName);

This change filename in dialog only, but dialog must to be auto-agreed.
And more one. When I try to make AS3 script, for download via URLRequest, this work only in Flash editor. FLA file (when I comp[ile to SWF -> not work).


Q: Accordion and Dialog components for Material Design Lite Are there any accordion and modal dialog components available and actually work that are compatible with my environment of:
Google's Material Design Lite version 1.06
Facebook's ReactJS 0.14.2
Microsoft's TypeScript and Visual Studio 2015 (for typescript bundling)
I am trying to avoid JavaScript library bloat and Material Design Lite is missing these essential widgets.  I'm not using Node.js since I'm on a Windows platform so Material-UI is not an option.  MaterializeCSS bloats my Visual Studio project and makes it really slow and unusable.

A: Update Sep 28,2016
It looks like there is now an open-source library for doing just this: https://github.com/fiffty/react-treeview-mui

Self Implementation
This answer serves as an example for an Accordion dropdown built using React, though not styled as Material Design. You would need to do that yourself.
This setup requires a hierarchy object of parent > child objects/arrays. This base class should be able to handle very deep depths just fine. It uses recursion for its structure setup. I'll also be using ES6 syntax for preference, as it helps setup the recursion easier for me.
Accordion Class:

// Accordian Class
// Dynamic/Recursive
// a parent>child>child... relationship is required
// the whole object can be named however you like,
// but each child object needs to be identified as "children"
class Accordian extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openLevelRow: "", // this is the current open level row in an accordian (starts out with none being open)
      selfLevelObject: props.newLevel // the current level object containing all rows and their data/children
    };
  }

  // This is our toggle open/close method
  // if row is already open, close it
  // uniqueSelector is unique per row, and also a key
  // in the selfLevelObject (could be a name, id)
  toggleOpenClose(uniqueSelector) {
    // simple ternary assignment
    this.setState({
      openLevelRow: this.state.openLevelRow != uniqueSelector ? uniqueSelector : ""
    });
  }

  render () {
    // deconstruct assignment from state
    const { selfLevelObject, openLevelRow } = this.state

    return (

          {selfLevelObject.map((row, i) =>
              {/* Collectively where all children of the same hierchy level are listed*/}

                {/* This is an individual collapsable Row */}

 {row.title}

                {/*
                    When iterating the list, find out if a row has been opened
                */}
                {this.state.openLevelRow != row.uniqueSelector ?  :
                    /*
                      This code block is called if the current row is opened
                      now we to need to find out if there are children,
                      if not, then we are at the bottom, do what ever
                      you'd like with the bottom row
                    */
                    selfLevelObject[uniqueSelector].children != undefined ?
                      <Accordian newLevel={selfLevelObject[uniqueSelector].children} />
                      : // else
                    // TODO - whatever you want with bottom row
                }

          )}

    );
  }
}

Accordian.propTypes = {
    newLevel: React.PropTypes.object
}


Q: visual studio backward compatibility Hi there I have build a project with visual studio 2010 but I now need to open it using an older version vs2008. Is this possible by just changing the target framework to .net 3.5?

A: In my experience, VS2008 can open VS2010 project files if there aren't VS2010-specific bits in it - so simple class libraries or console apps are fine, for example. There will be a warning that the tools version is unknown, but it will basically work. (You'll still need to target .NET 3.5, I believe - I haven't tried opening a .NET 4 project in VS2008, but I wouldn't really expect it to work, at least not if it uses new language features.)
Where I've used this approach, I've had two different solution files - one for VS2008 and one for VS2010, both including the same projects. That way both can open without any problems, and without any conversion prompts. So far it's worked fine.
As I say, that's my experience - YMMV.

A: I was able to open a project file created in VS2010 by simply opening it in VS2008. I was then able to go into Project Properties and set the target framework - just be sure to check the Build settings too, as 2010 is version 4, which isn't supported in 2008.
In my particular case, I targeted Framework v2.0, which involved removing unused LINQ references. The project compiled happily, and I was able to run the app.

A: No, the project file format has been extended.


Q: Doctype for html email Which DOCTYPE is the right one for HTML email?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

A: There is only minor differences these days in DOCTYPE declarations in html email.  Although only minor, it is still recommended to test your emails via Email on Acid or Litmus or any other testing software prior to a send to ensure cross client compatibility and to find any unforeseen quirks.
The larger issues comes with if you do not declare a doctype or body tag, it can really screw up different parts of the email on certain clients.
The most popular DOCTYPE nowadays is the HTML 5 doctype (<!DOCTYPE HTML>) which is used with very little hiccups. The most popular/safest doctype used to be the <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> doctype. This can still be used, but may limit different capabilities of your email, as it is referencing an older version of HTML.
See this forum post in litmus for more in-depth information on this: https://litmus.com/community/discussions/39-explanation-of-doctype-html-attributes-and-meta-tags-in-email-head

A: This is what I use.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

I code emails daily and this came as the header that exact  target (salesforce) provided us. Our company has sister brands and this what they all use as well so I'm assuming this is standard.

A: More primitive email readers cannot handle DOCTYPE at all, and instead either strip it completely out of the email, or just remove the string "!DOCTYPE" and leave the rest of the HTML intact. You wind up seeing weird things like this at the beginning of the emails:

< HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

...because the word !DOCTYPE was removed, but not the rest, and since it did not remove the space, it displayed the broken code to the reader.
The rest of the email will usually display just fine.
While this obviously is a programming error by the writer of the script, I have seen a lot of scripts with this same exact error. It's usually because they are simply stripping out HTML tags and not allowing !DOCTYPE.
Email clients seem to be able to process your email without it unless you are using a different character set than the user, and sometimes stumble when you declare it.


Q: How does the method know what array need to be checked? If I have 2 classes that extend from this container class, one that can only alter the list container and the other that can only alter the set container. How would the isEmpty() method be able to know which container to check? This is a lab for class so I'm not allowed to change any of the code already given to me.
public class Container {
    // Do not change the value of the following constants.
    protected final int ORIGINAL_SIZE = 10;
    protected Object[] list; // is a container that stores the element of MyList
    protected Object[] set; // is a container that stores the element of MySet
    protected int size; // this variable holds the actual number of elements that are stored in either of the containers (i.e. MyList or MySet).

    /**
    * This method returns true if the container is empty.
    * @return It returns true if the container is empty, otherwise false.
    */
    boolean isEmpty() {

    return true;
    }
}

class MyList extends Container{

    public MyList () {
        list= new Object[ORIGINAL_SIZE];
        size = 0;
    }
}

class MySet extends Container{

    public MySet() {
        set = new Object[ORIGINAL_SIZE];
        size = 0;
    }
}

A: You need to override the isEmpty method on the respective sub classes, and then it's clear to which collection they refer:
class MyList extends Container {
    public MyList() {
        list = new Object[ORIGINAL_SIZE];
        size = 0;
    }

    @Override
    public boolean isEmpty() {
        return size > 0;
    }
}

Here you need to maintain the size variable each time you modify (add to or remove from) the list.
(Same for the set implementation, just using set instead of list.)
The whole thing is a bit of a weird class design. The Container base class should not have list and set, these should be in the respective child classes MyList and MySet, so that everything is defined where it's used (only).

A: You don't need to check either container. Override the isEmpty() method in both classes to check the size field. As elements are added or removed to either array, increment or decrement the size accordingly.


Q: simple Tkinter program - window vanishes after clicking button - maintop problem? Coders,
I guess I have a newbie question: my windows disappears when I click on a button. If I put in root.mainloop() as last line in the buttonClicked-function, then the program is fine - but it looks not right...what is wrong here?
import tkinter as tk

def buttonClicked(event):
    print(tf1.get())
    tf1Content.set("button clicked")
    # root.mainloop() ... would work

root = tk.Tk()

frame = tk.Frame(root, relief="ridge", borderwidth=2)
frame.pack(fill="both",expand=1)
label = tk.Label(frame, text="Input:")
label.pack(expand=1)
tf1Content = tk.StringVar()
tf1 = tk.Entry(frame, text="input here", textvariable=tf1Content)
tf1.pack(expand=1)
bOk = tk.Button(frame,text="OK",command=root.destroy)
bOk.bind("<Button-1>", buttonClicked)
bOk.widget = "bOK"
bOk.pack(side="bottom")

tf1.focus()

root.mainloop()

A: It turns out that you just copied this line:
bOk = tk.Button(frame,text="OK",command=root.destroy)

which binds a call to root.destroy() to the button press.
The fix is to just remove the command parameter:
bOk = tk.Button(frame,text="OK")


Q: Capistrano: Override shared_dir variable First off, very new to Capistrano, so excuse my newbness.
I am deploying a CodeIgniter application of which I have a data folder that lives outside the current web directory that I am trying to symlink to. This is what I have used to create the symlink
set :shared_dir, %w(/var/www/website/)
set :linked_dirs, %w{43b621acdfc9523443f27b7767e}

This is the result of the deployed application
43b621acdfc9523443f27b7767e -> /var/www/website/shared/43b621acdfc9523443f27b7767e

My goal is to override the shared_dir variable to generate a symlink of
/var/www/website/43b621acdfc9523443f27b7767e

I am using Capistrano 3. Any insight greatly appreciated.
Thanks

A: You can create an specific task to take care of creating and updating the symlink from anywhere in your application to anywhere in your system on each deploy. For example:
namespace :terminal do
  task :link_external_dir, :except => { :no_release => true } do
    capifony_pretty_print '--> Generating soft link with external_example_dir'
    run "sharedWebDir=#{shared_path}/web; cd $sharedWebDir; if [ -d $sharedWebDir/internal_example_dir -o -f $sharedWebDir/internal_example_dir ]; then rm -rf $sharedWebDir/internal_example_dir; fi; if [ ! -L $sharedWebDir/internal_example_dir ]; then ln -s /srv/example/vhost/external_example_dir $sharedWebDir/internal_example_dir; fi;"
    capifony_puts_ok
  end
  task :rm_shared_example_dir, :except => { :no_release => true } do
    capifony_pretty_print '--> Removing sharedDir/internal_example_dir symlink'
    run "sharedWebDir=#{shared_path}/internal_example_dir; if [ -L $sharedWebDir/internal_example_dir ]; then rm $sharedWebDir/internal_example_dir; fi;"
    capifony_puts_ok
  end
end

Now call each function on each deploy:
before "deploy", "terminal:rm_shared_example_dir"
after  "deploy", "deploy:cleanup"
after  "deploy", "terminal:link_external_dir"

What we are trying to accomplish is:
1.Before Deploy, remove the file from your main sharedDir that links to your external dir.
REMOVE
/var/www/website/shared/externalDir -> /srv/example/vhost/external_example_dir

2.Deploy your app.
3.Generate the custom symlink again.
ln -s /srv/example/vhost/external_example_dir $sharedWebDir/internal_example_dir


Q: Swift convert string to date output wrong date I want to convert dateStartString = “28/02/2018” in to Date and compare that converted date with today date. when i convert dateStartString the converted date is "2018-02-27 18:30:00 UTC".why its output is wrong date?
here is my code
var dateStartString = "28/02/2018"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
guard let dateStartDate = dateFormatter.date(from: dateStartString) else {
    fatalError("ERROR: Date conversion failed due to mismatched format.")
}

let dateToday = Date()

if(dateStartDate>=dateToday){
    print("Yes")
}
else{
    print("Today date is 28/02/2018. Why it print No?")
}

Hope you understand my problem.
Thanks in advance.

A: You need to understand that Date does not only represent a date, but also a time.
>= compares both date and time components of a Date object. Since you didn't specified any time in your date string, the API assumed it to be 00:00:00 in your local time, which is 18:30:00 of the previous day in UTC. Why UTC, you ask? That's what the description of the date always is. When you print a date, it always prints it in UTC time. To print it in your time zone, set the timeZone property of your date formatter and format it.
One way to only compare the date components is by removing the time components. From this answer, this is how you remove time components:
public func removeTimeStamp(fromDate: Date) -> Date {
    guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: fromDate)) else {
        fatalError("Failed to strip time from Date object")
    }
    return date
}

Now this should be true:
dateStartDate >= removeTimeStamp(fromDate: dateToday)

A: As Sweeper explained, dateStartDate is at 00:00 of 28/02/2018,
whereas dateToday is the current point in time, which is
on the same day, but after midnight. Therefore dateStartDate >= dateToday evaluates to false.
To compare the timestamps only to day granularity and ignore the
time components you can use
if Calendar.current.compare(dateStartDate, to: dateToday, toGranularity: .day) != .orderedAscending {
    print("Yes")
}

This will print "Yes" if dateStartDate is on the same or a later
day than dateToday.
The compare method returns .orderedAscending, .orderedSame,
or .orderedDescending, depending on wether the first date is on
a previous day, the same day, or a later day, than the second date.

A: try to set your current date Formatter while comapring date.
Below your sample code update:
var dateStartString = "28/02/2018"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.locale = NSLocale.current
guard let dateStartDate = dateFormatter.date(from: dateStartString) else {
    fatalError("ERROR: Date conversion failed due to mismatched format.")
}

var dateToday = Date()
print(dateToday)
let dateTodaystr = dateFormatter.string(from: dateToday)
dateToday = dateFormatter.date(from: dateTodaystr)!
print(dateToday)

if(dateStartDate>=dateToday){
    print("Yes")
}
else{
    print("Today date is 28/02/2018. Why it print No?")
}

A: You need to timeZone for your dateFormatter:
dateFormatter.timeZone = TimeZone(secondsFromGMT:0)!


Q: How to bypass onCompleted I use BehaviorSubject to make a stream of events from different sources.
Being simplified, It look like that:
BehaviorSubject subject = BehaviorSubject.create();
Observable<Integer> src1 = Observable.just(1, 2, 3);
Observable<Integer> src2 = Observable.just(4, 5, 6);
Observable<Integer> src3 = Observable.just(7, 8, 9);
src1.subscribe(subject);
src2.subscribe(subject);
src3.subscribe(subject);
subject.subscribe(this::log);

In this example values from src1 only will be logged, because no more subject subscription will exists after src1 completion.
How could I bypass completion events from all the sources? Is there an operator like ignoreCompleted()?

A: Use this, it ignores onComplete() and onError(): https://github.com/JakeWharton/RxRelay


Q: MVC4 403 forbidden error with siteminder We have a MVC4 application running on a windows server 2008 with iis 7.5. everything was running fine until out SSO team installed siteminder for single sign on.
Now the application after the SSO redirect is giving a 403 forbidden error. Any Suggestions?
Here's what is happening.
1. access the site.
2. Site redirects to SSO page
3. after entering the credentials (everything is validated as the siteminder trace and logs is showing no errors)
4. application redirects the original entered url and we see a 403.
we currently have no implementation that uses the SSO user coz we were waiting for the SSO to be setup and our current authentication in web config is set to "None"
application was all good before the siteminder and the url was accessible.
Verified everything but not sure what is the issue.
1. Application pool is set to 4.0
2. TestConnection is ok for authorization and authentication
3. No errors in siteminder logs (the SM cookie is set correctly)
4. We do not have SSL
5. this is the only site running on the server
6. IIS_IUSRS is given access to the sites root folder
Not sure if there is anything we can do in the sites web config. though as i have mentioned before it was all ok before site minder. Now Even if we disable the siteminder the application just return 403 forbidden.
please help!!

A: well we finally reached out to some people with extensive siteminder experience and they suggested to use the "classic" app pool instead of "Integrated" which solved our issue.


Q: jsPDF: addHTML method not working I created html table and tried to generate pdf using jsPDF.
I have used following code:
var pdf = new jsPDF('p','pt','a4');
pdf.addHTML(document.getElementById('pdfTable'),function() {
  console.log('pdf generated');
});
pdf.save('pdfTable.pdf');

I am getting blank pdf file. Am I doing anything wrong?
Here is a plunker for this.
Working demo  of jsPDF with addHTML function.

A: Made working plunker for this:
Update:
I have updated the plunker and made it work with addHTML() function:
var pdf = new jsPDF('p','pt','a4');
//var source = document.getElementById('table-container').innerHTML;
console.log(document.getElementById('table-container'));
var margins = {
   top: 25,
   bottom: 60,
   left: 20,
   width: 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.text(20, 20, 'Hello world.');
pdf.addHTML(document.body, margins.top, margins.left, {}, function() {
   pdf.save('test.pdf');
});

You can see plunker for more details.

A: Change this in app.js:
  pdf.addHTML(document.getElementById('pdfTable'),function() {
      });
  pdf.save('pdfTable.pdf');

for this one:
pdf.addHTML(document.getElementById('pdfTable'),function() {
    pdf.save('pdfTable.pdf');
});

A: I took out everything but these:
<script src="//mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script>
<script src="//html2canvas.hertzen.com/build/html2canvas.js"></script>

then I used this:
  $(document).ready(function() {

        $("#pdfDiv").click(function() {

    var pdf = new jsPDF('p','pt','letter');

    var specialElementHandlers = {
    '#rentalListCan': function (element, renderer) {
        return true;
        }
    };

    pdf.addHTML($('#rentalListCan').first(), function() {
        pdf.save("rentals.pdf");
    });
    });
});

I can print the table... looks great with chrome, safari or firefox, however, I only get the first page if my table is very large.

A: In app.js change:
  pdf.addHTML(document.getElementById('pdfTable'),function() {

  });
  pdf.save('pdfTable.pdf');

to
  pdf.addHTML(document.getElementById('pdfTable'),function() {
      pdf.save('pdfTable.pdf');
  });

If you see a black background, you can add to sytle.css "background-color: white;"

A: Instead of using the getElementById() you should use querySelector()
var pdf = new jsPDF('p','pt','a4');
pdf.addHTML(document.querySelector('#pdfTable'), function () {
  console.log('pdf generated');
});

pdf.save('pdfTable.pdf');

A: I have test this in your plunker.
Just update your app.js
pdf.addHTML(document.getElementById('pdfTable'), function() {
      pdf.save('pdfTable.pdf');
});

update your css file:
#pdfTable{
  background-color:#fff;
}


Q: How to return all the rows in tracker_sessions table using antonioribeiro/tracker I am using antonioribeiro/tracker for my website analytics.
Everything is working as intended but I want to count all the rows in tracker_sessions table, when I do
$sessions = Tracker::sessions();
return count($sessions);

It returns only the number of rows created today.
How would I return all the rows in tracker_sessions table?

A: Looking at the documentation, you can do this to get more sessions:
$sessions = Tracker::sessions(60 * 24 * 365 ); // get sessions (visits) from the past 365 days

.., or any number of minutes you want.
You can also use Query Builder to count the table directly:
use Illuminate\Support\Facades\DB;

$sessions = DB::table('tracker_sessions')->count();


Q: In Visual Studio (2010), how do I get the little method information help box to pop up again? I know that Ctr+Space is to bring up intellisense for code completion, but how do I get this little box to pop up, which is the one that provides method and parameter info:

At the moment, if I lose it, I backspace the comma, then it pops up when I re-enter the comma. I'm sure there's a keyboard shortcut I'm missing though.

A: You can bring it back up with
Ctrl + Shift + Space


Q: What is Java Regex to check if a String is a chain of numbers delimited by "_" (java)? I want to check if a String  is a chain of numbers delimited by "_":
Examples:
200_121_545  : return true;
455          : return true;  // it doesn't need _ to be valid, a number is ok
ff_78        : return false;
2212 _55     : return false; // no space in the string
121212@44    : return false;

The number of numbers is unknown inadvanced. Ex: it could be 21212_545 or 45_545_78

A: If you want each number to have at least one non-zero digit you may try something like this (updated with help of Tims comments):
^0*[1-9]\\d*(_0*[1-9]\\d*)*$

The [1-9] makes sure there is (at least) one non-zero digit in each group, where as the 0* before allows any number of zeros. After that one non-zero digit, any digits including (but not only) zero can be allowed: \\d*.
Update 2: Added anchors as suggested by Daniël to make sure the whole string is matched.

A: As it stands you will need to define your regexp of what you consider a number and repeat it. As far as I can tell you would like to have something like
s.matches("0[1-9][0-9]*|[1-9][0-9]*")

to match a single number string. As regexps cannot be factored you will need to repeat yourself for the _, as in
s.matches("0[1-9][0-9]*|[1-9][0-9]*(_(0[1-9][0-9]*|[1-9][0-9]*)*")

that should do the trick as long as you do not want 0 as an answer and you want to avoid double leading zeros. In all it is a horrible expression though.

A: try this
s.matches("\\d*[1-9](_\\d+)*")


Q: The function table.setColumnLayout(columnSettings); is not working for me I've written a function to create tables with different column setups and different data based on the parameters I send it. That all works fine.
My problem is that I can't get the setColumnLayout function to work when I want to reconfigure the existing table with new data and column settings. I know that the column settings are correct because they work for table creation.
The code, table.clearData(); , in the top section works normally.
I'm also unable to get the destroy function to work. As far as I could tell that is for Tabulator 3.0.
I am using Mac Chrome 76 and Tabulator 4.3.
Any help letting me know what I'm doing wrong would be apreciated.
Thanks, Mike
function  createTable (tabledata,SelectedColumnSettings){

     $("#clear").click(function(){
        table.clearData();

         var columnSettings = [
            {title:"id", field:"id", visible:false},
            {title:"Company", field:"Company Name", sorter:"string"},
            {title:"Name", field:"Name", sorter:"string"},
            {title:"Word Count Rate", field:"Word Count Rate", sorter:"number",  align:"center"},
            {title:"Hourly Rate", field:"Hourly Rate", sorter:"number",  align:"center"},
            {title:"Resourced", field:"Resourced", sorter:"number",  align:"center"},
            {title:"Language Source", field:"Language Source", sorter:"string"},
            {title:"Profile Picture", field:"Profile Picture", align:"center"},
            {title:"Completed Projects", field:"Completed Projects", sorter:"number",  align:"center"}];

       // var columnSettings=getColumnSettings("Contacts");
        table.setColumnLayout(columnSettings);
     });

        var columnSettings=getColumnSettings(SelectedColumnSettings); // get the settings for the selected list

        var table = new Tabulator("#example-table", {

        height:600, // set height of table to enable virtual DOM

        resizableColumns:false, // this option takes a boolean value (default = true)

        data:tabledata, //load initial data into table
        layout:"fitDataFill", //fit columns to width of table (optional)

        columns: columnSettings,  //Define Table Columns. Sets columns for the different lists projects, contacts....

       });

  };    // end create table

I'm not getting any errors.

A: setColumnLayout needs to be done in conjunction with getColumnLayout. Not sure where SelectedColumnSettings is coming from. Also getColumnSettings is a property of a table and I do see it being called that way:
var columnSettings=getColumnSettings(SelectedColumnSettings);

A: Use  Set Column
         var columnSettings = [
            {title:"id", field:"id", visible:false},
            {title:"Company", field:"Company Name", sorter:"string"},
            {title:"Name", field:"Name", sorter:"string"},
            {title:"Word Count Rate", field:"Word Count Rate", sorter:"number",  align:"center"},
            {title:"Hourly Rate", field:"Hourly Rate", sorter:"number",  align:"center"},
            {title:"Resourced", field:"Resourced", sorter:"number",  align:"center"},
            {title:"Language Source", field:"Language Source", sorter:"string"},
            {title:"Profile Picture", field:"Profile Picture", align:"center"},
            {title:"Completed Projects", field:"Completed Projects", sorter:"number",  align:"center"}];

       // var columnSettings=getColumnSettings("Contacts");

   table.setColumn(columnSettings);


Q: Strange behavior with var in Chrome I'm getting some very strange behavior in Chrome v57.0.2987.133 using JavaScript:
Here is my code:
var firstName = "Bob";
var lastName = "Smith";
var age = 29;

function happyBirthdayLocal(first, last, a) {
    a = a + 1;
    message = "Happy Birthday to " + first + " " +
                last + " who just turned " + a;
    console.log(message);
}
happyBirthdayLocal(firstName, lastName, age);

As expected, because I did not use var in front of message in the function, message acts like a global variable, and I can access window.message in the developer console.
However, if I insert a line accessing message above the call to the function, like so:
var firstName = "Bob";
var lastName = "Smith";
var age = 29;

function happyBirthdayLocal(first, last, a) {
    a = a + 1;
    message = "Happy Birthday to " + first + " " +
                last + " who just turned " + a;
    console.log(message);
}
console.log(message);
happyBirthdayLocal(firstName, lastName, age);

(no other changes!) now, I'm getting an uncaught reference error, and window.message is no longer defined.
My sense is that "failing to declare variables will very likely lead to unexpected results" is at play here and it seems Chrome is in an in-between place with regards to defaulting to global vs. local scope for undeclared variables depending on other use in the program? Can anyone confirm this?
I get similar results in Firefox. I've tried searching for specific information regarding what the default behavior is for undeclared variables in both Firefox and Chrome and didn't find anything more enlightening other than to potentially expect strange behavior.
(I'm a bit surprised this hasn't broken a bunch of people's code actually. Or maybe it has. My (mis)use of the variable here--not declaring it--is in the context of teaching about global vs. local scope; I wouldn't on purpose forget to declare a variable (and would lint my code anyway) so this is the first time I've noticed this behavior.)
Thank you in advance for any insight.

A: Step through it in order.
First, due to hoisting, the variables firstName, lastName, age are declared, and the function happyBirthdayLocal is also declared.
Then, firstName, lastName, age are all assigned their values.
Next you call console.log(message);. Uh-oh, message hasn't been defined yet. That doesn't happen until happyBirthdayLocal is actually called for the first time, which would be on the following line.
Due to the error, which is fatal, the function is never called, and message remains undefined.


Q: Elasticsearch port 9300 django I'm facing a strange issue, using Django Haystack and ElasticSearch so I can't rebuild_index.
ElasticSearch is properly running on the machine :
$ curl -X GET 'http://localhost:9200'
{
  "status" : 200,
  "name" : "Ziggy Pig",
  "cluster_name" : "elasticsearch",
  "version" : {
  "number" : "1.7.2",
  "build_hash" : "e43676b1385b8125d647f593f7202acbd816e8ec",
  "build_timestamp" : "2015-09-14T09:49:53Z",
  "build_snapshot" : false,
  "lucene_version" : "4.10.4"
  },
  "tagline" : "You Know, for Search"
}

But this is the log of ElasticSearch :
[2017-11-29 18:25:22,723][INFO ][node] [Ziggy Pig] initialized
[2017-11-29 18:25:22,724][INFO ][node] [Ziggy Pig] starting ...
[2017-11-29 18:25:22,913][INFO ][transport] [Ziggy Pig] bound_address
     {inet[/127.0.0.1:9300]}, publish_address {inet[/10.142.0.2:9300]}
[2017-11-29 18:25:22,937][INFO ][discovery] [Ziggy Pig] .
     elasticsearch/HWEvbIkAR3mFwcGeHIa7Cg
[2017-11-29 18:25:26,710][INFO ][cluster.service] [Ziggy Pig]
    new_master [Ziggy Pig][HWEvbIkAR3mFwcGeHIa7Cg][stagelighted]
    [inet[/10.142.0.2:9300]], reason: zen-disco-join(elected_as_master)
[2017-11-29 18:25:26,734][INFO ][http] [Ziggy Pig] bound_address
     {inet[/127.0.0.1:9200]}, publish_address {inet[/10.142.0.2:9200]}
[2017-11-29 18:25:26,734][INFO ][node] [Ziggy Pig] started
[2017-11-29 18:25:26,762][INFO ][gateway] [Ziggy Pig] recovered [1]
     indices into cluster_state
[2017-11-29 18:26:22,946][WARN ][cluster.service] [Ziggy Pig] failed to
     reconnect to node [Ziggy Pig][HWEvbIkAR3mFwcGeHIa7Cg]
     [stagelighted][inet[/10.142.0.2:9300]]
org.elasticsearch.transport.ConnectTransportException: [Ziggy Pig][inet[/10.142.0.2:9300]] connect_timeout[30s]
at org.elasticsearch.transport.netty.NettyTransport.connectToChannels(NettyTransport.java:825)
at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:758)
at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:731)
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:216)
at org.elasticsearch.cluster.service.InternalClusterService$ReconnectToNodes.run(InternalClusterService.java:584)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused: /10.142.0.2:9300
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.connect(NioClientBoss.java:152)
at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.processSelectedKeys(NioClientBoss.java:105)
at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:79)
at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337)
at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42)
at org.elasticsearch.common.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
at org.elasticsearch.common.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)

I installed JAVA and Elastisearch with this tutorial
My app running in Google Compute Engine
If someone can help me.

My settings:
ELASTICSEARCH_INDEX_SETTINGS = {
'settings': {
    "analysis": {
        "analyzer": {
            "synonym_analyzer" : {
                "type": "custom",
                "tokenizer" : "standard",
                "filter" : ["synonym"]
            },
            "ngram_analyzer": {
                "type": "custom",
                "tokenizer": "lowercase",
                "filter": ["haystack_ngram", "synonym"]
            },
            "edgengram_analyzer": {
                "type": "custom",
                "tokenizer": "lowercase",
                "filter": ["haystack_edgengram"]
            }
        },
        "tokenizer": {
            "haystack_ngram_tokenizer": {
                "type": "nGram",
                "min_gram": 3,
                "max_gram": 15,
            },
            "haystack_edgengram_tokenizer": {
                "type": "edgeNGram",
                "min_gram": 2,
                "max_gram": 15,
                "side": "front"
            }
        },
        "filter": {
            "haystack_ngram": {
                "type": "nGram",
                "min_gram": 3,
                "max_gram": 15
            },
            "haystack_edgengram": {
                "type": "edgeNGram",
                "min_gram": 2,
                "max_gram": 15
            },
            "synonym" : {
                "type" : "synonym",
                "ignore_case": "true",
                "synonyms_path" : "synonyms.txt"
            }
        }
    }
  }
}

HAYSTACK_CONNECTIONS = {
  'default': {
    'ENGINE': 'elasticstack.backends.ConfigurableElasticSearchEngine',
    'URL': 'http://127.0.0.1:9200/',
    'INDEX_NAME': 'haystack',
  },
}
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 100

A: I think you have a typo in your settings.py file: You're trying to connect to port 9300 while elasticsearch is running on port 9200:
Caused by: java.net.ConnectException: Connection refused: /10.142.0.2:9300

Can you post the relevant parts of your settings.py file if that doesn't solve the issue?
EDIT
Looking through a few relevant posts, it seems as though nodes communicate with each other via port 9300 as well as port 9200. Does your ping work on port 9300 as well? If not, that may also need to be opened up.
Possibly related: https://discuss.elastic.co/t/elasticsearch-port-9200-or-9300/72080


Q: How to improve performance with MonetDB on OSX? I am using monetdb on a 16GB Macbook Pro with OSX 10.10.4 Yosemite.
I execute queries with SQLWorkbenchJ (configured with a minimum of 2048M RAM).
I find the performance overall erratic:

*

*performance is acceptable / good with small size tables (<100K rows)

*abysmal with tables with many rows: a query with a join of two tables (8670 rows and 242K rows) and a simple sum took  1H 20m!!

My 16GB of memory notwithstanding, in one run I never saw MSERVER5 using more than 35MB  of RAM, 450MB in another.  On the other hand the time is consumed swapping data onto disk (according to Activity Monitor over 160GB of data!).
There are a number of performance-related issues that I would like to understand better:

*

*I have the impression that MonetDB struggles with understanding how much RAM to use / is available in OSX.  How can I "force" MonetDB to use more RAM?

*I use MonetDB through R.  The MonetDB.R driver converts all the character fields into CLOB.  I wonder if CLOBs create memory allocation issues?

*I find difficult to explain the many GBs of writes (as mentioned >150GB!!) even for index creation or temporary results.  On the other hand when I create the DB and load the tables overall the DB is <50MB. Should I create an artificial integer key and set it as index?

*I join 2 tables on a timestamp field (e.g. "2015/01/01 01:00") that again is seen as a text CLOB by MonetDb / MonetDb.R. Should I just convert it to integer before saving it to MonetDb?

*I have configured each table with a primary key, using a field of type integer. MonetDB (as a typical columnar database) doesn't need the user to specify an index.  Is there any other way to improve performance?

Any recommendation is welcome.
For clarity the two tables I join have the following layout:
Calendar # classic calendar table with one entry per our in a year = 8760 rows
Fields: datetime, date, month, weekbyhour, monthbyday, yearbyweek, yearbymonth # all fields are CLOBs as mentioned

Activity # around 200K rows
Fields: company, department, subdepartment, function, subfunction, activityname, activityunits, datetime, duration # all CLOBs except activityunits; datetime refers to when the activity has occurred

I have tied various types of join syntax, but an example would (`*` used for brevity)
select * from Activity as a, Calendar as b where a.datetime=b.datetime


Q: Accidentally ran php artisan clear - compiled services and packages files removed Just as I was getting ready to run:
php artisan cache:clear
php artisan view:clear
php artisan route:clear

...for debugging purposes, I ended up running php artisan clear instead. I got back the following output:

Compiled services and packages files removed!

What have I just done and how do I undo it? My application still seems to work fine, but if things are broken I'd rather roll things back now rather than get further down the line before I eventually realise that they are. If things aren't broken, I'd still like to know what I just did.

A: A preliminary answer before someone who can do more than read through the help commands comes along:
Although:
php artisan clear

...isn't listed in artisan's documentation at all (or at least not in php artisan list), based on its output it seems to be an alias of:
php artisan clear-compiled

This seems to be confirmed by php artisan help clear-compiled:
Description:
  Remove the compiled class file

Usage:
  clear-compiled

Although that help command doesn't really clear up much, like what exactly compiled class files are or what relation they have to any of the other clear commands, I'm guessing the command does something similar to:
php artisan view:clear

...which does the following according to its own help command:
Description:
  Clear all compiled view files

Usage:
  view:clear

Based on the above, I can only guess that running php artisan clear is about as harmless as running php artisan view:clear, in that both are designed to clear away compiled files that, when cleared, are simply recompiled again on the next build.
How exactly php artisan clear differs from php artisan view:clear and why it needs its own separate command and a much more memorable alias than any of the other clear commands is still... unclear.

BONUS
To anyone else that arrived here because they find themselves constantly running some variation of the above commands for debugging and troubleshooting, I just learnt about the php artisan optimize:clear command, which runs all of these commands at once:
php artisan view:clear
php artisan cache:clear
php artisan route:clear
php artisan config:clear
php artisan clear

and returns the following output:
Compiled views cleared!
Application cache cleared!
Route cache cleared!
Configuration cache cleared!
Compiled services and packages files removed!
Caches cleared successfully!


Q: Get property value and convert class type to boolean I have following piece of code:
 ClassName class = new ClassName();

 var getValue = GetPrivateProperty<BaseClass>(class, "BoolProperty");

 public static T GetPrivateProperty<T>(object obj, string name)
    {
        BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
        PropertyInfo field = typeof(T).GetProperty(name, flags);
        return (T)field.GetValue(obj, null);
    }

Now when I get an InvalidCastException in the return statement that he can not convert the object with type System.Boolean to the type ClassName.
BaseClass has the property. ClassName inherits from BaseClass. In have to access all properties from the "ClassName" Class. Since this property is private, I have to access it directly over the BaseClass. This works but I crashes because the property has the return value boolean.
Thanks!

A: You got the property of type T and the return value should also be of type T? I don't believe that.
Maybe this will help:
var getValue = GetPrivateProperty<bool>(class, "BoolProperty");

public static T GetPrivateProperty<T>(object obj, string name)
{
    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    PropertyInfo field = null;
    var objType = obj.GetType();
    while (objType != null && field == null)
    {
        field = objType.GetProperty(name, flags);
        objType = objType.BaseType;
    }

    return (T)field.GetValue(obj, null);
}

Please see the changes of <BaseClass> to <bool> and typeof(T).GetProperty to obj.GetType().GetProperty.


Q: Does GRPC have a Channel that can be used for testing? I'd like to create a simple test but with RPC within the same JVM.
What I was thinking was something like
@Test
void foo() {
    Channel channel = new SomeMagicalObject(new MySystemImpl());
    SystemStub stub =  SystemGrpc.newStub(channel);

    var ret = stub.doSomething(...)
    assertThat(ret).isTrue();
}

I was wondering if there's something already built that implements Channel that takes in a GRPC server implementation.  That way I avoid having to run Netty and manage ports etc. Like this...
private static Server server;
private static Channel channel;

@BeforeAll
@SneakyThrows
static void setupServer() {
    server = ServerBuilder.forPort(0)
            .addService(new MySystemImpl())
            .build()
            .start();
    channel = ManagedChannelBuilder.forAddress("localhost", server.getPort())
            .usePlaintext()
            .build();

}

@AfterAll
@SneakyThrows
static void teardownServer() {
    server
            .shutdown()
            .awaitTermination();
}

A: The InProcess transport is what you want. It is a full-fledged transport, but uses method calls and some tricks to avoid message serialization. It is ideally suited to testing, but is also production-worthy. When used with directExecutor(), tests can be deterministic. InProcess transport is used in the examples. See HelloWorldServerTest for one usage.
private static Server server;
private static Channel channel;

@BeforeAll
@SneakyThrows
static void setupServer() {
    // This code, except for the server.start(),
    // could be moved to the declarations above.
    server = InProcessServerBuilder.forName("test-name")
            .directExecutor()
            .addService(new MySystemImpl())
            .build()
            .start();
    channel = InProcessChannelBuilder.forName("test-name")
            .directExecutor()
            .build();
}

@AfterAll
@SneakyThrows
static void teardownServer() {
    server.shutdownNow();
    channel.shutdownNow();

    // Useful if you are worried about test
    // code continuing to run after the test is
    // considered complete. For a static usage,
    // probably not necessary.
    server.awaitTermination(1, SECONDS);
    channel.awaitTermination(1, SECONDS);
}


Q: Unroll / splat arguments in common lisp Say I have a list of arguments:
> (setf format-args `(t "it's ~a" 1))
(T "it's ~a" 1)

How can I then "splat" or "unroll" this into a series of arguments rather than a single list argument, for supplying to the format function?
i.e I would like the following function call to take place:
> (format t "it's ~a" 1)

For reference, I would write the following in python or ruby:
format(*format-args)

I'm sure it can be done, but perhaps I'm thinking about it wrong. It also doesn't help that the name for this operation doesn't seem to be terribly well agreed upon...

A: Oops! I should have remembered how javascript does it.
Turns out you use the apply function, as in:
(apply #'format format-args)


Q: Drupal trial account development I am creating a website where you can create an account with your name and email. When this is done, you get a 30 day trial. From this point, you can 'upgrade' your account by supplying more information.
When you do not update your information after 30 days, your account is suspended.
Can anyone give me some tips how to do this ?
So:
- Create profile with email and name (easy), indicator is stored in db that you are trial user.
- When you log in, you can extend your profile with extra information. indicator that you are full user.

A: You can always write your own module to do it, but my recommendation is using the Rules module, and using several user roles.

*

*Any new user gets a "trial" role he registers.

*Create the needed fields in the user profile

*Create a rule which will change the user's role in case the field is filled (rule triggeres whenever user profile is updated).

*Create a rule with cron that executes once a day, to suspend user account, and probably to send him a notification before doing so.


Q: Swift: Modifying an Array using a variable to specify the array name I am working on an app that parses XML responses from a web service.  This web service will return several instances of an object of many different types using object stacking.  I just want to take these objects and populate them into an array.  Right now I have a switch that is repeating several different lines of similar code based on "objectStack.last" type.  This is what it looks like right now in the parserDidEndElement function of the XML parser:
    switch(objectStack.last){
    case _ as apple:
        apples.removeAll()
        for apple in objectStack as! [apple]{
            apples.append(apple.name.value)
        objectType = "apple"
        }
    case _ as orage:
        oranges.removeAll()
        for orange in objectStack as! [orange]{
            oranges.append(orange.name.value)
        }
        objectType = "orange"
    case _ as bananas:
        bananas.removeAll()
        for banana in objectStack as! [banana]{
            bananas.append(banana.name.value)
        }
        objectType = "banana"
    case default:
        break

The problem is that the webservice will be returning a large number of different types, and I would rather not have to build a switch case for each.  For the purposes of this discussion, let's say I have created an empty array for each type just by adding a "s" to the type name (ie apples, oranges and bananas).  Is there a way for me to manipulate the arrays using a variable?  Something like this:
   objectStack.last + "s".removeAll()
   for objectStack.last in objectStack.last + "s" as! [objectStack.last]{
      objectStack.last + "s".append(objectStack.last.name.value)
      objectType = objectStack.last
   }

Obviously this second code block is not valid code, I'm just hoping it helps to illustrate what I am trying to accomplish.
Thanks in advance for your help!

A: I ended up using inheritance to fix my issue.  Although I have objects of many types, I created a "baseObject" class that contains the fields I needed for this to be successful.  I was then able to use the following:
for obj in objectStack{
    let obj2 = obj as! baseObject
    fieldArrays[objectType]!.append(obj2.name.value)
}

I also used the solution here to use a dictionary to populate the correct array using the "didSet" event on the dictionary.


Q: Haskell Unit Testing integrated in Leksah I'm writing some Haskell code in the Leksah IDE. As I edit the code, Leksah does background compilation and runs unit tests after the background compilation completes.
I see in the "console" frame the following:
Building UNFI-EIC-0.0.1...
Preprocessing test suite 'test-UNFI-EIC' for UNFI-EIC-0.0.1...
Preprocessing executable 'UNFI-EIC' for UNFI-EIC-0.0.1...
-----------------------------------------
Running 1 test suites...
Test suite test-UNFI-EIC: RUNNING...
test-UNFI-EIC: Prelude.head: empty list
Test suite test-UNFI-EIC: FAIL
Test suite logged to: dist/test/UNFI-EIC-0.0.1-test-UNFI-EIC.log
0 of 1 test suites (0 of 1 test cases) passed.

Where are the default test cases that failed? How do I add relevant unit tests to them? There is nothing obvious in the GUI menus...
How can I edit the test suite for the package that is integrated in Leksah?

A: You can edit the unit test suite by finding the test-suite reference in the .cabal file of the project.
To do this, go to your project directory and open *.cabal in a text editor and search for the line containing test-suite:. This line will be of the form test-suite: ExampleTests, where ExampleTests is the main file of the test suite for the project.
Simply add tests to this file using the testing framework of your choice. Leksah will run these tests automatically through the IDE GUI.


Q: Image preprocessing before feeding into Deep learning algorithm I am developing an image segmentation algorithm, I used Deeplabv3+ to train a model, which performs fine. The question is if I can improve its performance. I would like to know if there is preprocessing methods to use before feeding the image.
I want to detect the charging connector, as depicted in the image:

I can detect it without any problem. But just looking for some improvements if exist.


Q: Pandas: Find date of last edit for each element in Dataframe Hope to express myself correctly in the following as it seems to be a complicated one.
My department is regularly creating daily snapshots at random times for our current project portfolio website. Below, I have filtered the entire table for all snapshot with project_id = 1. Filtering here to make it more understandable as there are many projects. Moreover, I have reduced the number of columns for this example.
df_table
project_id  project_name  region  style   effect   representative lazy  timestamp
1           PullPressure  EU      A-B-C   Pull     Martin         DCA   10/01/20
1           PullPressure  EU      A-B-C   Pull     Martin         DCA   09/05/20
1           PushPressure  EU      A-B-C   Push     Martin               08/20/20
1           PressurePush  EU      A-B-C   Push     Martin               04/06/20
1           PressurePush  US      A-B-C   Push     Johnsson             12/31/19
1           PressurePush  US      A-B-C   Push     Johnsson             10/15/19

My goal is to find out when the last change for any columns of project_id (or in general any key_column) has occurred, i.e. when was each cell for a given id last edited?
My goal is to achieve something like this:
df_table_new:
project_id  project_name region       style        effect       representative  lazy        timestamp
1           08/20/20     04/06/20     10/15/19     09/05/20     04/06/20        09/05/20    10/01/20
1           08/20/20     04/06/20     10/15/19     09/05/20     04/06/20        09/05/20    09/05/20
1           08/20/20     04/06/20     10/15/19     10/15/19     04/06/20        10/15/19    08/20/20
1           10/15/19     04/06/20     10/15/19     10/15/19     04/06/20        10/15/19    04/06/20
1           10/15/19     10/15/19     10/15/19     10/15/19     10/15/19        10/15/19    12/31/19
1           10/15/19     10/15/19     10/15/19     10/15/19     10/15/19        10/15/19    10/15/19

Please let me know in case anything is unclear!
edit: having null values inside the column, results in an NaT error as such:
lazy
09/05/20
09/05/20
NaT
NaT
NaT
NaT

Whereas, instead of NaT the values the fields should refer to the oldest available timestamp in timestamp column, which is 10/15/19.
edit2: Solved with the solution of @jezrael by adding the respective elements to the function. Well appreciated!

A: Use GroupBy.transform with GroupBy.last for each column generated by Index.difference:
df['timestamp'] = pd.to_datetime(df['timestamp'], format='%m/%d/%y')

for c in df.columns.difference(['project_id','timestamp']):
    df[c] = df.groupby(['project_id',c], sort=False)['timestamp'].transform('last')
print (df)

   project_id project_name     region      style     effect representative  \
0           1   2020-09-05 2020-04-06 2019-10-15 2020-09-05     2020-04-06
1           1   2020-09-05 2020-04-06 2019-10-15 2020-09-05     2020-04-06
2           1   2020-08-20 2020-04-06 2019-10-15 2019-10-15     2020-04-06
3           1   2019-10-15 2020-04-06 2019-10-15 2019-10-15     2020-04-06
4           1   2019-10-15 2019-10-15 2019-10-15 2019-10-15     2019-10-15
5           1   2019-10-15 2019-10-15 2019-10-15 2019-10-15     2019-10-15

   timestamp
0 2020-10-01
1 2020-09-05
2 2020-08-20
3 2020-04-06
4 2019-12-31

If need original format add Series.dt.strftime:
df['timestamp'] = pd.to_datetime(df['timestamp'], format='%m/%d/%y')

for c in df.columns.difference(['project_id','timestamp']):
    df[c] = (df.groupby(['project_id',c], sort=False)['timestamp'].transform('last')
               .dt.strftime('%m/%d/%y'))
print (df)

   project_id project_name    region     style    effect representative  \
0           1     09/05/20  04/06/20  10/15/19  09/05/20       04/06/20
1           1     09/05/20  04/06/20  10/15/19  09/05/20       04/06/20
2           1     08/20/20  04/06/20  10/15/19  10/15/19       04/06/20
3           1     10/15/19  04/06/20  10/15/19  10/15/19       04/06/20
4           1     10/15/19  10/15/19  10/15/19  10/15/19       10/15/19
5           1     10/15/19  10/15/19  10/15/19  10/15/19       10/15/19

   timestamp
0 2020-10-01
1 2020-09-05
2 2020-08-20
3 2020-04-06
4 2019-12-31
5 2019-10-15

EDIT: Add fillna by minimal timestamp:
df['timestamp'] = pd.to_datetime(df['timestamp'], format='%m/%d/%y')
min1 = df['timestamp'].min()

for c in df.columns.difference(['project_id','timestamp']):
    df[c] = df.groupby(['project_id',c], sort=False)['timestamp'].transform('last').fillna(min1)
print (df)
   project_id project_name     region      style     effect representative  \
0           1   2020-09-05 2020-04-06 2019-10-15 2020-09-05     2020-04-06
1           1   2020-09-05 2020-04-06 2019-10-15 2020-09-05     2020-04-06
2           1   2020-08-20 2020-04-06 2019-10-15 2019-10-15     2020-04-06
3           1   2019-10-15 2020-04-06 2019-10-15 2019-10-15     2020-04-06
4           1   2019-10-15 2019-10-15 2019-10-15 2019-10-15     2019-10-15
5           1   2019-10-15 2019-10-15 2019-10-15 2019-10-15     2019-10-15

        lazy  timestamp
0 2020-09-05 2020-10-01
1 2020-09-05 2020-09-05
2 2019-10-15 2020-08-20
3 2019-10-15 2020-04-06
4 2019-10-15 2019-12-31
5 2019-10-15 2019-10-15


Q: Can you insert jquery into a php file? I have the following .php file:

<div class="excerpt">
  <?php get_the_excerpt();?>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $(".excerpt").hide();
  });
</script>

I want to hide the div class "excerpt" through jQuery. Unfortunately, the code doesn't do anything and I do not understand where I went wrong. Is it even possible to use jQuery in php?

A: identifier $ will usually won't be enabled by default in wordpress like cms
you have to use identifier jQuery
inorder to make identifier $ work, you can try this
(function($){
    // inside this scope, $ can be used
    $(document).ready(function(){

        // other scripts

    });
})(jQuery);


Q: Notepad++ NppExec run in cmd How can I make my commands run in NppExec run in cmd, as opposed to the built in console, which doesn't work with things like: "Press any key to continue", which only works when you press enter?

A: You want to take a look at cmd /? output and http://ss64.com/nt/.  Using start along with cmd /c will give an external window and using cmd /k will keep it in the nppexec console.  One thing I don't like about the /k option is that it really isn't true as 'any key' doesn't do the trick and Enter needs to be used.
Test it out with cmd /k pause and start cmd /c pause.
Notice the start option has the window close, so any history will go away too.  If that's important then substitute /k for the /c and use exit when done.


Q: Cannot get same cursor for all objects and events in a window I have searched and tested a lot and have not found a way to force a window and all children use the same cursor for all events.
In the example code below I want the DIAMOND_CROSS cursor used even when hovering over the Gtk.Paned handle. As it is now it switches to the horizontal sizing arrow.
import gi
gi.require_version('Gdk', '3.0')
gi.require_version('Gtk', '3.0')
from gi.repository import Gdk, Gtk

class MainWindow(Gtk.ApplicationWindow):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.connect("realize", self.on_realize)
        self.connect('delete_event', Gtk.main_quit)
        self.set_default_size(800, 600)

        button1 = Gtk.Button('Button 1')
        button2 = Gtk.Button('Button 2')

        paned = Gtk.Paned()
        paned.set_position(400)
        paned.add1(button1)
        paned.add2(button2)

        self.add(paned)
        self.show_all()

    def on_realize(self, widget):
        cursor = Gdk.Cursor(Gdk.CursorType.DIAMOND_CROSS)
        self.get_window().set_cursor(cursor)

if __name__ == '__main__':
    win = MainWindow()
    Gtk.main()

A: I just checked the source of the paned object which has the following code in the gtk_paned_state_flags_changed function:
if (gtk_widget_is_sensitive (widget))
    cursor = gdk_cursor_new_from_name (gtk_widget_get_display (widget),
                                       priv->orientation == GTK_ORIENTATION_HORIZONTAL
                                       ? "col-resize" : "row-resize");
else
    cursor = NULL;

(https://git.gnome.org/browse/gtk+/tree/gtk/gtkpaned.c?h=3.18.6#n1866)
Thus in theory you could overwrite the do_state_flags_changed function of the paned widget (and all other widget that have behavior like this) to achieve the result you want.
But as you ask for a way to set the cursor for all objects in one go the answer is simply: No, that is not possible.


Q: How to properly dispose of a pthread mutex? I wrote a class to wrap a mutex. In the destructor, I call pthread_mutex_destroy and sometimes it returns EBUSY because some other thread has not released it. My question is, what is the best way to handle the destruction of a mutex? Should I wait for it to be free?
Here is what I have so far, which may not be the best solution:
Mutex::~Mutex()
{
    int rc = pthread_mutex_destroy( &_mutex );
    while ( rc == EBUSY )
    {
        lock(); // Call to pthread_mutex_lock
        unlock(); // Call to pthread_mutex_unlock

        // Attempt destroy again
        rc = pthread_mutex_destroy( &_mutex );
    }
}

A:
My question is, what is the best way to handle the destruction of a mutex? Should I wait for it to be free?

You should not destroy resources while they are being used because that often leads to undefined behaviour.
The correct course of action is:

*

*Tell the other thread to release the resources and wait till it does, or

*Tell the other thread to terminate politely an wait till it has done so, or

*Pass the ownership of the resource to another thread and let it manage the resource's lifetime as it pleases, or

*Use shared resources, so that they stay alive while its users are still around.


Q: VueJS data() not working I am trying to make a VueJS app but I am failing even with the simplest examples.
I am using Laravel 5.3 with pre-built support for VueJS (version 1, I tried version 2 as well).
Here is my Example.vue component
<template>

        {{ name }}

</template>

And here is the main code
Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app'
});

This is the error that shows up everytime in console:
[Vue warn]: Property or method "name" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in component )
Any ideas whats wrong?
Thanks

A: In your script tags instead of export default use:
module.exports = {
  data() {
    return { counter: 1 }
  }
}

This should work for you

A: Call the component inside your template

Vue.component('example', {
  template: `<div class="profile">{{ name }}</div>`,
  data () {
return {
  name: 'John Doe'
}
  }
})

const app = new Vue({
  el: '#app'
})

<example></example>

A: The problem is that you are trying to load the component 'example' from that file but you didn't give a name to it. You should use:

Or load the component the following way (not sure if extension .vue is needed):
require('./exmaple').default();

If you are using Babel you can also load the components without giving them a name using this syntax:
import Example from ./example

Also checkout this post to get some more info in case you use Babel


Q: Programmatically Push VC on Table Row Tap I am attempting to do a onRowTap method without using a storyboard segue to push to a new View Controller, however when tapped it only displays information from the first item of the indexPath no matter which row is tapped. Here is my code:
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
    NSInteger row = [[self tableView].indexPathForSelectedRow row];
    NSDictionary *insta = [self.instaPics objectAtIndex:row];
    UIStoryboard*  sb = [UIStoryboard storyboardWithName:@"Main"
                                                  bundle:nil];
    InstaPicDetailViewController* vc = [sb instantiateViewControllerWithIdentifier:@"InstagramDetail"];
    vc.detailItem = insta;
    [self.navigationController pushViewController:vc animated:YES];
}

A: Move your deslectRowAtIndexPath message call below the assignment of your row variable:
NSInteger row = [[self tableView].indexPathForSelectedRow row];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];


Q: How to delete an entry from a Record in typescript,based on the Id I have a Main.tsx file where i have a Record ,personList,with key as PersonId and value as PersonInfo,i want to delete a particular entry from personList,based on Id provided.Below is my code:
interface PersonInfo{
FirstName:string;
SecondName:string;
Age:string;
}

const [personList,setPersonList] = useState<Record<string,PersonInfo>>({});

//For inserting entry
const Create = () => {

      setPersonList((oldList)=>{
        return {
          ...oldList,[PersonId]:PersonDescription  //PersonDescription is of type PersonInfo
        }
      });
};

const Delete = () => {

    const newPersonList :Record<string,PersonInfo>=
    personList.filter()//Here i want to delete the entry based on personId

    setPersonList(newPersonList);
 };

A: What about use delete keyword?
delete personList[personId];

A: Since you're already assigning the keys of your object to the personId you can just do:
const Delete = (id: string): void => {
    const filteredPersonList: Record<string,PersonInfo> = {}
    for(let key in personList){
        if(key !== id){
            filteredPersonList[key] = personList[key]
        }
    }
    setPersonList(filteredPersonList)
}

A: Based on the context (i.e. updating React state) and your code sample, what you're actually trying to do is create a modified copy of the record without mutating the original.

const deletePerson = (personId: string): void => {
    // first create a shallow copy of the old record.
    const newList = {...personList};
    // now delete the entry from the new record
    delete newList[personId];
    setPersonList(newList)
}

A: Eslint complains with @ehutchllew answer:
  40:7  error  for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array  no-restricted-syntax
  40:7  error  The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype                                                             guard-for-in

So using the suggested Object.{keys,values,entries}, it becomes:
const Delete = (id: string): void => {
  const filteredPersonList: Record<string, PersonInfo> = {};
  Object.keys(personList).forEach((key) => {
    if (key !== id) {
      filteredPersonList[key] = personList[key];
    }
  });
  setPersonList(filteredPersonList);
};


Q: Session and page Redirection Not working on hosted server? My php website is clearly working on localhost.When  hosted it to server page redirection doesn't works(Tested by removing all echo).But when using javascript redirection it works but missing session variables on the next page.
Then tested echo session_id(); on both pages it show different numbers.How can I solve this issue?
I handle path on server using set_include_path();method.
<!DOCTYPE html>
<?php
session_start();
ob_start();
set_include_path(".:/home/user/data");
echo session_id();
//echo ini_get('session.cookie_domain');
if($id == 'Login failed'){ header("Location: login.php?msg=Invalid Username or Password"); }
?>

A: You can not use session_start() or header() after content has been sent to the browser (<!DOCTYPE html> in your case).
Here, even if you are using ob_start() to buffer the output, what came before has not been buffered and is sent to the browser, which prevents header() and session_start()  from working.
From the PHP documentation :

To use cookie-based sessions, session_start() must be called before outputting anything to the browser.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

The fact that it works on your local computer but not on your Web hosting provider's server  is most likely due to differences between your configuration of PHP or of your Web server. For instance, output buffering may be enabled by default on your local installation (output_buffering = 4096 for instance), and be disabled on your Web hosting (output_buffering = Off).


Q: Dynamically adding files to a input I'm using this plugin: jQuery HTML5 uploader (see the demo), inside a form. I want to send uploaded files with the POST method when user submit the form.
Maybe can I create a input[type="file"], make it hidden, and dynamically add uploaded files with the plugin inside the input? It is possible?

So, if I can't do that, how can I upload files to server with this plugin, only when user click on the submit button? I know that the plugin it's already doing that with AJAX, but I want to upload them only if user clicks on a button.
Maybe should I create a variable named for example files and, when user clicks on the submit button use AJAX myself to send files and the rest of inputs data?
Something like this:
jQuery( "#dropbox" ).html5Uploader({
    onClientLoadStart: function( event, file ) {
        files[] = file;
        [...]
    }
});

[...]

jQuery("#button").on("click", function() {
    jQuery.ajax({
        data: files
    });
    [...]
});

A: You can't do that for security reasons. Just imagine the possibilities. I enter a file by JavaScript in a hidden field. You press submit. I get your file. Any file. Terrifying, right?

A:
You can not select file in file uploader because of Browser security .

User can only do this not the script .

A: this script already upload the files to the server.. what you need is a way to get back the files name/id from the server and attach them to hidden form.. than when someone submit the form you will know which files he uploaded..
youd do this by listen to the onSuccess event..

A: For security reasons you can not dynamically change the value an input field of type file. If that were possible, a malicious user could set the value to say: "c:\maliciousfile" and harm your system

A: Looks like your question is two-part:

*

*How to dynamically add files to a form using JavaScript
1a. (I'll throw in a bonus - previewing images)

*How to perform an Ajax file upload
1 Dynamically adding files to a form
What you want to do here create an <input type="file"> field and change the form value by Javascript. You can hide the input using CSS display: none;.
As far as I know, this can only be done using the FileReader API and drag and drop, and the API is limited.
You can replace and remove all files from an input but you can't append or remove individual files.
The basic drag/drop file upload looks like this:

const dropZone = document.getElementById('dropzone');
const fileInput = document.getElementById('file-input');

dropzone.addEventListener('dragover', event => {
  // we must preventDefault() to let the drop event fire
  event.preventDefault();
});
dropzone.addEventListener('drop', event => {
  event.preventDefault();
  // drag/drop files are in event.dataTransfer
  let files = event.dataTransfer.files;
  fileInput.files = files;
  console.log(`added ${files.length} files`);
});
.upload {
  border: 1px solid #eee;
  border-radius:  10px;
  padding: 20px
}

.hidden {
  opacity: 0.5;
}

Drop images here

<input type="file" id="file-input" class="hidden" />

1a Previewing files
Working with Javascript opens up some fun options for form interactions, such as previewing uploaded files.  Take for example an image uploader which can preview multiple drag-and-dropped images.

const imageTypeFilter = /image.*/;

const dropZone = document.getElementById('dropzone');
const fileInput = document.getElementById('file-input');
const previewContainer = document.getElementById('preview-container');

function generateImagePreview(file) {
    const fileReader = new FileReader();
    fileReader.addEventListener('load', event => {
      // generate an image preview
      let image = document.createElement('img');
      image.classList.add('preview-image');
      srcAttr = document.createAttribute('src');
      srcAttr.value = fileReader.result;
      image.setAttributeNode(srcAttr);
      previewContainer.append(image);
    }, false);
    // open and read the file
    fileReader.readAsDataURL(file);
}

function processFiles(files) {
  previewContainer.innerHTML = "";
  ([...files]).forEach((file, index) => {
    if (!file.type.match(imageTypeFilter)) {
      console.error("Incorrect file type:");
      console.log(file);
    } else {
      generateImagePreview(file);
    }
  });
}

dropZone.addEventListener('dragover', event => {
  // required to fire the drop event
  event.preventDefault();
});
dropZone.addEventListener('drop', event => {
  event.preventDefault();
  const files = event.dataTransfer.files;
  fileInput.files = files;
  processFiles(files);
});

fileInput.addEventListener('change', event => {
  processFiles(event.target.files);
});
.upload {
  border: 1px solid #eee;
  border-radius:  10px;
  padding: 20px
}

.preview-image {
  max-width: 100px;
  max-height: 100px;
}

.hidden {
  opacity: 0.5;
}

Drag images here

<input id="file-input" type="file" multiple accept="image/jpeg,image/png,image/gif" class="hidden" />

2 Perform an AJAX upload when the user clicks the submit button.
In this case, you want to override the default the form submit event which I believe would look something like this:

const submitUrl = 'https://httpbin.org/post';
const form = document.getElementById('ajax-form');

form.addEventListener('submit', event => {
  // this line prevents the default submit
  event.preventDefault();
  // convert the form into POST data
  const serializedFormData = new FormData(event.target);

  // use your favorite AJAX library
  axios.post(
    submitUrl,
    serializedFormData
  ).then(response => {
    console.log("success!");
  }).catch(error => {
    console.log("falied");
    console.log(error.response);
  });
});

<form id="ajax-form" method="post" enctype="multipart/form-data">
    <input type="text" name="name"/>
    <input name="file" type="file" />
    <button type="submit">Submit</button>
</form>


Q: How to compare if an item in a list has the same value AND position as an item in another list? Python 2.7 eg.
l1 = [a,b,c,d]
l2 = [e,b,f,g]

A method that would return true when it sees that b is in both l1 and l2, and in position [1] in both lists. Preferably something that I can use in a for loop so that I can compare all the items in the list.
Many thanks :)

A: Try this code:
if 'b' in l1 and 'b' in l2: # Separated both statements to prevent ValueErrors
    if l1.index('b') == l2.index('b'):
        print 'b is in both lists and same position!'

Unlike Volatility's code, the length in either list doesn't matter.
The index() function gets the position of an element in a string. For example, if there was:
>>> mylist = ['hai', 'hello', 'hey']
>>> print mylist.index('hello')
1

A: You can do:
def has_equal_element(list1, list2):
    return any(e1 == e2 for e1, e2 in zip(list1, list2))

This function will return True when at least one element has the same value and position as in the other list. This function also works when the lists differ in length, you'll need to adjust the function if that's not desired.

A: Assuming the lists are the same length, you could use the zip function
for i, j in zip(l1, l2):
    if i == j:
        print '{0} and {1} are equal and in the same position'.format(i, j)

What the zip function does is something like this:
l1 = [1, 2, 3]
l2 = [2, 3, 4]
print zip(l1, l2)
# [(1, 2), (2, 3), (3, 4)]

If you want a function that returns True or False given an input, you could do this
def some_func(your_input, l1, l2):
    return (your_input,)*2 in zip(l1, l2)

(your_input,) is a one-tuple containing your_input, and multiplying it by two makes it (your_input, your_input) - which is what you want to test for.
Or if you want the return True if any satisfy the condition
def some_func(l1, l2):
    return any(i == j for i, j in zip(l1, l2))

The any function basically checks if any of the elements of a list (or in this case a generator) are True in a boolean context, so in this case it returns true if two lists satisfy your condition.

A: If you actually want a method to compare one position in two lists you can use the following:
def compare_pos(l1, l2, pos):
    try:
        return l1[pos] == l2[pos]
    except IndexError:
        return False

l1 = [0, 1, 2, 3]
l2 = [0, 2, 2, 4]

for i, _ in enumerate(l1):
    print i, compare_pos(l1, l2, i)

# Output:
# 0 True
# 1 False
# 2 True
# 3 False

If you want to test whether two lists have all the same elements in the same positions you can just check for equality:
print l1 == l2

A: I'd get common elements from both lists:
l1 = [a, b, c, d]
l2 = [e, b, f, g]
common_elements = [(i, v) for i,v in enumerate(l1) if l2[i] == v]

This will create a list of tuples: (index, value) and then you can just check if your desired value or index is in the list.


Q: Disadvantages of using multiple


Q: Is there a way to crack or bypass the VBA project password with Excel 2011 Mac edition? There are several good sources (referenced below) that demonstrate how to bypass VBA project passwords for Windows versions of Excel. But, none of these work for Excel 2011 for Mac.
Is there a way to achieve the same result with Excel 2011 for Mac?
References:
Is there a way to crack the password on an Excel VBA Project?
https://superuser.com/questions/807926/how-to-bypass-the-vba-project-password-from-excel


Q: How can I change a color channel in an image using numpy? I have an image where some color channels in the pixels have a value of zero (ie 255, 146, 0). I want to be able to change any value equal to zero in the array to a different value, but I do not know how to access these values. Any help with this?
This is the image array:
[[[ 76 163 168]
  [109 166 168]
  [173 172 167]
  ...,
  [ 83 182 144]
  [ 78 172 134]
  [ 82 150 131]]

 [[ 51 151 168]
  [ 99 157 171]
  [173 195 159]
  ...,
  [ 56 165 144]
  [ 25 198 125]
  [ 35 185 121]]

 [[ 76 163 121]
  [112 147 120]
  [175 151 118]
  ...,
  [ 57 162 159]
  [ 36 185 132]
  [ 32 194  97]]

 ...,
 [[ 78 189 126]
  [ 68 173 129]
  [ 58 171 150]
  ...,
  [ 41 188 163]
  [ 34 176 126]
  [ 35 176 102]]

 [[131 155 161]
  [101 141 161]
  [ 42 151 177]
  ...,
  [ 56 178 122]
  [ 45 192 114]
  [ 46 184 112]]

 [[130 157 185]
  [ 83 141 185]
  [ 42 158 185]
  ...,
  [ 63 187  88]
  [ 45 194 102]
  [ 45 184 129]]]

A: Use masking -
img[(img==zero_val).all(-1)] = new_val

, where zero_val is the zero color and new_val is the new color to be assigned at those places where we have zero colored pixels.
Sample run -
# Random image array
In [112]: img = np.random.randint(0,255,(4,5,3))

# Define sample zero valued and new valued arrays
In [113]: zero_val = [255,146,0]
     ...: new_val = [255,255,255]
     ...:

# Set two random points/pixels to be zero valued
In [114]: img[0,2] = zero_val

In [115]: img[2,3] = zero_val

# Use proposed approach
In [116]: img[(img==zero_val).all(-1)] = new_val

# Verify that new values have been assigned
In [117]: img[0,2]
Out[117]: array([255, 255, 255])

In [118]: img[2,3]
Out[118]: array([255, 255, 255])


Q: NASM: move from memory to memory via registers I am difficulties moving data from memory to another memory in bss. My implementation somewhat works however when moving some weird characters appear in the first couple bytes and half of my string is also missing while the other half is fine.
This is the value I get when I print out message == �F@elcome to the new life
I need all the help, what am I missing? I went over my code a hundred times.
    section .data
hello:       db  "Hello, Welcome to the new life! Lets begin the journey.",10
hello_len:   equ  $ - hello

    section .bss
message: resb 255

    section .text

mov rdi, hello
mov rsi, message

msg_into_message:
    cmp byte [rdi], 10          ; hello ends with a new line char
    je end_count
    mov al, byte [rdi]
    mov byte [rsi], al
    inc rsi
    inc rdi
    jmp msg_into_message

end_count:
    mov [message], rsi
    ret

    ; Prints message
    mov rsi, message
    mov rdx, hello_len
    call pre_print
    syscall

A: Okay, first things first, the s and d in rsi and rdi stand for source and destination. It may work the other way (as you have it) but you'll upset a lot of CDO people like myself(a) :-)
But, for your actual problem, look here:
end_count:
    mov [message], rsi

I assume that's meant to copy the final byte 0x10 into the destination but there are two problems:

*

*message is the start of the buffer, not the position where the byte should go.

*You're copying the multi-byte rsi variable into there, not the byte you need.

Those two points mean that you're putting some weird value into the first few bytes, as your symptoms suggest.
Perhaps a better way to do it would be as follows:
    mov rsi, hello            ; as Gordon Moore intended :-)
    mov rdi, message

put_str_into_message:
    mov al, byte [rsi]        ; get byte, increment src ptr.
    inc rsi

    mov byte [rdi], al        ; put byte, increment dst ptr.
    inc rdi

    cmp al, 10                ; continue until newline.
    jne put_str_into_message

    ret

For completeness, if you didn't want the newline copied (though this is pretty much what you have now, just with the errant buffer-damaging mov taken away) (b):
put_str_into_message:
    mov al, byte [rsi]        ; get byte.
    cmp al, 10                ; stop before newline.
    je  stop_str

    mov byte [rdi], al        ; put byte, increment pointers.
    inc rsi
    inc rdi

    jmp put_str_into_message

stop_str:
    ret

(a) CDO is obsessive-compulsive disorder, but with the letters arranged correctly :-)

(b) Or the don't-copy-newline loop can be done more efficiently, while still having a single branch at the bottom.
Looping one byte at a time is still very inefficient (x86-64 has SSE2 which lets you copy and check 16 bytes at a time). Since you have the length as an assemble-time constant hello_len, you could use that to efficiently copy in wide chunks (possibly needing special handling at the end if your buffer size is not a multiple of 16), or with rep movsb.
But this demonstrates an efficient loop structure, avoiding the false dependency of merging a new AL into the bottom of RAX, allowing out-of-order exec to run ahead and "see" the loop exit branch earlier.
strcpy_newline_end:
    movzx  eax, byte [rsi]    ; get byte (without false dependency).
    cmp    al, 10
    je    copy_done           ; first byte isn't newline, enter loop.

copy_loop:                    ; do:
    mov    [rdi], al          ;    put byte.
    inc    rsi                ;    increment both pointers.
    inc    rdi
    movzx  eax, byte [rsi]    ;    get next byte.
    cmp    al, 10
    jne   copy_loop           ; until you get a newline.

; After falling out of the loop (or jumping here from the top)
; we've loaded but *not* stored the terminating newline

copy_done:
    ret

You should also be aware there are other tricks you can use, to save instructions inside the loop, such as addressing one string relative to the other (with an indexed addressing mode for the load, only incrementing one pointer).
However, we won't cover them in detail here as it risks making the answer more complex than it needs to be.


Q: Why does average damping magically speed up the convergence of fixed-point calculators? I'm reading through SICP, and the authors brush over the technique of average damping in computing the fixed points of functions. I understand that it's necessary in certain cases, ie square roots in order to damp out the oscillation of the function y = x/y however, I don't understand why it magically aids the convergence of the fixed point calculating function. Help?
edit
Obviously, I've thought this through somewhat. I can't seem to wrap my head around why averaging a function with itself would speed up convergence when applied repeatedly.

A: While I can't answer your question on a mathematical basis, I'll try on an intuitive one:
fixpoint techniques need a "flat" function graph around their ..well.. fixpoint. This means: if you picture your fixpoint function on an X-Y chart, you'll see that the function crosses the diagonal (+x,+y) exactly at the true result. In one step of your fixpoint algorithm you are guessing an X value which needs to be within the interval around the intersection point where the first derivative is between (-1..+1) and take the Y value. The Y that you took will be closer to the intersection point because starting from the intersection it is reachable by following a path which has a smaller slope than +/-1 , in contrast to the previous X value that you utilized, which has in this sense, the exact slope -1. It is immediately clear now that the smaller the slope, the more way you make towards the intersection point (the true function value) when using the Y as new X. The best interpolation function is trivially a constant, which has slope 0, giving you the true value in the first step.
Sorry to all mathematicians.

A: It only speeds up those functions whose repeated applications "hop around" the fixpoint. Intuitively, it's like adding a brake to a pendulum - it'll stop sooner with the brake.
But not every function has this property. Consider f(x)=x/2. This function will converge sooner without the average damping (log base 2 steps vs log base (4/3) steps), because it approaches the fixpoint from one side.